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 overloading is allowed for a new function 1464 /// declaration considering prior declarations of the same name. 1465 /// 1466 /// This routine determines whether overloading is possible, not 1467 /// whether a new declaration actually overloads a previous one. 1468 /// It will return true in C++ (where overloads are alway permitted) 1469 /// or, as a C extension, when either the new declaration or a 1470 /// previous one is declared with the 'overloadable' attribute. 1471 static bool AllowOverloadingOfFunction(const LookupResult &Previous, 1472 ASTContext &Context, 1473 const FunctionDecl *New) { 1474 if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>()) 1475 return true; 1476 1477 // Multiversion function declarations are not overloads in the 1478 // usual sense of that term, but lookup will report that an 1479 // overload set was found if more than one multiversion function 1480 // declaration is present for the same name. It is therefore 1481 // inadequate to assume that some prior declaration(s) had 1482 // the overloadable attribute; checking is required. Since one 1483 // declaration is permitted to omit the attribute, it is necessary 1484 // to check at least two; hence the 'any_of' check below. Note that 1485 // the overloadable attribute is implicitly added to declarations 1486 // that were required to have it but did not. 1487 if (Previous.getResultKind() == LookupResult::FoundOverloaded) { 1488 return llvm::any_of(Previous, [](const NamedDecl *ND) { 1489 return ND->hasAttr<OverloadableAttr>(); 1490 }); 1491 } else if (Previous.getResultKind() == LookupResult::Found) 1492 return Previous.getFoundDecl()->hasAttr<OverloadableAttr>(); 1493 1494 return false; 1495 } 1496 1497 /// Add this decl to the scope shadowed decl chains. 1498 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1499 // Move up the scope chain until we find the nearest enclosing 1500 // non-transparent context. The declaration will be introduced into this 1501 // scope. 1502 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1503 S = S->getParent(); 1504 1505 // Add scoped declarations into their context, so that they can be 1506 // found later. Declarations without a context won't be inserted 1507 // into any context. 1508 if (AddToContext) 1509 CurContext->addDecl(D); 1510 1511 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1512 // are function-local declarations. 1513 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent()) 1514 return; 1515 1516 // Template instantiations should also not be pushed into scope. 1517 if (isa<FunctionDecl>(D) && 1518 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1519 return; 1520 1521 // If this replaces anything in the current scope, 1522 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1523 IEnd = IdResolver.end(); 1524 for (; I != IEnd; ++I) { 1525 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1526 S->RemoveDecl(*I); 1527 IdResolver.RemoveDecl(*I); 1528 1529 // Should only need to replace one decl. 1530 break; 1531 } 1532 } 1533 1534 S->AddDecl(D); 1535 1536 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1537 // Implicitly-generated labels may end up getting generated in an order that 1538 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1539 // the label at the appropriate place in the identifier chain. 1540 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1541 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1542 if (IDC == CurContext) { 1543 if (!S->isDeclScope(*I)) 1544 continue; 1545 } else if (IDC->Encloses(CurContext)) 1546 break; 1547 } 1548 1549 IdResolver.InsertDeclAfter(I, D); 1550 } else { 1551 IdResolver.AddDecl(D); 1552 } 1553 warnOnReservedIdentifier(D); 1554 } 1555 1556 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1557 bool AllowInlineNamespace) { 1558 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1559 } 1560 1561 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1562 DeclContext *TargetDC = DC->getPrimaryContext(); 1563 do { 1564 if (DeclContext *ScopeDC = S->getEntity()) 1565 if (ScopeDC->getPrimaryContext() == TargetDC) 1566 return S; 1567 } while ((S = S->getParent())); 1568 1569 return nullptr; 1570 } 1571 1572 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1573 DeclContext*, 1574 ASTContext&); 1575 1576 /// Filters out lookup results that don't fall within the given scope 1577 /// as determined by isDeclInScope. 1578 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1579 bool ConsiderLinkage, 1580 bool AllowInlineNamespace) { 1581 LookupResult::Filter F = R.makeFilter(); 1582 while (F.hasNext()) { 1583 NamedDecl *D = F.next(); 1584 1585 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1586 continue; 1587 1588 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1589 continue; 1590 1591 F.erase(); 1592 } 1593 1594 F.done(); 1595 } 1596 1597 /// We've determined that \p New is a redeclaration of \p Old. Check that they 1598 /// have compatible owning modules. 1599 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) { 1600 // [module.interface]p7: 1601 // A declaration is attached to a module as follows: 1602 // - If the declaration is a non-dependent friend declaration that nominates a 1603 // function with a declarator-id that is a qualified-id or template-id or that 1604 // nominates a class other than with an elaborated-type-specifier with neither 1605 // a nested-name-specifier nor a simple-template-id, it is attached to the 1606 // module to which the friend is attached ([basic.link]). 1607 if (New->getFriendObjectKind() && 1608 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) { 1609 New->setLocalOwningModule(Old->getOwningModule()); 1610 makeMergedDefinitionVisible(New); 1611 return false; 1612 } 1613 1614 Module *NewM = New->getOwningModule(); 1615 Module *OldM = Old->getOwningModule(); 1616 1617 if (NewM && NewM->Kind == Module::PrivateModuleFragment) 1618 NewM = NewM->Parent; 1619 if (OldM && OldM->Kind == Module::PrivateModuleFragment) 1620 OldM = OldM->Parent; 1621 1622 // If we have a decl in a module partition, it is part of the containing 1623 // module (which is the only thing that can be importing it). 1624 if (NewM && OldM && 1625 (OldM->Kind == Module::ModulePartitionInterface || 1626 OldM->Kind == Module::ModulePartitionImplementation)) { 1627 return false; 1628 } 1629 1630 if (NewM == OldM) 1631 return false; 1632 1633 bool NewIsModuleInterface = NewM && NewM->isModulePurview(); 1634 bool OldIsModuleInterface = OldM && OldM->isModulePurview(); 1635 if (NewIsModuleInterface || OldIsModuleInterface) { 1636 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]: 1637 // if a declaration of D [...] appears in the purview of a module, all 1638 // other such declarations shall appear in the purview of the same module 1639 Diag(New->getLocation(), diag::err_mismatched_owning_module) 1640 << New 1641 << NewIsModuleInterface 1642 << (NewIsModuleInterface ? NewM->getFullModuleName() : "") 1643 << OldIsModuleInterface 1644 << (OldIsModuleInterface ? OldM->getFullModuleName() : ""); 1645 Diag(Old->getLocation(), diag::note_previous_declaration); 1646 New->setInvalidDecl(); 1647 return true; 1648 } 1649 1650 return false; 1651 } 1652 1653 // [module.interface]p6: 1654 // A redeclaration of an entity X is implicitly exported if X was introduced by 1655 // an exported declaration; otherwise it shall not be exported. 1656 bool Sema::CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old) { 1657 // [module.interface]p1: 1658 // An export-declaration shall inhabit a namespace scope. 1659 // 1660 // So it is meaningless to talk about redeclaration which is not at namespace 1661 // scope. 1662 if (!New->getLexicalDeclContext() 1663 ->getNonTransparentContext() 1664 ->isFileContext() || 1665 !Old->getLexicalDeclContext() 1666 ->getNonTransparentContext() 1667 ->isFileContext()) 1668 return false; 1669 1670 bool IsNewExported = New->isInExportDeclContext(); 1671 bool IsOldExported = Old->isInExportDeclContext(); 1672 1673 // It should be irrevelant if both of them are not exported. 1674 if (!IsNewExported && !IsOldExported) 1675 return false; 1676 1677 if (IsOldExported) 1678 return false; 1679 1680 assert(IsNewExported); 1681 1682 auto Lk = Old->getFormalLinkage(); 1683 int S = 0; 1684 if (Lk == Linkage::InternalLinkage) 1685 S = 1; 1686 else if (Lk == Linkage::ModuleLinkage) 1687 S = 2; 1688 Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S; 1689 Diag(Old->getLocation(), diag::note_previous_declaration); 1690 return true; 1691 } 1692 1693 // A wrapper function for checking the semantic restrictions of 1694 // a redeclaration within a module. 1695 bool Sema::CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old) { 1696 if (CheckRedeclarationModuleOwnership(New, Old)) 1697 return true; 1698 1699 if (CheckRedeclarationExported(New, Old)) 1700 return true; 1701 1702 return false; 1703 } 1704 1705 static bool isUsingDecl(NamedDecl *D) { 1706 return isa<UsingShadowDecl>(D) || 1707 isa<UnresolvedUsingTypenameDecl>(D) || 1708 isa<UnresolvedUsingValueDecl>(D); 1709 } 1710 1711 /// Removes using shadow declarations from the lookup results. 1712 static void RemoveUsingDecls(LookupResult &R) { 1713 LookupResult::Filter F = R.makeFilter(); 1714 while (F.hasNext()) 1715 if (isUsingDecl(F.next())) 1716 F.erase(); 1717 1718 F.done(); 1719 } 1720 1721 /// Check for this common pattern: 1722 /// @code 1723 /// class S { 1724 /// S(const S&); // DO NOT IMPLEMENT 1725 /// void operator=(const S&); // DO NOT IMPLEMENT 1726 /// }; 1727 /// @endcode 1728 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1729 // FIXME: Should check for private access too but access is set after we get 1730 // the decl here. 1731 if (D->doesThisDeclarationHaveABody()) 1732 return false; 1733 1734 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1735 return CD->isCopyConstructor(); 1736 return D->isCopyAssignmentOperator(); 1737 } 1738 1739 // We need this to handle 1740 // 1741 // typedef struct { 1742 // void *foo() { return 0; } 1743 // } A; 1744 // 1745 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1746 // for example. If 'A', foo will have external linkage. If we have '*A', 1747 // foo will have no linkage. Since we can't know until we get to the end 1748 // of the typedef, this function finds out if D might have non-external linkage. 1749 // Callers should verify at the end of the TU if it D has external linkage or 1750 // not. 1751 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1752 const DeclContext *DC = D->getDeclContext(); 1753 while (!DC->isTranslationUnit()) { 1754 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1755 if (!RD->hasNameForLinkage()) 1756 return true; 1757 } 1758 DC = DC->getParent(); 1759 } 1760 1761 return !D->isExternallyVisible(); 1762 } 1763 1764 // FIXME: This needs to be refactored; some other isInMainFile users want 1765 // these semantics. 1766 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1767 if (S.TUKind != TU_Complete) 1768 return false; 1769 return S.SourceMgr.isInMainFile(Loc); 1770 } 1771 1772 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1773 assert(D); 1774 1775 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1776 return false; 1777 1778 // Ignore all entities declared within templates, and out-of-line definitions 1779 // of members of class templates. 1780 if (D->getDeclContext()->isDependentContext() || 1781 D->getLexicalDeclContext()->isDependentContext()) 1782 return false; 1783 1784 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1785 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1786 return false; 1787 // A non-out-of-line declaration of a member specialization was implicitly 1788 // instantiated; it's the out-of-line declaration that we're interested in. 1789 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1790 FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) 1791 return false; 1792 1793 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1794 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1795 return false; 1796 } else { 1797 // 'static inline' functions are defined in headers; don't warn. 1798 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1799 return false; 1800 } 1801 1802 if (FD->doesThisDeclarationHaveABody() && 1803 Context.DeclMustBeEmitted(FD)) 1804 return false; 1805 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1806 // Constants and utility variables are defined in headers with internal 1807 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1808 // like "inline".) 1809 if (!isMainFileLoc(*this, VD->getLocation())) 1810 return false; 1811 1812 if (Context.DeclMustBeEmitted(VD)) 1813 return false; 1814 1815 if (VD->isStaticDataMember() && 1816 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1817 return false; 1818 if (VD->isStaticDataMember() && 1819 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1820 VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) 1821 return false; 1822 1823 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) 1824 return false; 1825 } else { 1826 return false; 1827 } 1828 1829 // Only warn for unused decls internal to the translation unit. 1830 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1831 // for inline functions defined in the main source file, for instance. 1832 return mightHaveNonExternalLinkage(D); 1833 } 1834 1835 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1836 if (!D) 1837 return; 1838 1839 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1840 const FunctionDecl *First = FD->getFirstDecl(); 1841 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1842 return; // First should already be in the vector. 1843 } 1844 1845 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1846 const VarDecl *First = VD->getFirstDecl(); 1847 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1848 return; // First should already be in the vector. 1849 } 1850 1851 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1852 UnusedFileScopedDecls.push_back(D); 1853 } 1854 1855 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1856 if (D->isInvalidDecl()) 1857 return false; 1858 1859 if (auto *DD = dyn_cast<DecompositionDecl>(D)) { 1860 // For a decomposition declaration, warn if none of the bindings are 1861 // referenced, instead of if the variable itself is referenced (which 1862 // it is, by the bindings' expressions). 1863 for (auto *BD : DD->bindings()) 1864 if (BD->isReferenced()) 1865 return false; 1866 } else if (!D->getDeclName()) { 1867 return false; 1868 } else if (D->isReferenced() || D->isUsed()) { 1869 return false; 1870 } 1871 1872 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>()) 1873 return false; 1874 1875 if (isa<LabelDecl>(D)) 1876 return true; 1877 1878 // Except for labels, we only care about unused decls that are local to 1879 // functions. 1880 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1881 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1882 // For dependent types, the diagnostic is deferred. 1883 WithinFunction = 1884 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1885 if (!WithinFunction) 1886 return false; 1887 1888 if (isa<TypedefNameDecl>(D)) 1889 return true; 1890 1891 // White-list anything that isn't a local variable. 1892 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1893 return false; 1894 1895 // Types of valid local variables should be complete, so this should succeed. 1896 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1897 1898 const Expr *Init = VD->getInit(); 1899 if (const auto *Cleanups = dyn_cast_or_null<ExprWithCleanups>(Init)) 1900 Init = Cleanups->getSubExpr(); 1901 1902 const auto *Ty = VD->getType().getTypePtr(); 1903 1904 // Only look at the outermost level of typedef. 1905 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1906 // Allow anything marked with __attribute__((unused)). 1907 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1908 return false; 1909 } 1910 1911 // Warn for reference variables whose initializtion performs lifetime 1912 // extension. 1913 if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>(Init)) { 1914 if (MTE->getExtendingDecl()) { 1915 Ty = VD->getType().getNonReferenceType().getTypePtr(); 1916 Init = MTE->getSubExpr()->IgnoreImplicitAsWritten(); 1917 } 1918 } 1919 1920 // If we failed to complete the type for some reason, or if the type is 1921 // dependent, don't diagnose the variable. 1922 if (Ty->isIncompleteType() || Ty->isDependentType()) 1923 return false; 1924 1925 // Look at the element type to ensure that the warning behaviour is 1926 // consistent for both scalars and arrays. 1927 Ty = Ty->getBaseElementTypeUnsafe(); 1928 1929 if (const TagType *TT = Ty->getAs<TagType>()) { 1930 const TagDecl *Tag = TT->getDecl(); 1931 if (Tag->hasAttr<UnusedAttr>()) 1932 return false; 1933 1934 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1935 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1936 return false; 1937 1938 if (Init) { 1939 const CXXConstructExpr *Construct = 1940 dyn_cast<CXXConstructExpr>(Init); 1941 if (Construct && !Construct->isElidable()) { 1942 CXXConstructorDecl *CD = Construct->getConstructor(); 1943 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() && 1944 (VD->getInit()->isValueDependent() || !VD->evaluateValue())) 1945 return false; 1946 } 1947 1948 // Suppress the warning if we don't know how this is constructed, and 1949 // it could possibly be non-trivial constructor. 1950 if (Init->isTypeDependent()) { 1951 for (const CXXConstructorDecl *Ctor : RD->ctors()) 1952 if (!Ctor->isTrivial()) 1953 return false; 1954 } 1955 1956 // Suppress the warning if the constructor is unresolved because 1957 // its arguments are dependent. 1958 if (isa<CXXUnresolvedConstructExpr>(Init)) 1959 return false; 1960 } 1961 } 1962 } 1963 1964 // TODO: __attribute__((unused)) templates? 1965 } 1966 1967 return true; 1968 } 1969 1970 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1971 FixItHint &Hint) { 1972 if (isa<LabelDecl>(D)) { 1973 SourceLocation AfterColon = Lexer::findLocationAfterToken( 1974 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), 1975 true); 1976 if (AfterColon.isInvalid()) 1977 return; 1978 Hint = FixItHint::CreateRemoval( 1979 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon)); 1980 } 1981 } 1982 1983 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1984 if (D->getTypeForDecl()->isDependentType()) 1985 return; 1986 1987 for (auto *TmpD : D->decls()) { 1988 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1989 DiagnoseUnusedDecl(T); 1990 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1991 DiagnoseUnusedNestedTypedefs(R); 1992 } 1993 } 1994 1995 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1996 /// unless they are marked attr(unused). 1997 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1998 if (!ShouldDiagnoseUnusedDecl(D)) 1999 return; 2000 2001 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 2002 // typedefs can be referenced later on, so the diagnostics are emitted 2003 // at end-of-translation-unit. 2004 UnusedLocalTypedefNameCandidates.insert(TD); 2005 return; 2006 } 2007 2008 FixItHint Hint; 2009 GenerateFixForUnusedDecl(D, Context, Hint); 2010 2011 unsigned DiagID; 2012 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 2013 DiagID = diag::warn_unused_exception_param; 2014 else if (isa<LabelDecl>(D)) 2015 DiagID = diag::warn_unused_label; 2016 else 2017 DiagID = diag::warn_unused_variable; 2018 2019 Diag(D->getLocation(), DiagID) << D << Hint; 2020 } 2021 2022 void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD) { 2023 // If it's not referenced, it can't be set. If it has the Cleanup attribute, 2024 // it's not really unused. 2025 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<UnusedAttr>() || 2026 VD->hasAttr<CleanupAttr>()) 2027 return; 2028 2029 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe(); 2030 2031 if (Ty->isReferenceType() || Ty->isDependentType()) 2032 return; 2033 2034 if (const TagType *TT = Ty->getAs<TagType>()) { 2035 const TagDecl *Tag = TT->getDecl(); 2036 if (Tag->hasAttr<UnusedAttr>()) 2037 return; 2038 // In C++, don't warn for record types that don't have WarnUnusedAttr, to 2039 // mimic gcc's behavior. 2040 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 2041 if (!RD->hasAttr<WarnUnusedAttr>()) 2042 return; 2043 } 2044 } 2045 2046 // Don't warn about __block Objective-C pointer variables, as they might 2047 // be assigned in the block but not used elsewhere for the purpose of lifetime 2048 // extension. 2049 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType()) 2050 return; 2051 2052 // Don't warn about Objective-C pointer variables with precise lifetime 2053 // semantics; they can be used to ensure ARC releases the object at a known 2054 // time, which may mean assignment but no other references. 2055 if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType()) 2056 return; 2057 2058 auto iter = RefsMinusAssignments.find(VD); 2059 if (iter == RefsMinusAssignments.end()) 2060 return; 2061 2062 assert(iter->getSecond() >= 0 && 2063 "Found a negative number of references to a VarDecl"); 2064 if (iter->getSecond() != 0) 2065 return; 2066 unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter 2067 : diag::warn_unused_but_set_variable; 2068 Diag(VD->getLocation(), DiagID) << VD; 2069 } 2070 2071 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 2072 // Verify that we have no forward references left. If so, there was a goto 2073 // or address of a label taken, but no definition of it. Label fwd 2074 // definitions are indicated with a null substmt which is also not a resolved 2075 // MS inline assembly label name. 2076 bool Diagnose = false; 2077 if (L->isMSAsmLabel()) 2078 Diagnose = !L->isResolvedMSAsmLabel(); 2079 else 2080 Diagnose = L->getStmt() == nullptr; 2081 if (Diagnose) 2082 S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L; 2083 } 2084 2085 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 2086 S->mergeNRVOIntoParent(); 2087 2088 if (S->decl_empty()) return; 2089 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 2090 "Scope shouldn't contain decls!"); 2091 2092 for (auto *TmpD : S->decls()) { 2093 assert(TmpD && "This decl didn't get pushed??"); 2094 2095 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 2096 NamedDecl *D = cast<NamedDecl>(TmpD); 2097 2098 // Diagnose unused variables in this scope. 2099 if (!S->hasUnrecoverableErrorOccurred()) { 2100 DiagnoseUnusedDecl(D); 2101 if (const auto *RD = dyn_cast<RecordDecl>(D)) 2102 DiagnoseUnusedNestedTypedefs(RD); 2103 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 2104 DiagnoseUnusedButSetDecl(VD); 2105 RefsMinusAssignments.erase(VD); 2106 } 2107 } 2108 2109 if (!D->getDeclName()) continue; 2110 2111 // If this was a forward reference to a label, verify it was defined. 2112 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 2113 CheckPoppedLabel(LD, *this); 2114 2115 // Remove this name from our lexical scope, and warn on it if we haven't 2116 // already. 2117 IdResolver.RemoveDecl(D); 2118 auto ShadowI = ShadowingDecls.find(D); 2119 if (ShadowI != ShadowingDecls.end()) { 2120 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { 2121 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) 2122 << D << FD << FD->getParent(); 2123 Diag(FD->getLocation(), diag::note_previous_declaration); 2124 } 2125 ShadowingDecls.erase(ShadowI); 2126 } 2127 } 2128 } 2129 2130 /// Look for an Objective-C class in the translation unit. 2131 /// 2132 /// \param Id The name of the Objective-C class we're looking for. If 2133 /// typo-correction fixes this name, the Id will be updated 2134 /// to the fixed name. 2135 /// 2136 /// \param IdLoc The location of the name in the translation unit. 2137 /// 2138 /// \param DoTypoCorrection If true, this routine will attempt typo correction 2139 /// if there is no class with the given name. 2140 /// 2141 /// \returns The declaration of the named Objective-C class, or NULL if the 2142 /// class could not be found. 2143 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 2144 SourceLocation IdLoc, 2145 bool DoTypoCorrection) { 2146 // The third "scope" argument is 0 since we aren't enabling lazy built-in 2147 // creation from this context. 2148 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 2149 2150 if (!IDecl && DoTypoCorrection) { 2151 // Perform typo correction at the given location, but only if we 2152 // find an Objective-C class name. 2153 DeclFilterCCC<ObjCInterfaceDecl> CCC{}; 2154 if (TypoCorrection C = 2155 CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, 2156 TUScope, nullptr, CCC, CTK_ErrorRecovery)) { 2157 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 2158 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 2159 Id = IDecl->getIdentifier(); 2160 } 2161 } 2162 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 2163 // This routine must always return a class definition, if any. 2164 if (Def && Def->getDefinition()) 2165 Def = Def->getDefinition(); 2166 return Def; 2167 } 2168 2169 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 2170 /// from S, where a non-field would be declared. This routine copes 2171 /// with the difference between C and C++ scoping rules in structs and 2172 /// unions. For example, the following code is well-formed in C but 2173 /// ill-formed in C++: 2174 /// @code 2175 /// struct S6 { 2176 /// enum { BAR } e; 2177 /// }; 2178 /// 2179 /// void test_S6() { 2180 /// struct S6 a; 2181 /// a.e = BAR; 2182 /// } 2183 /// @endcode 2184 /// For the declaration of BAR, this routine will return a different 2185 /// scope. The scope S will be the scope of the unnamed enumeration 2186 /// within S6. In C++, this routine will return the scope associated 2187 /// with S6, because the enumeration's scope is a transparent 2188 /// context but structures can contain non-field names. In C, this 2189 /// routine will return the translation unit scope, since the 2190 /// enumeration's scope is a transparent context and structures cannot 2191 /// contain non-field names. 2192 Scope *Sema::getNonFieldDeclScope(Scope *S) { 2193 while (((S->getFlags() & Scope::DeclScope) == 0) || 2194 (S->getEntity() && S->getEntity()->isTransparentContext()) || 2195 (S->isClassScope() && !getLangOpts().CPlusPlus)) 2196 S = S->getParent(); 2197 return S; 2198 } 2199 2200 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, 2201 ASTContext::GetBuiltinTypeError Error) { 2202 switch (Error) { 2203 case ASTContext::GE_None: 2204 return ""; 2205 case ASTContext::GE_Missing_type: 2206 return BuiltinInfo.getHeaderName(ID); 2207 case ASTContext::GE_Missing_stdio: 2208 return "stdio.h"; 2209 case ASTContext::GE_Missing_setjmp: 2210 return "setjmp.h"; 2211 case ASTContext::GE_Missing_ucontext: 2212 return "ucontext.h"; 2213 } 2214 llvm_unreachable("unhandled error kind"); 2215 } 2216 2217 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type, 2218 unsigned ID, SourceLocation Loc) { 2219 DeclContext *Parent = Context.getTranslationUnitDecl(); 2220 2221 if (getLangOpts().CPlusPlus) { 2222 LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create( 2223 Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false); 2224 CLinkageDecl->setImplicit(); 2225 Parent->addDecl(CLinkageDecl); 2226 Parent = CLinkageDecl; 2227 } 2228 2229 FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type, 2230 /*TInfo=*/nullptr, SC_Extern, 2231 getCurFPFeatures().isFPConstrained(), 2232 false, Type->isFunctionProtoType()); 2233 New->setImplicit(); 2234 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID)); 2235 2236 // Create Decl objects for each parameter, adding them to the 2237 // FunctionDecl. 2238 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) { 2239 SmallVector<ParmVarDecl *, 16> Params; 2240 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 2241 ParmVarDecl *parm = ParmVarDecl::Create( 2242 Context, New, SourceLocation(), SourceLocation(), nullptr, 2243 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr); 2244 parm->setScopeInfo(0, i); 2245 Params.push_back(parm); 2246 } 2247 New->setParams(Params); 2248 } 2249 2250 AddKnownFunctionAttributes(New); 2251 return New; 2252 } 2253 2254 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 2255 /// file scope. lazily create a decl for it. ForRedeclaration is true 2256 /// if we're creating this built-in in anticipation of redeclaring the 2257 /// built-in. 2258 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 2259 Scope *S, bool ForRedeclaration, 2260 SourceLocation Loc) { 2261 LookupNecessaryTypesForBuiltin(S, ID); 2262 2263 ASTContext::GetBuiltinTypeError Error; 2264 QualType R = Context.GetBuiltinType(ID, Error); 2265 if (Error) { 2266 if (!ForRedeclaration) 2267 return nullptr; 2268 2269 // If we have a builtin without an associated type we should not emit a 2270 // warning when we were not able to find a type for it. 2271 if (Error == ASTContext::GE_Missing_type || 2272 Context.BuiltinInfo.allowTypeMismatch(ID)) 2273 return nullptr; 2274 2275 // If we could not find a type for setjmp it is because the jmp_buf type was 2276 // not defined prior to the setjmp declaration. 2277 if (Error == ASTContext::GE_Missing_setjmp) { 2278 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf) 2279 << Context.BuiltinInfo.getName(ID); 2280 return nullptr; 2281 } 2282 2283 // Generally, we emit a warning that the declaration requires the 2284 // appropriate header. 2285 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 2286 << getHeaderName(Context.BuiltinInfo, ID, Error) 2287 << Context.BuiltinInfo.getName(ID); 2288 return nullptr; 2289 } 2290 2291 if (!ForRedeclaration && 2292 (Context.BuiltinInfo.isPredefinedLibFunction(ID) || 2293 Context.BuiltinInfo.isHeaderDependentFunction(ID))) { 2294 Diag(Loc, diag::ext_implicit_lib_function_decl) 2295 << Context.BuiltinInfo.getName(ID) << R; 2296 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID)) 2297 Diag(Loc, diag::note_include_header_or_declare) 2298 << Header << Context.BuiltinInfo.getName(ID); 2299 } 2300 2301 if (R.isNull()) 2302 return nullptr; 2303 2304 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc); 2305 RegisterLocallyScopedExternCDecl(New, S); 2306 2307 // TUScope is the translation-unit scope to insert this function into. 2308 // FIXME: This is hideous. We need to teach PushOnScopeChains to 2309 // relate Scopes to DeclContexts, and probably eliminate CurContext 2310 // entirely, but we're not there yet. 2311 DeclContext *SavedContext = CurContext; 2312 CurContext = New->getDeclContext(); 2313 PushOnScopeChains(New, TUScope); 2314 CurContext = SavedContext; 2315 return New; 2316 } 2317 2318 /// Typedef declarations don't have linkage, but they still denote the same 2319 /// entity if their types are the same. 2320 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 2321 /// isSameEntity. 2322 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 2323 TypedefNameDecl *Decl, 2324 LookupResult &Previous) { 2325 // This is only interesting when modules are enabled. 2326 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 2327 return; 2328 2329 // Empty sets are uninteresting. 2330 if (Previous.empty()) 2331 return; 2332 2333 LookupResult::Filter Filter = Previous.makeFilter(); 2334 while (Filter.hasNext()) { 2335 NamedDecl *Old = Filter.next(); 2336 2337 // Non-hidden declarations are never ignored. 2338 if (S.isVisible(Old)) 2339 continue; 2340 2341 // Declarations of the same entity are not ignored, even if they have 2342 // different linkages. 2343 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2344 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 2345 Decl->getUnderlyingType())) 2346 continue; 2347 2348 // If both declarations give a tag declaration a typedef name for linkage 2349 // purposes, then they declare the same entity. 2350 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 2351 Decl->getAnonDeclWithTypedefName()) 2352 continue; 2353 } 2354 2355 Filter.erase(); 2356 } 2357 2358 Filter.done(); 2359 } 2360 2361 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 2362 QualType OldType; 2363 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 2364 OldType = OldTypedef->getUnderlyingType(); 2365 else 2366 OldType = Context.getTypeDeclType(Old); 2367 QualType NewType = New->getUnderlyingType(); 2368 2369 if (NewType->isVariablyModifiedType()) { 2370 // Must not redefine a typedef with a variably-modified type. 2371 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2372 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 2373 << Kind << NewType; 2374 if (Old->getLocation().isValid()) 2375 notePreviousDefinition(Old, New->getLocation()); 2376 New->setInvalidDecl(); 2377 return true; 2378 } 2379 2380 if (OldType != NewType && 2381 !OldType->isDependentType() && 2382 !NewType->isDependentType() && 2383 !Context.hasSameType(OldType, NewType)) { 2384 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2385 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 2386 << Kind << NewType << OldType; 2387 if (Old->getLocation().isValid()) 2388 notePreviousDefinition(Old, New->getLocation()); 2389 New->setInvalidDecl(); 2390 return true; 2391 } 2392 return false; 2393 } 2394 2395 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 2396 /// same name and scope as a previous declaration 'Old'. Figure out 2397 /// how to resolve this situation, merging decls or emitting 2398 /// diagnostics as appropriate. If there was an error, set New to be invalid. 2399 /// 2400 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 2401 LookupResult &OldDecls) { 2402 // If the new decl is known invalid already, don't bother doing any 2403 // merging checks. 2404 if (New->isInvalidDecl()) return; 2405 2406 // Allow multiple definitions for ObjC built-in typedefs. 2407 // FIXME: Verify the underlying types are equivalent! 2408 if (getLangOpts().ObjC) { 2409 const IdentifierInfo *TypeID = New->getIdentifier(); 2410 switch (TypeID->getLength()) { 2411 default: break; 2412 case 2: 2413 { 2414 if (!TypeID->isStr("id")) 2415 break; 2416 QualType T = New->getUnderlyingType(); 2417 if (!T->isPointerType()) 2418 break; 2419 if (!T->isVoidPointerType()) { 2420 QualType PT = T->castAs<PointerType>()->getPointeeType(); 2421 if (!PT->isStructureType()) 2422 break; 2423 } 2424 Context.setObjCIdRedefinitionType(T); 2425 // Install the built-in type for 'id', ignoring the current definition. 2426 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 2427 return; 2428 } 2429 case 5: 2430 if (!TypeID->isStr("Class")) 2431 break; 2432 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 2433 // Install the built-in type for 'Class', ignoring the current definition. 2434 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 2435 return; 2436 case 3: 2437 if (!TypeID->isStr("SEL")) 2438 break; 2439 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 2440 // Install the built-in type for 'SEL', ignoring the current definition. 2441 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 2442 return; 2443 } 2444 // Fall through - the typedef name was not a builtin type. 2445 } 2446 2447 // Verify the old decl was also a type. 2448 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 2449 if (!Old) { 2450 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2451 << New->getDeclName(); 2452 2453 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 2454 if (OldD->getLocation().isValid()) 2455 notePreviousDefinition(OldD, New->getLocation()); 2456 2457 return New->setInvalidDecl(); 2458 } 2459 2460 // If the old declaration is invalid, just give up here. 2461 if (Old->isInvalidDecl()) 2462 return New->setInvalidDecl(); 2463 2464 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2465 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2466 auto *NewTag = New->getAnonDeclWithTypedefName(); 2467 NamedDecl *Hidden = nullptr; 2468 if (OldTag && NewTag && 2469 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 2470 !hasVisibleDefinition(OldTag, &Hidden)) { 2471 // There is a definition of this tag, but it is not visible. Use it 2472 // instead of our tag. 2473 New->setTypeForDecl(OldTD->getTypeForDecl()); 2474 if (OldTD->isModed()) 2475 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 2476 OldTD->getUnderlyingType()); 2477 else 2478 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 2479 2480 // Make the old tag definition visible. 2481 makeMergedDefinitionVisible(Hidden); 2482 2483 // If this was an unscoped enumeration, yank all of its enumerators 2484 // out of the scope. 2485 if (isa<EnumDecl>(NewTag)) { 2486 Scope *EnumScope = getNonFieldDeclScope(S); 2487 for (auto *D : NewTag->decls()) { 2488 auto *ED = cast<EnumConstantDecl>(D); 2489 assert(EnumScope->isDeclScope(ED)); 2490 EnumScope->RemoveDecl(ED); 2491 IdResolver.RemoveDecl(ED); 2492 ED->getLexicalDeclContext()->removeDecl(ED); 2493 } 2494 } 2495 } 2496 } 2497 2498 // If the typedef types are not identical, reject them in all languages and 2499 // with any extensions enabled. 2500 if (isIncompatibleTypedef(Old, New)) 2501 return; 2502 2503 // The types match. Link up the redeclaration chain and merge attributes if 2504 // the old declaration was a typedef. 2505 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2506 New->setPreviousDecl(Typedef); 2507 mergeDeclAttributes(New, Old); 2508 } 2509 2510 if (getLangOpts().MicrosoftExt) 2511 return; 2512 2513 if (getLangOpts().CPlusPlus) { 2514 // C++ [dcl.typedef]p2: 2515 // In a given non-class scope, a typedef specifier can be used to 2516 // redefine the name of any type declared in that scope to refer 2517 // to the type to which it already refers. 2518 if (!isa<CXXRecordDecl>(CurContext)) 2519 return; 2520 2521 // C++0x [dcl.typedef]p4: 2522 // In a given class scope, a typedef specifier can be used to redefine 2523 // any class-name declared in that scope that is not also a typedef-name 2524 // to refer to the type to which it already refers. 2525 // 2526 // This wording came in via DR424, which was a correction to the 2527 // wording in DR56, which accidentally banned code like: 2528 // 2529 // struct S { 2530 // typedef struct A { } A; 2531 // }; 2532 // 2533 // in the C++03 standard. We implement the C++0x semantics, which 2534 // allow the above but disallow 2535 // 2536 // struct S { 2537 // typedef int I; 2538 // typedef int I; 2539 // }; 2540 // 2541 // since that was the intent of DR56. 2542 if (!isa<TypedefNameDecl>(Old)) 2543 return; 2544 2545 Diag(New->getLocation(), diag::err_redefinition) 2546 << New->getDeclName(); 2547 notePreviousDefinition(Old, New->getLocation()); 2548 return New->setInvalidDecl(); 2549 } 2550 2551 // Modules always permit redefinition of typedefs, as does C11. 2552 if (getLangOpts().Modules || getLangOpts().C11) 2553 return; 2554 2555 // If we have a redefinition of a typedef in C, emit a warning. This warning 2556 // is normally mapped to an error, but can be controlled with 2557 // -Wtypedef-redefinition. If either the original or the redefinition is 2558 // in a system header, don't emit this for compatibility with GCC. 2559 if (getDiagnostics().getSuppressSystemWarnings() && 2560 // Some standard types are defined implicitly in Clang (e.g. OpenCL). 2561 (Old->isImplicit() || 2562 Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2563 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2564 return; 2565 2566 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2567 << New->getDeclName(); 2568 notePreviousDefinition(Old, New->getLocation()); 2569 } 2570 2571 /// DeclhasAttr - returns true if decl Declaration already has the target 2572 /// attribute. 2573 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2574 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2575 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2576 for (const auto *i : D->attrs()) 2577 if (i->getKind() == A->getKind()) { 2578 if (Ann) { 2579 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2580 return true; 2581 continue; 2582 } 2583 // FIXME: Don't hardcode this check 2584 if (OA && isa<OwnershipAttr>(i)) 2585 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2586 return true; 2587 } 2588 2589 return false; 2590 } 2591 2592 static bool isAttributeTargetADefinition(Decl *D) { 2593 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2594 return VD->isThisDeclarationADefinition(); 2595 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2596 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2597 return true; 2598 } 2599 2600 /// Merge alignment attributes from \p Old to \p New, taking into account the 2601 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2602 /// 2603 /// \return \c true if any attributes were added to \p New. 2604 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2605 // Look for alignas attributes on Old, and pick out whichever attribute 2606 // specifies the strictest alignment requirement. 2607 AlignedAttr *OldAlignasAttr = nullptr; 2608 AlignedAttr *OldStrictestAlignAttr = nullptr; 2609 unsigned OldAlign = 0; 2610 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2611 // FIXME: We have no way of representing inherited dependent alignments 2612 // in a case like: 2613 // template<int A, int B> struct alignas(A) X; 2614 // template<int A, int B> struct alignas(B) X {}; 2615 // For now, we just ignore any alignas attributes which are not on the 2616 // definition in such a case. 2617 if (I->isAlignmentDependent()) 2618 return false; 2619 2620 if (I->isAlignas()) 2621 OldAlignasAttr = I; 2622 2623 unsigned Align = I->getAlignment(S.Context); 2624 if (Align > OldAlign) { 2625 OldAlign = Align; 2626 OldStrictestAlignAttr = I; 2627 } 2628 } 2629 2630 // Look for alignas attributes on New. 2631 AlignedAttr *NewAlignasAttr = nullptr; 2632 unsigned NewAlign = 0; 2633 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2634 if (I->isAlignmentDependent()) 2635 return false; 2636 2637 if (I->isAlignas()) 2638 NewAlignasAttr = I; 2639 2640 unsigned Align = I->getAlignment(S.Context); 2641 if (Align > NewAlign) 2642 NewAlign = Align; 2643 } 2644 2645 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2646 // Both declarations have 'alignas' attributes. We require them to match. 2647 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2648 // fall short. (If two declarations both have alignas, they must both match 2649 // every definition, and so must match each other if there is a definition.) 2650 2651 // If either declaration only contains 'alignas(0)' specifiers, then it 2652 // specifies the natural alignment for the type. 2653 if (OldAlign == 0 || NewAlign == 0) { 2654 QualType Ty; 2655 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2656 Ty = VD->getType(); 2657 else 2658 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2659 2660 if (OldAlign == 0) 2661 OldAlign = S.Context.getTypeAlign(Ty); 2662 if (NewAlign == 0) 2663 NewAlign = S.Context.getTypeAlign(Ty); 2664 } 2665 2666 if (OldAlign != NewAlign) { 2667 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2668 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2669 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2670 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2671 } 2672 } 2673 2674 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2675 // C++11 [dcl.align]p6: 2676 // if any declaration of an entity has an alignment-specifier, 2677 // every defining declaration of that entity shall specify an 2678 // equivalent alignment. 2679 // C11 6.7.5/7: 2680 // If the definition of an object does not have an alignment 2681 // specifier, any other declaration of that object shall also 2682 // have no alignment specifier. 2683 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2684 << OldAlignasAttr; 2685 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2686 << OldAlignasAttr; 2687 } 2688 2689 bool AnyAdded = false; 2690 2691 // Ensure we have an attribute representing the strictest alignment. 2692 if (OldAlign > NewAlign) { 2693 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2694 Clone->setInherited(true); 2695 New->addAttr(Clone); 2696 AnyAdded = true; 2697 } 2698 2699 // Ensure we have an alignas attribute if the old declaration had one. 2700 if (OldAlignasAttr && !NewAlignasAttr && 2701 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2702 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2703 Clone->setInherited(true); 2704 New->addAttr(Clone); 2705 AnyAdded = true; 2706 } 2707 2708 return AnyAdded; 2709 } 2710 2711 #define WANT_DECL_MERGE_LOGIC 2712 #include "clang/Sema/AttrParsedAttrImpl.inc" 2713 #undef WANT_DECL_MERGE_LOGIC 2714 2715 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2716 const InheritableAttr *Attr, 2717 Sema::AvailabilityMergeKind AMK) { 2718 // Diagnose any mutual exclusions between the attribute that we want to add 2719 // and attributes that already exist on the declaration. 2720 if (!DiagnoseMutualExclusions(S, D, Attr)) 2721 return false; 2722 2723 // This function copies an attribute Attr from a previous declaration to the 2724 // new declaration D if the new declaration doesn't itself have that attribute 2725 // yet or if that attribute allows duplicates. 2726 // If you're adding a new attribute that requires logic different from 2727 // "use explicit attribute on decl if present, else use attribute from 2728 // previous decl", for example if the attribute needs to be consistent 2729 // between redeclarations, you need to call a custom merge function here. 2730 InheritableAttr *NewAttr = nullptr; 2731 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2732 NewAttr = S.mergeAvailabilityAttr( 2733 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(), 2734 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(), 2735 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK, 2736 AA->getPriority()); 2737 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2738 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility()); 2739 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2740 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility()); 2741 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2742 NewAttr = S.mergeDLLImportAttr(D, *ImportA); 2743 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2744 NewAttr = S.mergeDLLExportAttr(D, *ExportA); 2745 else if (const auto *EA = dyn_cast<ErrorAttr>(Attr)) 2746 NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic()); 2747 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2748 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(), 2749 FA->getFirstArg()); 2750 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2751 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName()); 2752 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr)) 2753 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName()); 2754 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2755 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(), 2756 IA->getInheritanceModel()); 2757 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2758 NewAttr = S.mergeAlwaysInlineAttr(D, *AA, 2759 &S.Context.Idents.get(AA->getSpelling())); 2760 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2761 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2762 isa<CUDAGlobalAttr>(Attr))) { 2763 // CUDA target attributes are part of function signature for 2764 // overloading purposes and must not be merged. 2765 return false; 2766 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2767 NewAttr = S.mergeMinSizeAttr(D, *MA); 2768 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr)) 2769 NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName()); 2770 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2771 NewAttr = S.mergeOptimizeNoneAttr(D, *OA); 2772 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2773 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA); 2774 else if (isa<AlignedAttr>(Attr)) 2775 // AlignedAttrs are handled separately, because we need to handle all 2776 // such attributes on a declaration at the same time. 2777 NewAttr = nullptr; 2778 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2779 (AMK == Sema::AMK_Override || 2780 AMK == Sema::AMK_ProtocolImplementation || 2781 AMK == Sema::AMK_OptionalProtocolImplementation)) 2782 NewAttr = nullptr; 2783 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2784 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl()); 2785 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr)) 2786 NewAttr = S.mergeImportModuleAttr(D, *IMA); 2787 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr)) 2788 NewAttr = S.mergeImportNameAttr(D, *INA); 2789 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr)) 2790 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA); 2791 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr)) 2792 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA); 2793 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr)) 2794 NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA); 2795 else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr)) 2796 NewAttr = 2797 S.mergeHLSLNumThreadsAttr(D, *NT, NT->getX(), NT->getY(), NT->getZ()); 2798 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr)) 2799 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2800 2801 if (NewAttr) { 2802 NewAttr->setInherited(true); 2803 D->addAttr(NewAttr); 2804 if (isa<MSInheritanceAttr>(NewAttr)) 2805 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2806 return true; 2807 } 2808 2809 return false; 2810 } 2811 2812 static const NamedDecl *getDefinition(const Decl *D) { 2813 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2814 return TD->getDefinition(); 2815 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2816 const VarDecl *Def = VD->getDefinition(); 2817 if (Def) 2818 return Def; 2819 return VD->getActingDefinition(); 2820 } 2821 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2822 const FunctionDecl *Def = nullptr; 2823 if (FD->isDefined(Def, true)) 2824 return Def; 2825 } 2826 return nullptr; 2827 } 2828 2829 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2830 for (const auto *Attribute : D->attrs()) 2831 if (Attribute->getKind() == Kind) 2832 return true; 2833 return false; 2834 } 2835 2836 /// checkNewAttributesAfterDef - If we already have a definition, check that 2837 /// there are no new attributes in this declaration. 2838 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2839 if (!New->hasAttrs()) 2840 return; 2841 2842 const NamedDecl *Def = getDefinition(Old); 2843 if (!Def || Def == New) 2844 return; 2845 2846 AttrVec &NewAttributes = New->getAttrs(); 2847 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2848 const Attr *NewAttribute = NewAttributes[I]; 2849 2850 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 2851 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2852 Sema::SkipBodyInfo SkipBody; 2853 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2854 2855 // If we're skipping this definition, drop the "alias" attribute. 2856 if (SkipBody.ShouldSkip) { 2857 NewAttributes.erase(NewAttributes.begin() + I); 2858 --E; 2859 continue; 2860 } 2861 } else { 2862 VarDecl *VD = cast<VarDecl>(New); 2863 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2864 VarDecl::TentativeDefinition 2865 ? diag::err_alias_after_tentative 2866 : diag::err_redefinition; 2867 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2868 if (Diag == diag::err_redefinition) 2869 S.notePreviousDefinition(Def, VD->getLocation()); 2870 else 2871 S.Diag(Def->getLocation(), diag::note_previous_definition); 2872 VD->setInvalidDecl(); 2873 } 2874 ++I; 2875 continue; 2876 } 2877 2878 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2879 // Tentative definitions are only interesting for the alias check above. 2880 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2881 ++I; 2882 continue; 2883 } 2884 } 2885 2886 if (hasAttribute(Def, NewAttribute->getKind())) { 2887 ++I; 2888 continue; // regular attr merging will take care of validating this. 2889 } 2890 2891 if (isa<C11NoReturnAttr>(NewAttribute)) { 2892 // C's _Noreturn is allowed to be added to a function after it is defined. 2893 ++I; 2894 continue; 2895 } else if (isa<UuidAttr>(NewAttribute)) { 2896 // msvc will allow a subsequent definition to add an uuid to a class 2897 ++I; 2898 continue; 2899 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2900 if (AA->isAlignas()) { 2901 // C++11 [dcl.align]p6: 2902 // if any declaration of an entity has an alignment-specifier, 2903 // every defining declaration of that entity shall specify an 2904 // equivalent alignment. 2905 // C11 6.7.5/7: 2906 // If the definition of an object does not have an alignment 2907 // specifier, any other declaration of that object shall also 2908 // have no alignment specifier. 2909 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2910 << AA; 2911 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2912 << AA; 2913 NewAttributes.erase(NewAttributes.begin() + I); 2914 --E; 2915 continue; 2916 } 2917 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) { 2918 // If there is a C definition followed by a redeclaration with this 2919 // attribute then there are two different definitions. In C++, prefer the 2920 // standard diagnostics. 2921 if (!S.getLangOpts().CPlusPlus) { 2922 S.Diag(NewAttribute->getLocation(), 2923 diag::err_loader_uninitialized_redeclaration); 2924 S.Diag(Def->getLocation(), diag::note_previous_definition); 2925 NewAttributes.erase(NewAttributes.begin() + I); 2926 --E; 2927 continue; 2928 } 2929 } else if (isa<SelectAnyAttr>(NewAttribute) && 2930 cast<VarDecl>(New)->isInline() && 2931 !cast<VarDecl>(New)->isInlineSpecified()) { 2932 // Don't warn about applying selectany to implicitly inline variables. 2933 // Older compilers and language modes would require the use of selectany 2934 // to make such variables inline, and it would have no effect if we 2935 // honored it. 2936 ++I; 2937 continue; 2938 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) { 2939 // We allow to add OMP[Begin]DeclareVariantAttr to be added to 2940 // declarations after defintions. 2941 ++I; 2942 continue; 2943 } 2944 2945 S.Diag(NewAttribute->getLocation(), 2946 diag::warn_attribute_precede_definition); 2947 S.Diag(Def->getLocation(), diag::note_previous_definition); 2948 NewAttributes.erase(NewAttributes.begin() + I); 2949 --E; 2950 } 2951 } 2952 2953 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, 2954 const ConstInitAttr *CIAttr, 2955 bool AttrBeforeInit) { 2956 SourceLocation InsertLoc = InitDecl->getInnerLocStart(); 2957 2958 // Figure out a good way to write this specifier on the old declaration. 2959 // FIXME: We should just use the spelling of CIAttr, but we don't preserve 2960 // enough of the attribute list spelling information to extract that without 2961 // heroics. 2962 std::string SuitableSpelling; 2963 if (S.getLangOpts().CPlusPlus20) 2964 SuitableSpelling = std::string( 2965 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit})); 2966 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2967 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2968 InsertLoc, {tok::l_square, tok::l_square, 2969 S.PP.getIdentifierInfo("clang"), tok::coloncolon, 2970 S.PP.getIdentifierInfo("require_constant_initialization"), 2971 tok::r_square, tok::r_square})); 2972 if (SuitableSpelling.empty()) 2973 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2974 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren, 2975 S.PP.getIdentifierInfo("require_constant_initialization"), 2976 tok::r_paren, tok::r_paren})); 2977 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20) 2978 SuitableSpelling = "constinit"; 2979 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2980 SuitableSpelling = "[[clang::require_constant_initialization]]"; 2981 if (SuitableSpelling.empty()) 2982 SuitableSpelling = "__attribute__((require_constant_initialization))"; 2983 SuitableSpelling += " "; 2984 2985 if (AttrBeforeInit) { 2986 // extern constinit int a; 2987 // int a = 0; // error (missing 'constinit'), accepted as extension 2988 assert(CIAttr->isConstinit() && "should not diagnose this for attribute"); 2989 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing) 2990 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 2991 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here); 2992 } else { 2993 // int a = 0; 2994 // constinit extern int a; // error (missing 'constinit') 2995 S.Diag(CIAttr->getLocation(), 2996 CIAttr->isConstinit() ? diag::err_constinit_added_too_late 2997 : diag::warn_require_const_init_added_too_late) 2998 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation())); 2999 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here) 3000 << CIAttr->isConstinit() 3001 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 3002 } 3003 } 3004 3005 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 3006 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 3007 AvailabilityMergeKind AMK) { 3008 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 3009 UsedAttr *NewAttr = OldAttr->clone(Context); 3010 NewAttr->setInherited(true); 3011 New->addAttr(NewAttr); 3012 } 3013 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) { 3014 RetainAttr *NewAttr = OldAttr->clone(Context); 3015 NewAttr->setInherited(true); 3016 New->addAttr(NewAttr); 3017 } 3018 3019 if (!Old->hasAttrs() && !New->hasAttrs()) 3020 return; 3021 3022 // [dcl.constinit]p1: 3023 // If the [constinit] specifier is applied to any declaration of a 3024 // variable, it shall be applied to the initializing declaration. 3025 const auto *OldConstInit = Old->getAttr<ConstInitAttr>(); 3026 const auto *NewConstInit = New->getAttr<ConstInitAttr>(); 3027 if (bool(OldConstInit) != bool(NewConstInit)) { 3028 const auto *OldVD = cast<VarDecl>(Old); 3029 auto *NewVD = cast<VarDecl>(New); 3030 3031 // Find the initializing declaration. Note that we might not have linked 3032 // the new declaration into the redeclaration chain yet. 3033 const VarDecl *InitDecl = OldVD->getInitializingDeclaration(); 3034 if (!InitDecl && 3035 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition())) 3036 InitDecl = NewVD; 3037 3038 if (InitDecl == NewVD) { 3039 // This is the initializing declaration. If it would inherit 'constinit', 3040 // that's ill-formed. (Note that we do not apply this to the attribute 3041 // form). 3042 if (OldConstInit && OldConstInit->isConstinit()) 3043 diagnoseMissingConstinit(*this, NewVD, OldConstInit, 3044 /*AttrBeforeInit=*/true); 3045 } else if (NewConstInit) { 3046 // This is the first time we've been told that this declaration should 3047 // have a constant initializer. If we already saw the initializing 3048 // declaration, this is too late. 3049 if (InitDecl && InitDecl != NewVD) { 3050 diagnoseMissingConstinit(*this, InitDecl, NewConstInit, 3051 /*AttrBeforeInit=*/false); 3052 NewVD->dropAttr<ConstInitAttr>(); 3053 } 3054 } 3055 } 3056 3057 // Attributes declared post-definition are currently ignored. 3058 checkNewAttributesAfterDef(*this, New, Old); 3059 3060 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 3061 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 3062 if (!OldA->isEquivalent(NewA)) { 3063 // This redeclaration changes __asm__ label. 3064 Diag(New->getLocation(), diag::err_different_asm_label); 3065 Diag(OldA->getLocation(), diag::note_previous_declaration); 3066 } 3067 } else if (Old->isUsed()) { 3068 // This redeclaration adds an __asm__ label to a declaration that has 3069 // already been ODR-used. 3070 Diag(New->getLocation(), diag::err_late_asm_label_name) 3071 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 3072 } 3073 } 3074 3075 // Re-declaration cannot add abi_tag's. 3076 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 3077 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 3078 for (const auto &NewTag : NewAbiTagAttr->tags()) { 3079 if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) { 3080 Diag(NewAbiTagAttr->getLocation(), 3081 diag::err_new_abi_tag_on_redeclaration) 3082 << NewTag; 3083 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 3084 } 3085 } 3086 } else { 3087 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 3088 Diag(Old->getLocation(), diag::note_previous_declaration); 3089 } 3090 } 3091 3092 // This redeclaration adds a section attribute. 3093 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { 3094 if (auto *VD = dyn_cast<VarDecl>(New)) { 3095 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) { 3096 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration); 3097 Diag(Old->getLocation(), diag::note_previous_declaration); 3098 } 3099 } 3100 } 3101 3102 // Redeclaration adds code-seg attribute. 3103 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 3104 if (NewCSA && !Old->hasAttr<CodeSegAttr>() && 3105 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) { 3106 Diag(New->getLocation(), diag::warn_mismatched_section) 3107 << 0 /*codeseg*/; 3108 Diag(Old->getLocation(), diag::note_previous_declaration); 3109 } 3110 3111 if (!Old->hasAttrs()) 3112 return; 3113 3114 bool foundAny = New->hasAttrs(); 3115 3116 // Ensure that any moving of objects within the allocated map is done before 3117 // we process them. 3118 if (!foundAny) New->setAttrs(AttrVec()); 3119 3120 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 3121 // Ignore deprecated/unavailable/availability attributes if requested. 3122 AvailabilityMergeKind LocalAMK = AMK_None; 3123 if (isa<DeprecatedAttr>(I) || 3124 isa<UnavailableAttr>(I) || 3125 isa<AvailabilityAttr>(I)) { 3126 switch (AMK) { 3127 case AMK_None: 3128 continue; 3129 3130 case AMK_Redeclaration: 3131 case AMK_Override: 3132 case AMK_ProtocolImplementation: 3133 case AMK_OptionalProtocolImplementation: 3134 LocalAMK = AMK; 3135 break; 3136 } 3137 } 3138 3139 // Already handled. 3140 if (isa<UsedAttr>(I) || isa<RetainAttr>(I)) 3141 continue; 3142 3143 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 3144 foundAny = true; 3145 } 3146 3147 if (mergeAlignedAttrs(*this, New, Old)) 3148 foundAny = true; 3149 3150 if (!foundAny) New->dropAttrs(); 3151 } 3152 3153 /// mergeParamDeclAttributes - Copy attributes from the old parameter 3154 /// to the new one. 3155 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 3156 const ParmVarDecl *oldDecl, 3157 Sema &S) { 3158 // C++11 [dcl.attr.depend]p2: 3159 // The first declaration of a function shall specify the 3160 // carries_dependency attribute for its declarator-id if any declaration 3161 // of the function specifies the carries_dependency attribute. 3162 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 3163 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 3164 S.Diag(CDA->getLocation(), 3165 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 3166 // Find the first declaration of the parameter. 3167 // FIXME: Should we build redeclaration chains for function parameters? 3168 const FunctionDecl *FirstFD = 3169 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 3170 const ParmVarDecl *FirstVD = 3171 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 3172 S.Diag(FirstVD->getLocation(), 3173 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 3174 } 3175 3176 if (!oldDecl->hasAttrs()) 3177 return; 3178 3179 bool foundAny = newDecl->hasAttrs(); 3180 3181 // Ensure that any moving of objects within the allocated map is 3182 // done before we process them. 3183 if (!foundAny) newDecl->setAttrs(AttrVec()); 3184 3185 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 3186 if (!DeclHasAttr(newDecl, I)) { 3187 InheritableAttr *newAttr = 3188 cast<InheritableParamAttr>(I->clone(S.Context)); 3189 newAttr->setInherited(true); 3190 newDecl->addAttr(newAttr); 3191 foundAny = true; 3192 } 3193 } 3194 3195 if (!foundAny) newDecl->dropAttrs(); 3196 } 3197 3198 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 3199 const ParmVarDecl *OldParam, 3200 Sema &S) { 3201 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 3202 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 3203 if (*Oldnullability != *Newnullability) { 3204 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 3205 << DiagNullabilityKind( 3206 *Newnullability, 3207 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3208 != 0)) 3209 << DiagNullabilityKind( 3210 *Oldnullability, 3211 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3212 != 0)); 3213 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 3214 } 3215 } else { 3216 QualType NewT = NewParam->getType(); 3217 NewT = S.Context.getAttributedType( 3218 AttributedType::getNullabilityAttrKind(*Oldnullability), 3219 NewT, NewT); 3220 NewParam->setType(NewT); 3221 } 3222 } 3223 } 3224 3225 namespace { 3226 3227 /// Used in MergeFunctionDecl to keep track of function parameters in 3228 /// C. 3229 struct GNUCompatibleParamWarning { 3230 ParmVarDecl *OldParm; 3231 ParmVarDecl *NewParm; 3232 QualType PromotedType; 3233 }; 3234 3235 } // end anonymous namespace 3236 3237 // Determine whether the previous declaration was a definition, implicit 3238 // declaration, or a declaration. 3239 template <typename T> 3240 static std::pair<diag::kind, SourceLocation> 3241 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 3242 diag::kind PrevDiag; 3243 SourceLocation OldLocation = Old->getLocation(); 3244 if (Old->isThisDeclarationADefinition()) 3245 PrevDiag = diag::note_previous_definition; 3246 else if (Old->isImplicit()) { 3247 PrevDiag = diag::note_previous_implicit_declaration; 3248 if (OldLocation.isInvalid()) 3249 OldLocation = New->getLocation(); 3250 } else 3251 PrevDiag = diag::note_previous_declaration; 3252 return std::make_pair(PrevDiag, OldLocation); 3253 } 3254 3255 /// canRedefineFunction - checks if a function can be redefined. Currently, 3256 /// only extern inline functions can be redefined, and even then only in 3257 /// GNU89 mode. 3258 static bool canRedefineFunction(const FunctionDecl *FD, 3259 const LangOptions& LangOpts) { 3260 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 3261 !LangOpts.CPlusPlus && 3262 FD->isInlineSpecified() && 3263 FD->getStorageClass() == SC_Extern); 3264 } 3265 3266 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 3267 const AttributedType *AT = T->getAs<AttributedType>(); 3268 while (AT && !AT->isCallingConv()) 3269 AT = AT->getModifiedType()->getAs<AttributedType>(); 3270 return AT; 3271 } 3272 3273 template <typename T> 3274 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 3275 const DeclContext *DC = Old->getDeclContext(); 3276 if (DC->isRecord()) 3277 return false; 3278 3279 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 3280 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 3281 return true; 3282 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 3283 return true; 3284 return false; 3285 } 3286 3287 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 3288 static bool isExternC(VarTemplateDecl *) { return false; } 3289 static bool isExternC(FunctionTemplateDecl *) { return false; } 3290 3291 /// Check whether a redeclaration of an entity introduced by a 3292 /// using-declaration is valid, given that we know it's not an overload 3293 /// (nor a hidden tag declaration). 3294 template<typename ExpectedDecl> 3295 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 3296 ExpectedDecl *New) { 3297 // C++11 [basic.scope.declarative]p4: 3298 // Given a set of declarations in a single declarative region, each of 3299 // which specifies the same unqualified name, 3300 // -- they shall all refer to the same entity, or all refer to functions 3301 // and function templates; or 3302 // -- exactly one declaration shall declare a class name or enumeration 3303 // name that is not a typedef name and the other declarations shall all 3304 // refer to the same variable or enumerator, or all refer to functions 3305 // and function templates; in this case the class name or enumeration 3306 // name is hidden (3.3.10). 3307 3308 // C++11 [namespace.udecl]p14: 3309 // If a function declaration in namespace scope or block scope has the 3310 // same name and the same parameter-type-list as a function introduced 3311 // by a using-declaration, and the declarations do not declare the same 3312 // function, the program is ill-formed. 3313 3314 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 3315 if (Old && 3316 !Old->getDeclContext()->getRedeclContext()->Equals( 3317 New->getDeclContext()->getRedeclContext()) && 3318 !(isExternC(Old) && isExternC(New))) 3319 Old = nullptr; 3320 3321 if (!Old) { 3322 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 3323 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 3324 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0; 3325 return true; 3326 } 3327 return false; 3328 } 3329 3330 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 3331 const FunctionDecl *B) { 3332 assert(A->getNumParams() == B->getNumParams()); 3333 3334 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 3335 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 3336 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 3337 if (AttrA == AttrB) 3338 return true; 3339 return AttrA && AttrB && AttrA->getType() == AttrB->getType() && 3340 AttrA->isDynamic() == AttrB->isDynamic(); 3341 }; 3342 3343 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 3344 } 3345 3346 /// If necessary, adjust the semantic declaration context for a qualified 3347 /// declaration to name the correct inline namespace within the qualifier. 3348 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, 3349 DeclaratorDecl *OldD) { 3350 // The only case where we need to update the DeclContext is when 3351 // redeclaration lookup for a qualified name finds a declaration 3352 // in an inline namespace within the context named by the qualifier: 3353 // 3354 // inline namespace N { int f(); } 3355 // int ::f(); // Sema DC needs adjusting from :: to N::. 3356 // 3357 // For unqualified declarations, the semantic context *can* change 3358 // along the redeclaration chain (for local extern declarations, 3359 // extern "C" declarations, and friend declarations in particular). 3360 if (!NewD->getQualifier()) 3361 return; 3362 3363 // NewD is probably already in the right context. 3364 auto *NamedDC = NewD->getDeclContext()->getRedeclContext(); 3365 auto *SemaDC = OldD->getDeclContext()->getRedeclContext(); 3366 if (NamedDC->Equals(SemaDC)) 3367 return; 3368 3369 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || 3370 NewD->isInvalidDecl() || OldD->isInvalidDecl()) && 3371 "unexpected context for redeclaration"); 3372 3373 auto *LexDC = NewD->getLexicalDeclContext(); 3374 auto FixSemaDC = [=](NamedDecl *D) { 3375 if (!D) 3376 return; 3377 D->setDeclContext(SemaDC); 3378 D->setLexicalDeclContext(LexDC); 3379 }; 3380 3381 FixSemaDC(NewD); 3382 if (auto *FD = dyn_cast<FunctionDecl>(NewD)) 3383 FixSemaDC(FD->getDescribedFunctionTemplate()); 3384 else if (auto *VD = dyn_cast<VarDecl>(NewD)) 3385 FixSemaDC(VD->getDescribedVarTemplate()); 3386 } 3387 3388 /// MergeFunctionDecl - We just parsed a function 'New' from 3389 /// declarator D which has the same name and scope as a previous 3390 /// declaration 'Old'. Figure out how to resolve this situation, 3391 /// merging decls or emitting diagnostics as appropriate. 3392 /// 3393 /// In C++, New and Old must be declarations that are not 3394 /// overloaded. Use IsOverload to determine whether New and Old are 3395 /// overloaded, and to select the Old declaration that New should be 3396 /// merged with. 3397 /// 3398 /// Returns true if there was an error, false otherwise. 3399 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 3400 Scope *S, bool MergeTypeWithOld) { 3401 // Verify the old decl was also a function. 3402 FunctionDecl *Old = OldD->getAsFunction(); 3403 if (!Old) { 3404 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 3405 if (New->getFriendObjectKind()) { 3406 Diag(New->getLocation(), diag::err_using_decl_friend); 3407 Diag(Shadow->getTargetDecl()->getLocation(), 3408 diag::note_using_decl_target); 3409 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) 3410 << 0; 3411 return true; 3412 } 3413 3414 // Check whether the two declarations might declare the same function or 3415 // function template. 3416 if (FunctionTemplateDecl *NewTemplate = 3417 New->getDescribedFunctionTemplate()) { 3418 if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow, 3419 NewTemplate)) 3420 return true; 3421 OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl()) 3422 ->getAsFunction(); 3423 } else { 3424 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 3425 return true; 3426 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 3427 } 3428 } else { 3429 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3430 << New->getDeclName(); 3431 notePreviousDefinition(OldD, New->getLocation()); 3432 return true; 3433 } 3434 } 3435 3436 // If the old declaration was found in an inline namespace and the new 3437 // declaration was qualified, update the DeclContext to match. 3438 adjustDeclContextForDeclaratorDecl(New, Old); 3439 3440 // If the old declaration is invalid, just give up here. 3441 if (Old->isInvalidDecl()) 3442 return true; 3443 3444 // Disallow redeclaration of some builtins. 3445 if (!getASTContext().canBuiltinBeRedeclared(Old)) { 3446 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName(); 3447 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 3448 << Old << Old->getType(); 3449 return true; 3450 } 3451 3452 diag::kind PrevDiag; 3453 SourceLocation OldLocation; 3454 std::tie(PrevDiag, OldLocation) = 3455 getNoteDiagForInvalidRedeclaration(Old, New); 3456 3457 // Don't complain about this if we're in GNU89 mode and the old function 3458 // is an extern inline function. 3459 // Don't complain about specializations. They are not supposed to have 3460 // storage classes. 3461 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 3462 New->getStorageClass() == SC_Static && 3463 Old->hasExternalFormalLinkage() && 3464 !New->getTemplateSpecializationInfo() && 3465 !canRedefineFunction(Old, getLangOpts())) { 3466 if (getLangOpts().MicrosoftExt) { 3467 Diag(New->getLocation(), diag::ext_static_non_static) << New; 3468 Diag(OldLocation, PrevDiag); 3469 } else { 3470 Diag(New->getLocation(), diag::err_static_non_static) << New; 3471 Diag(OldLocation, PrevDiag); 3472 return true; 3473 } 3474 } 3475 3476 if (const auto *ILA = New->getAttr<InternalLinkageAttr>()) 3477 if (!Old->hasAttr<InternalLinkageAttr>()) { 3478 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl) 3479 << ILA; 3480 Diag(Old->getLocation(), diag::note_previous_declaration); 3481 New->dropAttr<InternalLinkageAttr>(); 3482 } 3483 3484 if (auto *EA = New->getAttr<ErrorAttr>()) { 3485 if (!Old->hasAttr<ErrorAttr>()) { 3486 Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA; 3487 Diag(Old->getLocation(), diag::note_previous_declaration); 3488 New->dropAttr<ErrorAttr>(); 3489 } 3490 } 3491 3492 if (CheckRedeclarationInModule(New, Old)) 3493 return true; 3494 3495 if (!getLangOpts().CPlusPlus) { 3496 bool OldOvl = Old->hasAttr<OverloadableAttr>(); 3497 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { 3498 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) 3499 << New << OldOvl; 3500 3501 // Try our best to find a decl that actually has the overloadable 3502 // attribute for the note. In most cases (e.g. programs with only one 3503 // broken declaration/definition), this won't matter. 3504 // 3505 // FIXME: We could do this if we juggled some extra state in 3506 // OverloadableAttr, rather than just removing it. 3507 const Decl *DiagOld = Old; 3508 if (OldOvl) { 3509 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { 3510 const auto *A = D->getAttr<OverloadableAttr>(); 3511 return A && !A->isImplicit(); 3512 }); 3513 // If we've implicitly added *all* of the overloadable attrs to this 3514 // chain, emitting a "previous redecl" note is pointless. 3515 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; 3516 } 3517 3518 if (DiagOld) 3519 Diag(DiagOld->getLocation(), 3520 diag::note_attribute_overloadable_prev_overload) 3521 << OldOvl; 3522 3523 if (OldOvl) 3524 New->addAttr(OverloadableAttr::CreateImplicit(Context)); 3525 else 3526 New->dropAttr<OverloadableAttr>(); 3527 } 3528 } 3529 3530 // If a function is first declared with a calling convention, but is later 3531 // declared or defined without one, all following decls assume the calling 3532 // convention of the first. 3533 // 3534 // It's OK if a function is first declared without a calling convention, 3535 // but is later declared or defined with the default calling convention. 3536 // 3537 // To test if either decl has an explicit calling convention, we look for 3538 // AttributedType sugar nodes on the type as written. If they are missing or 3539 // were canonicalized away, we assume the calling convention was implicit. 3540 // 3541 // Note also that we DO NOT return at this point, because we still have 3542 // other tests to run. 3543 QualType OldQType = Context.getCanonicalType(Old->getType()); 3544 QualType NewQType = Context.getCanonicalType(New->getType()); 3545 const FunctionType *OldType = cast<FunctionType>(OldQType); 3546 const FunctionType *NewType = cast<FunctionType>(NewQType); 3547 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 3548 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 3549 bool RequiresAdjustment = false; 3550 3551 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 3552 FunctionDecl *First = Old->getFirstDecl(); 3553 const FunctionType *FT = 3554 First->getType().getCanonicalType()->castAs<FunctionType>(); 3555 FunctionType::ExtInfo FI = FT->getExtInfo(); 3556 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 3557 if (!NewCCExplicit) { 3558 // Inherit the CC from the previous declaration if it was specified 3559 // there but not here. 3560 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3561 RequiresAdjustment = true; 3562 } else if (Old->getBuiltinID()) { 3563 // Builtin attribute isn't propagated to the new one yet at this point, 3564 // so we check if the old one is a builtin. 3565 3566 // Calling Conventions on a Builtin aren't really useful and setting a 3567 // default calling convention and cdecl'ing some builtin redeclarations is 3568 // common, so warn and ignore the calling convention on the redeclaration. 3569 Diag(New->getLocation(), diag::warn_cconv_unsupported) 3570 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3571 << (int)CallingConventionIgnoredReason::BuiltinFunction; 3572 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3573 RequiresAdjustment = true; 3574 } else { 3575 // Calling conventions aren't compatible, so complain. 3576 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 3577 Diag(New->getLocation(), diag::err_cconv_change) 3578 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3579 << !FirstCCExplicit 3580 << (!FirstCCExplicit ? "" : 3581 FunctionType::getNameForCallConv(FI.getCC())); 3582 3583 // Put the note on the first decl, since it is the one that matters. 3584 Diag(First->getLocation(), diag::note_previous_declaration); 3585 return true; 3586 } 3587 } 3588 3589 // FIXME: diagnose the other way around? 3590 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 3591 NewTypeInfo = NewTypeInfo.withNoReturn(true); 3592 RequiresAdjustment = true; 3593 } 3594 3595 // Merge regparm attribute. 3596 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 3597 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 3598 if (NewTypeInfo.getHasRegParm()) { 3599 Diag(New->getLocation(), diag::err_regparm_mismatch) 3600 << NewType->getRegParmType() 3601 << OldType->getRegParmType(); 3602 Diag(OldLocation, diag::note_previous_declaration); 3603 return true; 3604 } 3605 3606 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 3607 RequiresAdjustment = true; 3608 } 3609 3610 // Merge ns_returns_retained attribute. 3611 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 3612 if (NewTypeInfo.getProducesResult()) { 3613 Diag(New->getLocation(), diag::err_function_attribute_mismatch) 3614 << "'ns_returns_retained'"; 3615 Diag(OldLocation, diag::note_previous_declaration); 3616 return true; 3617 } 3618 3619 NewTypeInfo = NewTypeInfo.withProducesResult(true); 3620 RequiresAdjustment = true; 3621 } 3622 3623 if (OldTypeInfo.getNoCallerSavedRegs() != 3624 NewTypeInfo.getNoCallerSavedRegs()) { 3625 if (NewTypeInfo.getNoCallerSavedRegs()) { 3626 AnyX86NoCallerSavedRegistersAttr *Attr = 3627 New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); 3628 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; 3629 Diag(OldLocation, diag::note_previous_declaration); 3630 return true; 3631 } 3632 3633 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); 3634 RequiresAdjustment = true; 3635 } 3636 3637 if (RequiresAdjustment) { 3638 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 3639 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 3640 New->setType(QualType(AdjustedType, 0)); 3641 NewQType = Context.getCanonicalType(New->getType()); 3642 } 3643 3644 // If this redeclaration makes the function inline, we may need to add it to 3645 // UndefinedButUsed. 3646 if (!Old->isInlined() && New->isInlined() && 3647 !New->hasAttr<GNUInlineAttr>() && 3648 !getLangOpts().GNUInline && 3649 Old->isUsed(false) && 3650 !Old->isDefined() && !New->isThisDeclarationADefinition()) 3651 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3652 SourceLocation())); 3653 3654 // If this redeclaration makes it newly gnu_inline, we don't want to warn 3655 // about it. 3656 if (New->hasAttr<GNUInlineAttr>() && 3657 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 3658 UndefinedButUsed.erase(Old->getCanonicalDecl()); 3659 } 3660 3661 // If pass_object_size params don't match up perfectly, this isn't a valid 3662 // redeclaration. 3663 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 3664 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 3665 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 3666 << New->getDeclName(); 3667 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3668 return true; 3669 } 3670 3671 if (getLangOpts().CPlusPlus) { 3672 // C++1z [over.load]p2 3673 // Certain function declarations cannot be overloaded: 3674 // -- Function declarations that differ only in the return type, 3675 // the exception specification, or both cannot be overloaded. 3676 3677 // Check the exception specifications match. This may recompute the type of 3678 // both Old and New if it resolved exception specifications, so grab the 3679 // types again after this. Because this updates the type, we do this before 3680 // any of the other checks below, which may update the "de facto" NewQType 3681 // but do not necessarily update the type of New. 3682 if (CheckEquivalentExceptionSpec(Old, New)) 3683 return true; 3684 OldQType = Context.getCanonicalType(Old->getType()); 3685 NewQType = Context.getCanonicalType(New->getType()); 3686 3687 // Go back to the type source info to compare the declared return types, 3688 // per C++1y [dcl.type.auto]p13: 3689 // Redeclarations or specializations of a function or function template 3690 // with a declared return type that uses a placeholder type shall also 3691 // use that placeholder, not a deduced type. 3692 QualType OldDeclaredReturnType = Old->getDeclaredReturnType(); 3693 QualType NewDeclaredReturnType = New->getDeclaredReturnType(); 3694 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 3695 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType, 3696 OldDeclaredReturnType)) { 3697 QualType ResQT; 3698 if (NewDeclaredReturnType->isObjCObjectPointerType() && 3699 OldDeclaredReturnType->isObjCObjectPointerType()) 3700 // FIXME: This does the wrong thing for a deduced return type. 3701 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 3702 if (ResQT.isNull()) { 3703 if (New->isCXXClassMember() && New->isOutOfLine()) 3704 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 3705 << New << New->getReturnTypeSourceRange(); 3706 else 3707 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 3708 << New->getReturnTypeSourceRange(); 3709 Diag(OldLocation, PrevDiag) << Old << Old->getType() 3710 << Old->getReturnTypeSourceRange(); 3711 return true; 3712 } 3713 else 3714 NewQType = ResQT; 3715 } 3716 3717 QualType OldReturnType = OldType->getReturnType(); 3718 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 3719 if (OldReturnType != NewReturnType) { 3720 // If this function has a deduced return type and has already been 3721 // defined, copy the deduced value from the old declaration. 3722 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 3723 if (OldAT && OldAT->isDeduced()) { 3724 QualType DT = OldAT->getDeducedType(); 3725 if (DT.isNull()) { 3726 New->setType(SubstAutoTypeDependent(New->getType())); 3727 NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType)); 3728 } else { 3729 New->setType(SubstAutoType(New->getType(), DT)); 3730 NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT)); 3731 } 3732 } 3733 } 3734 3735 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 3736 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 3737 if (OldMethod && NewMethod) { 3738 // Preserve triviality. 3739 NewMethod->setTrivial(OldMethod->isTrivial()); 3740 3741 // MSVC allows explicit template specialization at class scope: 3742 // 2 CXXMethodDecls referring to the same function will be injected. 3743 // We don't want a redeclaration error. 3744 bool IsClassScopeExplicitSpecialization = 3745 OldMethod->isFunctionTemplateSpecialization() && 3746 NewMethod->isFunctionTemplateSpecialization(); 3747 bool isFriend = NewMethod->getFriendObjectKind(); 3748 3749 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 3750 !IsClassScopeExplicitSpecialization) { 3751 // -- Member function declarations with the same name and the 3752 // same parameter types cannot be overloaded if any of them 3753 // is a static member function declaration. 3754 if (OldMethod->isStatic() != NewMethod->isStatic()) { 3755 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 3756 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3757 return true; 3758 } 3759 3760 // C++ [class.mem]p1: 3761 // [...] A member shall not be declared twice in the 3762 // member-specification, except that a nested class or member 3763 // class template can be declared and then later defined. 3764 if (!inTemplateInstantiation()) { 3765 unsigned NewDiag; 3766 if (isa<CXXConstructorDecl>(OldMethod)) 3767 NewDiag = diag::err_constructor_redeclared; 3768 else if (isa<CXXDestructorDecl>(NewMethod)) 3769 NewDiag = diag::err_destructor_redeclared; 3770 else if (isa<CXXConversionDecl>(NewMethod)) 3771 NewDiag = diag::err_conv_function_redeclared; 3772 else 3773 NewDiag = diag::err_member_redeclared; 3774 3775 Diag(New->getLocation(), NewDiag); 3776 } else { 3777 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 3778 << New << New->getType(); 3779 } 3780 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3781 return true; 3782 3783 // Complain if this is an explicit declaration of a special 3784 // member that was initially declared implicitly. 3785 // 3786 // As an exception, it's okay to befriend such methods in order 3787 // to permit the implicit constructor/destructor/operator calls. 3788 } else if (OldMethod->isImplicit()) { 3789 if (isFriend) { 3790 NewMethod->setImplicit(); 3791 } else { 3792 Diag(NewMethod->getLocation(), 3793 diag::err_definition_of_implicitly_declared_member) 3794 << New << getSpecialMember(OldMethod); 3795 return true; 3796 } 3797 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 3798 Diag(NewMethod->getLocation(), 3799 diag::err_definition_of_explicitly_defaulted_member) 3800 << getSpecialMember(OldMethod); 3801 return true; 3802 } 3803 } 3804 3805 // C++11 [dcl.attr.noreturn]p1: 3806 // The first declaration of a function shall specify the noreturn 3807 // attribute if any declaration of that function specifies the noreturn 3808 // attribute. 3809 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>()) 3810 if (!Old->hasAttr<CXX11NoReturnAttr>()) { 3811 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl) 3812 << NRA; 3813 Diag(Old->getLocation(), diag::note_previous_declaration); 3814 } 3815 3816 // C++11 [dcl.attr.depend]p2: 3817 // The first declaration of a function shall specify the 3818 // carries_dependency attribute for its declarator-id if any declaration 3819 // of the function specifies the carries_dependency attribute. 3820 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 3821 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 3822 Diag(CDA->getLocation(), 3823 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 3824 Diag(Old->getFirstDecl()->getLocation(), 3825 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 3826 } 3827 3828 // (C++98 8.3.5p3): 3829 // All declarations for a function shall agree exactly in both the 3830 // return type and the parameter-type-list. 3831 // We also want to respect all the extended bits except noreturn. 3832 3833 // noreturn should now match unless the old type info didn't have it. 3834 QualType OldQTypeForComparison = OldQType; 3835 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3836 auto *OldType = OldQType->castAs<FunctionProtoType>(); 3837 const FunctionType *OldTypeForComparison 3838 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3839 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3840 assert(OldQTypeForComparison.isCanonical()); 3841 } 3842 3843 if (haveIncompatibleLanguageLinkages(Old, New)) { 3844 // As a special case, retain the language linkage from previous 3845 // declarations of a friend function as an extension. 3846 // 3847 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3848 // and is useful because there's otherwise no way to specify language 3849 // linkage within class scope. 3850 // 3851 // Check cautiously as the friend object kind isn't yet complete. 3852 if (New->getFriendObjectKind() != Decl::FOK_None) { 3853 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3854 Diag(OldLocation, PrevDiag); 3855 } else { 3856 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3857 Diag(OldLocation, PrevDiag); 3858 return true; 3859 } 3860 } 3861 3862 // If the function types are compatible, merge the declarations. Ignore the 3863 // exception specifier because it was already checked above in 3864 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics 3865 // about incompatible types under -fms-compatibility. 3866 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison, 3867 NewQType)) 3868 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3869 3870 // If the types are imprecise (due to dependent constructs in friends or 3871 // local extern declarations), it's OK if they differ. We'll check again 3872 // during instantiation. 3873 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType)) 3874 return false; 3875 3876 // Fall through for conflicting redeclarations and redefinitions. 3877 } 3878 3879 // C: Function types need to be compatible, not identical. This handles 3880 // duplicate function decls like "void f(int); void f(enum X);" properly. 3881 if (!getLangOpts().CPlusPlus) { 3882 // If we are merging two functions where only one of them has a prototype, 3883 // we may have enough information to decide to issue a diagnostic that the 3884 // function without a protoype will change behavior in C2x. This handles 3885 // cases like: 3886 // void i(); void i(int j); 3887 // void i(int j); void i(); 3888 // void i(); void i(int j) {} 3889 // See ActOnFinishFunctionBody() for other cases of the behavior change 3890 // diagnostic. See GetFullTypeForDeclarator() for handling of a function 3891 // type without a prototype. 3892 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() && 3893 !New->isImplicit() && !Old->isImplicit()) { 3894 const FunctionDecl *WithProto, *WithoutProto; 3895 if (New->hasWrittenPrototype()) { 3896 WithProto = New; 3897 WithoutProto = Old; 3898 } else { 3899 WithProto = Old; 3900 WithoutProto = New; 3901 } 3902 3903 if (WithProto->getNumParams() != 0) { 3904 // The function definition has parameters, so this will change 3905 // behavior in C2x. 3906 // 3907 // If we already warned about about the function without a prototype 3908 // being deprecated, add a note that it also changes behavior. If we 3909 // didn't warn about it being deprecated (because the diagnostic is 3910 // not enabled), warn now that it is deprecated and changes behavior. 3911 bool AddNote = false; 3912 if (Diags.isIgnored(diag::warn_strict_prototypes, 3913 WithoutProto->getLocation())) { 3914 if (WithoutProto->getBuiltinID() == 0 && 3915 !WithoutProto->isImplicit() && 3916 SourceMgr.isBeforeInTranslationUnit(WithoutProto->getLocation(), 3917 WithProto->getLocation())) { 3918 PartialDiagnostic PD = 3919 PDiag(diag::warn_non_prototype_changes_behavior); 3920 if (TypeSourceInfo *TSI = WithoutProto->getTypeSourceInfo()) { 3921 if (auto FTL = TSI->getTypeLoc().getAs<FunctionNoProtoTypeLoc>()) 3922 PD << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); 3923 } 3924 Diag(WithoutProto->getLocation(), PD); 3925 } 3926 } else { 3927 AddNote = true; 3928 } 3929 3930 // Because the function with a prototype has parameters but a previous 3931 // declaration had none, the function with the prototype will also 3932 // change behavior in C2x. 3933 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit()) { 3934 if (SourceMgr.isBeforeInTranslationUnit( 3935 WithProto->getLocation(), WithoutProto->getLocation())) { 3936 // If the function with the prototype comes before the function 3937 // without the prototype, we only want to diagnose the one without 3938 // the prototype. 3939 Diag(WithoutProto->getLocation(), 3940 diag::warn_non_prototype_changes_behavior); 3941 } else { 3942 // Otherwise, diagnose the one with the prototype, and potentially 3943 // attach a note to the one without a prototype if needed. 3944 Diag(WithProto->getLocation(), 3945 diag::warn_non_prototype_changes_behavior); 3946 if (AddNote && WithoutProto->getBuiltinID() == 0) 3947 Diag(WithoutProto->getLocation(), 3948 diag::note_func_decl_changes_behavior); 3949 } 3950 } else if (AddNote && WithoutProto->getBuiltinID() == 0 && 3951 !WithoutProto->isImplicit()) { 3952 // If we were supposed to add a note but the function with a 3953 // prototype is a builtin or was implicitly declared, which means we 3954 // have nothing to attach the note to, so we issue a warning instead. 3955 Diag(WithoutProto->getLocation(), 3956 diag::warn_non_prototype_changes_behavior); 3957 } 3958 } 3959 } 3960 3961 if (Context.typesAreCompatible(OldQType, NewQType)) { 3962 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 3963 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 3964 const FunctionProtoType *OldProto = nullptr; 3965 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 3966 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 3967 // The old declaration provided a function prototype, but the 3968 // new declaration does not. Merge in the prototype. 3969 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 3970 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 3971 NewQType = 3972 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 3973 OldProto->getExtProtoInfo()); 3974 New->setType(NewQType); 3975 New->setHasInheritedPrototype(); 3976 3977 // Synthesize parameters with the same types. 3978 SmallVector<ParmVarDecl *, 16> Params; 3979 for (const auto &ParamType : OldProto->param_types()) { 3980 ParmVarDecl *Param = ParmVarDecl::Create( 3981 Context, New, SourceLocation(), SourceLocation(), nullptr, 3982 ParamType, /*TInfo=*/nullptr, SC_None, nullptr); 3983 Param->setScopeInfo(0, Params.size()); 3984 Param->setImplicit(); 3985 Params.push_back(Param); 3986 } 3987 3988 New->setParams(Params); 3989 } 3990 3991 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3992 } 3993 } 3994 3995 // Check if the function types are compatible when pointer size address 3996 // spaces are ignored. 3997 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType)) 3998 return false; 3999 4000 // GNU C permits a K&R definition to follow a prototype declaration 4001 // if the declared types of the parameters in the K&R definition 4002 // match the types in the prototype declaration, even when the 4003 // promoted types of the parameters from the K&R definition differ 4004 // from the types in the prototype. GCC then keeps the types from 4005 // the prototype. 4006 // 4007 // If a variadic prototype is followed by a non-variadic K&R definition, 4008 // the K&R definition becomes variadic. This is sort of an edge case, but 4009 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 4010 // C99 6.9.1p8. 4011 if (!getLangOpts().CPlusPlus && 4012 Old->hasPrototype() && !New->hasPrototype() && 4013 New->getType()->getAs<FunctionProtoType>() && 4014 Old->getNumParams() == New->getNumParams()) { 4015 SmallVector<QualType, 16> ArgTypes; 4016 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 4017 const FunctionProtoType *OldProto 4018 = Old->getType()->getAs<FunctionProtoType>(); 4019 const FunctionProtoType *NewProto 4020 = New->getType()->getAs<FunctionProtoType>(); 4021 4022 // Determine whether this is the GNU C extension. 4023 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 4024 NewProto->getReturnType()); 4025 bool LooseCompatible = !MergedReturn.isNull(); 4026 for (unsigned Idx = 0, End = Old->getNumParams(); 4027 LooseCompatible && Idx != End; ++Idx) { 4028 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 4029 ParmVarDecl *NewParm = New->getParamDecl(Idx); 4030 if (Context.typesAreCompatible(OldParm->getType(), 4031 NewProto->getParamType(Idx))) { 4032 ArgTypes.push_back(NewParm->getType()); 4033 } else if (Context.typesAreCompatible(OldParm->getType(), 4034 NewParm->getType(), 4035 /*CompareUnqualified=*/true)) { 4036 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 4037 NewProto->getParamType(Idx) }; 4038 Warnings.push_back(Warn); 4039 ArgTypes.push_back(NewParm->getType()); 4040 } else 4041 LooseCompatible = false; 4042 } 4043 4044 if (LooseCompatible) { 4045 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 4046 Diag(Warnings[Warn].NewParm->getLocation(), 4047 diag::ext_param_promoted_not_compatible_with_prototype) 4048 << Warnings[Warn].PromotedType 4049 << Warnings[Warn].OldParm->getType(); 4050 if (Warnings[Warn].OldParm->getLocation().isValid()) 4051 Diag(Warnings[Warn].OldParm->getLocation(), 4052 diag::note_previous_declaration); 4053 } 4054 4055 if (MergeTypeWithOld) 4056 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 4057 OldProto->getExtProtoInfo())); 4058 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 4059 } 4060 4061 // Fall through to diagnose conflicting types. 4062 } 4063 4064 // A function that has already been declared has been redeclared or 4065 // defined with a different type; show an appropriate diagnostic. 4066 4067 // If the previous declaration was an implicitly-generated builtin 4068 // declaration, then at the very least we should use a specialized note. 4069 unsigned BuiltinID; 4070 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 4071 // If it's actually a library-defined builtin function like 'malloc' 4072 // or 'printf', just warn about the incompatible redeclaration. 4073 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 4074 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 4075 Diag(OldLocation, diag::note_previous_builtin_declaration) 4076 << Old << Old->getType(); 4077 return false; 4078 } 4079 4080 PrevDiag = diag::note_previous_builtin_declaration; 4081 } 4082 4083 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 4084 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 4085 return true; 4086 } 4087 4088 /// Completes the merge of two function declarations that are 4089 /// known to be compatible. 4090 /// 4091 /// This routine handles the merging of attributes and other 4092 /// properties of function declarations from the old declaration to 4093 /// the new declaration, once we know that New is in fact a 4094 /// redeclaration of Old. 4095 /// 4096 /// \returns false 4097 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 4098 Scope *S, bool MergeTypeWithOld) { 4099 // Merge the attributes 4100 mergeDeclAttributes(New, Old); 4101 4102 // Merge "pure" flag. 4103 if (Old->isPure()) 4104 New->setPure(); 4105 4106 // Merge "used" flag. 4107 if (Old->getMostRecentDecl()->isUsed(false)) 4108 New->setIsUsed(); 4109 4110 // Merge attributes from the parameters. These can mismatch with K&R 4111 // declarations. 4112 if (New->getNumParams() == Old->getNumParams()) 4113 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 4114 ParmVarDecl *NewParam = New->getParamDecl(i); 4115 ParmVarDecl *OldParam = Old->getParamDecl(i); 4116 mergeParamDeclAttributes(NewParam, OldParam, *this); 4117 mergeParamDeclTypes(NewParam, OldParam, *this); 4118 } 4119 4120 if (getLangOpts().CPlusPlus) 4121 return MergeCXXFunctionDecl(New, Old, S); 4122 4123 // Merge the function types so the we get the composite types for the return 4124 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 4125 // was visible. 4126 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 4127 if (!Merged.isNull() && MergeTypeWithOld) 4128 New->setType(Merged); 4129 4130 return false; 4131 } 4132 4133 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 4134 ObjCMethodDecl *oldMethod) { 4135 // Merge the attributes, including deprecated/unavailable 4136 AvailabilityMergeKind MergeKind = 4137 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 4138 ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation 4139 : AMK_ProtocolImplementation) 4140 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 4141 : AMK_Override; 4142 4143 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 4144 4145 // Merge attributes from the parameters. 4146 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 4147 oe = oldMethod->param_end(); 4148 for (ObjCMethodDecl::param_iterator 4149 ni = newMethod->param_begin(), ne = newMethod->param_end(); 4150 ni != ne && oi != oe; ++ni, ++oi) 4151 mergeParamDeclAttributes(*ni, *oi, *this); 4152 4153 CheckObjCMethodOverride(newMethod, oldMethod); 4154 } 4155 4156 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 4157 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 4158 4159 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 4160 ? diag::err_redefinition_different_type 4161 : diag::err_redeclaration_different_type) 4162 << New->getDeclName() << New->getType() << Old->getType(); 4163 4164 diag::kind PrevDiag; 4165 SourceLocation OldLocation; 4166 std::tie(PrevDiag, OldLocation) 4167 = getNoteDiagForInvalidRedeclaration(Old, New); 4168 S.Diag(OldLocation, PrevDiag); 4169 New->setInvalidDecl(); 4170 } 4171 4172 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 4173 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 4174 /// emitting diagnostics as appropriate. 4175 /// 4176 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 4177 /// to here in AddInitializerToDecl. We can't check them before the initializer 4178 /// is attached. 4179 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 4180 bool MergeTypeWithOld) { 4181 if (New->isInvalidDecl() || Old->isInvalidDecl()) 4182 return; 4183 4184 QualType MergedT; 4185 if (getLangOpts().CPlusPlus) { 4186 if (New->getType()->isUndeducedType()) { 4187 // We don't know what the new type is until the initializer is attached. 4188 return; 4189 } else if (Context.hasSameType(New->getType(), Old->getType())) { 4190 // These could still be something that needs exception specs checked. 4191 return MergeVarDeclExceptionSpecs(New, Old); 4192 } 4193 // C++ [basic.link]p10: 4194 // [...] the types specified by all declarations referring to a given 4195 // object or function shall be identical, except that declarations for an 4196 // array object can specify array types that differ by the presence or 4197 // absence of a major array bound (8.3.4). 4198 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 4199 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 4200 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 4201 4202 // We are merging a variable declaration New into Old. If it has an array 4203 // bound, and that bound differs from Old's bound, we should diagnose the 4204 // mismatch. 4205 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 4206 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 4207 PrevVD = PrevVD->getPreviousDecl()) { 4208 QualType PrevVDTy = PrevVD->getType(); 4209 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 4210 continue; 4211 4212 if (!Context.hasSameType(New->getType(), PrevVDTy)) 4213 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 4214 } 4215 } 4216 4217 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 4218 if (Context.hasSameType(OldArray->getElementType(), 4219 NewArray->getElementType())) 4220 MergedT = New->getType(); 4221 } 4222 // FIXME: Check visibility. New is hidden but has a complete type. If New 4223 // has no array bound, it should not inherit one from Old, if Old is not 4224 // visible. 4225 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 4226 if (Context.hasSameType(OldArray->getElementType(), 4227 NewArray->getElementType())) 4228 MergedT = Old->getType(); 4229 } 4230 } 4231 else if (New->getType()->isObjCObjectPointerType() && 4232 Old->getType()->isObjCObjectPointerType()) { 4233 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 4234 Old->getType()); 4235 } 4236 } else { 4237 // C 6.2.7p2: 4238 // All declarations that refer to the same object or function shall have 4239 // compatible type. 4240 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 4241 } 4242 if (MergedT.isNull()) { 4243 // It's OK if we couldn't merge types if either type is dependent, for a 4244 // block-scope variable. In other cases (static data members of class 4245 // templates, variable templates, ...), we require the types to be 4246 // equivalent. 4247 // FIXME: The C++ standard doesn't say anything about this. 4248 if ((New->getType()->isDependentType() || 4249 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 4250 // If the old type was dependent, we can't merge with it, so the new type 4251 // becomes dependent for now. We'll reproduce the original type when we 4252 // instantiate the TypeSourceInfo for the variable. 4253 if (!New->getType()->isDependentType() && MergeTypeWithOld) 4254 New->setType(Context.DependentTy); 4255 return; 4256 } 4257 return diagnoseVarDeclTypeMismatch(*this, New, Old); 4258 } 4259 4260 // Don't actually update the type on the new declaration if the old 4261 // declaration was an extern declaration in a different scope. 4262 if (MergeTypeWithOld) 4263 New->setType(MergedT); 4264 } 4265 4266 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 4267 LookupResult &Previous) { 4268 // C11 6.2.7p4: 4269 // For an identifier with internal or external linkage declared 4270 // in a scope in which a prior declaration of that identifier is 4271 // visible, if the prior declaration specifies internal or 4272 // external linkage, the type of the identifier at the later 4273 // declaration becomes the composite type. 4274 // 4275 // If the variable isn't visible, we do not merge with its type. 4276 if (Previous.isShadowed()) 4277 return false; 4278 4279 if (S.getLangOpts().CPlusPlus) { 4280 // C++11 [dcl.array]p3: 4281 // If there is a preceding declaration of the entity in the same 4282 // scope in which the bound was specified, an omitted array bound 4283 // is taken to be the same as in that earlier declaration. 4284 return NewVD->isPreviousDeclInSameBlockScope() || 4285 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 4286 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 4287 } else { 4288 // If the old declaration was function-local, don't merge with its 4289 // type unless we're in the same function. 4290 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 4291 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 4292 } 4293 } 4294 4295 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 4296 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 4297 /// situation, merging decls or emitting diagnostics as appropriate. 4298 /// 4299 /// Tentative definition rules (C99 6.9.2p2) are checked by 4300 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 4301 /// definitions here, since the initializer hasn't been attached. 4302 /// 4303 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 4304 // If the new decl is already invalid, don't do any other checking. 4305 if (New->isInvalidDecl()) 4306 return; 4307 4308 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 4309 return; 4310 4311 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 4312 4313 // Verify the old decl was also a variable or variable template. 4314 VarDecl *Old = nullptr; 4315 VarTemplateDecl *OldTemplate = nullptr; 4316 if (Previous.isSingleResult()) { 4317 if (NewTemplate) { 4318 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 4319 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 4320 4321 if (auto *Shadow = 4322 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4323 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 4324 return New->setInvalidDecl(); 4325 } else { 4326 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 4327 4328 if (auto *Shadow = 4329 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4330 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 4331 return New->setInvalidDecl(); 4332 } 4333 } 4334 if (!Old) { 4335 Diag(New->getLocation(), diag::err_redefinition_different_kind) 4336 << New->getDeclName(); 4337 notePreviousDefinition(Previous.getRepresentativeDecl(), 4338 New->getLocation()); 4339 return New->setInvalidDecl(); 4340 } 4341 4342 // If the old declaration was found in an inline namespace and the new 4343 // declaration was qualified, update the DeclContext to match. 4344 adjustDeclContextForDeclaratorDecl(New, Old); 4345 4346 // Ensure the template parameters are compatible. 4347 if (NewTemplate && 4348 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 4349 OldTemplate->getTemplateParameters(), 4350 /*Complain=*/true, TPL_TemplateMatch)) 4351 return New->setInvalidDecl(); 4352 4353 // C++ [class.mem]p1: 4354 // A member shall not be declared twice in the member-specification [...] 4355 // 4356 // Here, we need only consider static data members. 4357 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 4358 Diag(New->getLocation(), diag::err_duplicate_member) 4359 << New->getIdentifier(); 4360 Diag(Old->getLocation(), diag::note_previous_declaration); 4361 New->setInvalidDecl(); 4362 } 4363 4364 mergeDeclAttributes(New, Old); 4365 // Warn if an already-declared variable is made a weak_import in a subsequent 4366 // declaration 4367 if (New->hasAttr<WeakImportAttr>() && 4368 Old->getStorageClass() == SC_None && 4369 !Old->hasAttr<WeakImportAttr>()) { 4370 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 4371 Diag(Old->getLocation(), diag::note_previous_declaration); 4372 // Remove weak_import attribute on new declaration. 4373 New->dropAttr<WeakImportAttr>(); 4374 } 4375 4376 if (const auto *ILA = New->getAttr<InternalLinkageAttr>()) 4377 if (!Old->hasAttr<InternalLinkageAttr>()) { 4378 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl) 4379 << ILA; 4380 Diag(Old->getLocation(), diag::note_previous_declaration); 4381 New->dropAttr<InternalLinkageAttr>(); 4382 } 4383 4384 // Merge the types. 4385 VarDecl *MostRecent = Old->getMostRecentDecl(); 4386 if (MostRecent != Old) { 4387 MergeVarDeclTypes(New, MostRecent, 4388 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 4389 if (New->isInvalidDecl()) 4390 return; 4391 } 4392 4393 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 4394 if (New->isInvalidDecl()) 4395 return; 4396 4397 diag::kind PrevDiag; 4398 SourceLocation OldLocation; 4399 std::tie(PrevDiag, OldLocation) = 4400 getNoteDiagForInvalidRedeclaration(Old, New); 4401 4402 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 4403 if (New->getStorageClass() == SC_Static && 4404 !New->isStaticDataMember() && 4405 Old->hasExternalFormalLinkage()) { 4406 if (getLangOpts().MicrosoftExt) { 4407 Diag(New->getLocation(), diag::ext_static_non_static) 4408 << New->getDeclName(); 4409 Diag(OldLocation, PrevDiag); 4410 } else { 4411 Diag(New->getLocation(), diag::err_static_non_static) 4412 << New->getDeclName(); 4413 Diag(OldLocation, PrevDiag); 4414 return New->setInvalidDecl(); 4415 } 4416 } 4417 // C99 6.2.2p4: 4418 // For an identifier declared with the storage-class specifier 4419 // extern in a scope in which a prior declaration of that 4420 // identifier is visible,23) if the prior declaration specifies 4421 // internal or external linkage, the linkage of the identifier at 4422 // the later declaration is the same as the linkage specified at 4423 // the prior declaration. If no prior declaration is visible, or 4424 // if the prior declaration specifies no linkage, then the 4425 // identifier has external linkage. 4426 if (New->hasExternalStorage() && Old->hasLinkage()) 4427 /* Okay */; 4428 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 4429 !New->isStaticDataMember() && 4430 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 4431 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 4432 Diag(OldLocation, PrevDiag); 4433 return New->setInvalidDecl(); 4434 } 4435 4436 // Check if extern is followed by non-extern and vice-versa. 4437 if (New->hasExternalStorage() && 4438 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 4439 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 4440 Diag(OldLocation, PrevDiag); 4441 return New->setInvalidDecl(); 4442 } 4443 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 4444 !New->hasExternalStorage()) { 4445 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 4446 Diag(OldLocation, PrevDiag); 4447 return New->setInvalidDecl(); 4448 } 4449 4450 if (CheckRedeclarationInModule(New, Old)) 4451 return; 4452 4453 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 4454 4455 // FIXME: The test for external storage here seems wrong? We still 4456 // need to check for mismatches. 4457 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 4458 // Don't complain about out-of-line definitions of static members. 4459 !(Old->getLexicalDeclContext()->isRecord() && 4460 !New->getLexicalDeclContext()->isRecord())) { 4461 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 4462 Diag(OldLocation, PrevDiag); 4463 return New->setInvalidDecl(); 4464 } 4465 4466 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 4467 if (VarDecl *Def = Old->getDefinition()) { 4468 // C++1z [dcl.fcn.spec]p4: 4469 // If the definition of a variable appears in a translation unit before 4470 // its first declaration as inline, the program is ill-formed. 4471 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 4472 Diag(Def->getLocation(), diag::note_previous_definition); 4473 } 4474 } 4475 4476 // If this redeclaration makes the variable inline, we may need to add it to 4477 // UndefinedButUsed. 4478 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 4479 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 4480 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 4481 SourceLocation())); 4482 4483 if (New->getTLSKind() != Old->getTLSKind()) { 4484 if (!Old->getTLSKind()) { 4485 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 4486 Diag(OldLocation, PrevDiag); 4487 } else if (!New->getTLSKind()) { 4488 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 4489 Diag(OldLocation, PrevDiag); 4490 } else { 4491 // Do not allow redeclaration to change the variable between requiring 4492 // static and dynamic initialization. 4493 // FIXME: GCC allows this, but uses the TLS keyword on the first 4494 // declaration to determine the kind. Do we need to be compatible here? 4495 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 4496 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 4497 Diag(OldLocation, PrevDiag); 4498 } 4499 } 4500 4501 // C++ doesn't have tentative definitions, so go right ahead and check here. 4502 if (getLangOpts().CPlusPlus && 4503 New->isThisDeclarationADefinition() == VarDecl::Definition) { 4504 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 4505 Old->getCanonicalDecl()->isConstexpr()) { 4506 // This definition won't be a definition any more once it's been merged. 4507 Diag(New->getLocation(), 4508 diag::warn_deprecated_redundant_constexpr_static_def); 4509 } else if (VarDecl *Def = Old->getDefinition()) { 4510 if (checkVarDeclRedefinition(Def, New)) 4511 return; 4512 } 4513 } 4514 4515 if (haveIncompatibleLanguageLinkages(Old, New)) { 4516 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 4517 Diag(OldLocation, PrevDiag); 4518 New->setInvalidDecl(); 4519 return; 4520 } 4521 4522 // Merge "used" flag. 4523 if (Old->getMostRecentDecl()->isUsed(false)) 4524 New->setIsUsed(); 4525 4526 // Keep a chain of previous declarations. 4527 New->setPreviousDecl(Old); 4528 if (NewTemplate) 4529 NewTemplate->setPreviousDecl(OldTemplate); 4530 4531 // Inherit access appropriately. 4532 New->setAccess(Old->getAccess()); 4533 if (NewTemplate) 4534 NewTemplate->setAccess(New->getAccess()); 4535 4536 if (Old->isInline()) 4537 New->setImplicitlyInline(); 4538 } 4539 4540 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { 4541 SourceManager &SrcMgr = getSourceManager(); 4542 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); 4543 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); 4544 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); 4545 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); 4546 auto &HSI = PP.getHeaderSearchInfo(); 4547 StringRef HdrFilename = 4548 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); 4549 4550 auto noteFromModuleOrInclude = [&](Module *Mod, 4551 SourceLocation IncLoc) -> bool { 4552 // Redefinition errors with modules are common with non modular mapped 4553 // headers, example: a non-modular header H in module A that also gets 4554 // included directly in a TU. Pointing twice to the same header/definition 4555 // is confusing, try to get better diagnostics when modules is on. 4556 if (IncLoc.isValid()) { 4557 if (Mod) { 4558 Diag(IncLoc, diag::note_redefinition_modules_same_file) 4559 << HdrFilename.str() << Mod->getFullModuleName(); 4560 if (!Mod->DefinitionLoc.isInvalid()) 4561 Diag(Mod->DefinitionLoc, diag::note_defined_here) 4562 << Mod->getFullModuleName(); 4563 } else { 4564 Diag(IncLoc, diag::note_redefinition_include_same_file) 4565 << HdrFilename.str(); 4566 } 4567 return true; 4568 } 4569 4570 return false; 4571 }; 4572 4573 // Is it the same file and same offset? Provide more information on why 4574 // this leads to a redefinition error. 4575 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { 4576 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); 4577 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); 4578 bool EmittedDiag = 4579 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); 4580 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); 4581 4582 // If the header has no guards, emit a note suggesting one. 4583 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) 4584 Diag(Old->getLocation(), diag::note_use_ifdef_guards); 4585 4586 if (EmittedDiag) 4587 return; 4588 } 4589 4590 // Redefinition coming from different files or couldn't do better above. 4591 if (Old->getLocation().isValid()) 4592 Diag(Old->getLocation(), diag::note_previous_definition); 4593 } 4594 4595 /// We've just determined that \p Old and \p New both appear to be definitions 4596 /// of the same variable. Either diagnose or fix the problem. 4597 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 4598 if (!hasVisibleDefinition(Old) && 4599 (New->getFormalLinkage() == InternalLinkage || 4600 New->isInline() || 4601 New->getDescribedVarTemplate() || 4602 New->getNumTemplateParameterLists() || 4603 New->getDeclContext()->isDependentContext())) { 4604 // The previous definition is hidden, and multiple definitions are 4605 // permitted (in separate TUs). Demote this to a declaration. 4606 New->demoteThisDefinitionToDeclaration(); 4607 4608 // Make the canonical definition visible. 4609 if (auto *OldTD = Old->getDescribedVarTemplate()) 4610 makeMergedDefinitionVisible(OldTD); 4611 makeMergedDefinitionVisible(Old); 4612 return false; 4613 } else { 4614 Diag(New->getLocation(), diag::err_redefinition) << New; 4615 notePreviousDefinition(Old, New->getLocation()); 4616 New->setInvalidDecl(); 4617 return true; 4618 } 4619 } 4620 4621 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4622 /// no declarator (e.g. "struct foo;") is parsed. 4623 Decl * 4624 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4625 RecordDecl *&AnonRecord) { 4626 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, 4627 AnonRecord); 4628 } 4629 4630 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 4631 // disambiguate entities defined in different scopes. 4632 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 4633 // compatibility. 4634 // We will pick our mangling number depending on which version of MSVC is being 4635 // targeted. 4636 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 4637 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 4638 ? S->getMSCurManglingNumber() 4639 : S->getMSLastManglingNumber(); 4640 } 4641 4642 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 4643 if (!Context.getLangOpts().CPlusPlus) 4644 return; 4645 4646 if (isa<CXXRecordDecl>(Tag->getParent())) { 4647 // If this tag is the direct child of a class, number it if 4648 // it is anonymous. 4649 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 4650 return; 4651 MangleNumberingContext &MCtx = 4652 Context.getManglingNumberContext(Tag->getParent()); 4653 Context.setManglingNumber( 4654 Tag, MCtx.getManglingNumber( 4655 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4656 return; 4657 } 4658 4659 // If this tag isn't a direct child of a class, number it if it is local. 4660 MangleNumberingContext *MCtx; 4661 Decl *ManglingContextDecl; 4662 std::tie(MCtx, ManglingContextDecl) = 4663 getCurrentMangleNumberContext(Tag->getDeclContext()); 4664 if (MCtx) { 4665 Context.setManglingNumber( 4666 Tag, MCtx->getManglingNumber( 4667 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4668 } 4669 } 4670 4671 namespace { 4672 struct NonCLikeKind { 4673 enum { 4674 None, 4675 BaseClass, 4676 DefaultMemberInit, 4677 Lambda, 4678 Friend, 4679 OtherMember, 4680 Invalid, 4681 } Kind = None; 4682 SourceRange Range; 4683 4684 explicit operator bool() { return Kind != None; } 4685 }; 4686 } 4687 4688 /// Determine whether a class is C-like, according to the rules of C++ 4689 /// [dcl.typedef] for anonymous classes with typedef names for linkage. 4690 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) { 4691 if (RD->isInvalidDecl()) 4692 return {NonCLikeKind::Invalid, {}}; 4693 4694 // C++ [dcl.typedef]p9: [P1766R1] 4695 // An unnamed class with a typedef name for linkage purposes shall not 4696 // 4697 // -- have any base classes 4698 if (RD->getNumBases()) 4699 return {NonCLikeKind::BaseClass, 4700 SourceRange(RD->bases_begin()->getBeginLoc(), 4701 RD->bases_end()[-1].getEndLoc())}; 4702 bool Invalid = false; 4703 for (Decl *D : RD->decls()) { 4704 // Don't complain about things we already diagnosed. 4705 if (D->isInvalidDecl()) { 4706 Invalid = true; 4707 continue; 4708 } 4709 4710 // -- have any [...] default member initializers 4711 if (auto *FD = dyn_cast<FieldDecl>(D)) { 4712 if (FD->hasInClassInitializer()) { 4713 auto *Init = FD->getInClassInitializer(); 4714 return {NonCLikeKind::DefaultMemberInit, 4715 Init ? Init->getSourceRange() : D->getSourceRange()}; 4716 } 4717 continue; 4718 } 4719 4720 // FIXME: We don't allow friend declarations. This violates the wording of 4721 // P1766, but not the intent. 4722 if (isa<FriendDecl>(D)) 4723 return {NonCLikeKind::Friend, D->getSourceRange()}; 4724 4725 // -- declare any members other than non-static data members, member 4726 // enumerations, or member classes, 4727 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) || 4728 isa<EnumDecl>(D)) 4729 continue; 4730 auto *MemberRD = dyn_cast<CXXRecordDecl>(D); 4731 if (!MemberRD) { 4732 if (D->isImplicit()) 4733 continue; 4734 return {NonCLikeKind::OtherMember, D->getSourceRange()}; 4735 } 4736 4737 // -- contain a lambda-expression, 4738 if (MemberRD->isLambda()) 4739 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()}; 4740 4741 // and all member classes shall also satisfy these requirements 4742 // (recursively). 4743 if (MemberRD->isThisDeclarationADefinition()) { 4744 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD)) 4745 return Kind; 4746 } 4747 } 4748 4749 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}}; 4750 } 4751 4752 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 4753 TypedefNameDecl *NewTD) { 4754 if (TagFromDeclSpec->isInvalidDecl()) 4755 return; 4756 4757 // Do nothing if the tag already has a name for linkage purposes. 4758 if (TagFromDeclSpec->hasNameForLinkage()) 4759 return; 4760 4761 // A well-formed anonymous tag must always be a TUK_Definition. 4762 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 4763 4764 // The type must match the tag exactly; no qualifiers allowed. 4765 if (!Context.hasSameType(NewTD->getUnderlyingType(), 4766 Context.getTagDeclType(TagFromDeclSpec))) { 4767 if (getLangOpts().CPlusPlus) 4768 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 4769 return; 4770 } 4771 4772 // C++ [dcl.typedef]p9: [P1766R1, applied as DR] 4773 // An unnamed class with a typedef name for linkage purposes shall [be 4774 // C-like]. 4775 // 4776 // FIXME: Also diagnose if we've already computed the linkage. That ideally 4777 // shouldn't happen, but there are constructs that the language rule doesn't 4778 // disallow for which we can't reasonably avoid computing linkage early. 4779 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec); 4780 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD) 4781 : NonCLikeKind(); 4782 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed(); 4783 if (NonCLike || ChangesLinkage) { 4784 if (NonCLike.Kind == NonCLikeKind::Invalid) 4785 return; 4786 4787 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef; 4788 if (ChangesLinkage) { 4789 // If the linkage changes, we can't accept this as an extension. 4790 if (NonCLike.Kind == NonCLikeKind::None) 4791 DiagID = diag::err_typedef_changes_linkage; 4792 else 4793 DiagID = diag::err_non_c_like_anon_struct_in_typedef; 4794 } 4795 4796 SourceLocation FixitLoc = 4797 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart()); 4798 llvm::SmallString<40> TextToInsert; 4799 TextToInsert += ' '; 4800 TextToInsert += NewTD->getIdentifier()->getName(); 4801 4802 Diag(FixitLoc, DiagID) 4803 << isa<TypeAliasDecl>(NewTD) 4804 << FixItHint::CreateInsertion(FixitLoc, TextToInsert); 4805 if (NonCLike.Kind != NonCLikeKind::None) { 4806 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct) 4807 << NonCLike.Kind - 1 << NonCLike.Range; 4808 } 4809 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here) 4810 << NewTD << isa<TypeAliasDecl>(NewTD); 4811 4812 if (ChangesLinkage) 4813 return; 4814 } 4815 4816 // Otherwise, set this as the anon-decl typedef for the tag. 4817 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 4818 } 4819 4820 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 4821 switch (T) { 4822 case DeclSpec::TST_class: 4823 return 0; 4824 case DeclSpec::TST_struct: 4825 return 1; 4826 case DeclSpec::TST_interface: 4827 return 2; 4828 case DeclSpec::TST_union: 4829 return 3; 4830 case DeclSpec::TST_enum: 4831 return 4; 4832 default: 4833 llvm_unreachable("unexpected type specifier"); 4834 } 4835 } 4836 4837 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4838 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 4839 /// parameters to cope with template friend declarations. 4840 Decl * 4841 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4842 MultiTemplateParamsArg TemplateParams, 4843 bool IsExplicitInstantiation, 4844 RecordDecl *&AnonRecord) { 4845 Decl *TagD = nullptr; 4846 TagDecl *Tag = nullptr; 4847 if (DS.getTypeSpecType() == DeclSpec::TST_class || 4848 DS.getTypeSpecType() == DeclSpec::TST_struct || 4849 DS.getTypeSpecType() == DeclSpec::TST_interface || 4850 DS.getTypeSpecType() == DeclSpec::TST_union || 4851 DS.getTypeSpecType() == DeclSpec::TST_enum) { 4852 TagD = DS.getRepAsDecl(); 4853 4854 if (!TagD) // We probably had an error 4855 return nullptr; 4856 4857 // Note that the above type specs guarantee that the 4858 // type rep is a Decl, whereas in many of the others 4859 // it's a Type. 4860 if (isa<TagDecl>(TagD)) 4861 Tag = cast<TagDecl>(TagD); 4862 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 4863 Tag = CTD->getTemplatedDecl(); 4864 } 4865 4866 if (Tag) { 4867 handleTagNumbering(Tag, S); 4868 Tag->setFreeStanding(); 4869 if (Tag->isInvalidDecl()) 4870 return Tag; 4871 } 4872 4873 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 4874 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 4875 // or incomplete types shall not be restrict-qualified." 4876 if (TypeQuals & DeclSpec::TQ_restrict) 4877 Diag(DS.getRestrictSpecLoc(), 4878 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 4879 << DS.getSourceRange(); 4880 } 4881 4882 if (DS.isInlineSpecified()) 4883 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 4884 << getLangOpts().CPlusPlus17; 4885 4886 if (DS.hasConstexprSpecifier()) { 4887 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 4888 // and definitions of functions and variables. 4889 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to 4890 // the declaration of a function or function template 4891 if (Tag) 4892 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 4893 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) 4894 << static_cast<int>(DS.getConstexprSpecifier()); 4895 else 4896 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind) 4897 << static_cast<int>(DS.getConstexprSpecifier()); 4898 // Don't emit warnings after this error. 4899 return TagD; 4900 } 4901 4902 DiagnoseFunctionSpecifiers(DS); 4903 4904 if (DS.isFriendSpecified()) { 4905 // If we're dealing with a decl but not a TagDecl, assume that 4906 // whatever routines created it handled the friendship aspect. 4907 if (TagD && !Tag) 4908 return nullptr; 4909 return ActOnFriendTypeDecl(S, DS, TemplateParams); 4910 } 4911 4912 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 4913 bool IsExplicitSpecialization = 4914 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 4915 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 4916 !IsExplicitInstantiation && !IsExplicitSpecialization && 4917 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 4918 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 4919 // nested-name-specifier unless it is an explicit instantiation 4920 // or an explicit specialization. 4921 // 4922 // FIXME: We allow class template partial specializations here too, per the 4923 // obvious intent of DR1819. 4924 // 4925 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 4926 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 4927 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 4928 return nullptr; 4929 } 4930 4931 // Track whether this decl-specifier declares anything. 4932 bool DeclaresAnything = true; 4933 4934 // Handle anonymous struct definitions. 4935 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 4936 if (!Record->getDeclName() && Record->isCompleteDefinition() && 4937 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 4938 if (getLangOpts().CPlusPlus || 4939 Record->getDeclContext()->isRecord()) { 4940 // If CurContext is a DeclContext that can contain statements, 4941 // RecursiveASTVisitor won't visit the decls that 4942 // BuildAnonymousStructOrUnion() will put into CurContext. 4943 // Also store them here so that they can be part of the 4944 // DeclStmt that gets created in this case. 4945 // FIXME: Also return the IndirectFieldDecls created by 4946 // BuildAnonymousStructOr union, for the same reason? 4947 if (CurContext->isFunctionOrMethod()) 4948 AnonRecord = Record; 4949 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 4950 Context.getPrintingPolicy()); 4951 } 4952 4953 DeclaresAnything = false; 4954 } 4955 } 4956 4957 // C11 6.7.2.1p2: 4958 // A struct-declaration that does not declare an anonymous structure or 4959 // anonymous union shall contain a struct-declarator-list. 4960 // 4961 // This rule also existed in C89 and C99; the grammar for struct-declaration 4962 // did not permit a struct-declaration without a struct-declarator-list. 4963 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 4964 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 4965 // Check for Microsoft C extension: anonymous struct/union member. 4966 // Handle 2 kinds of anonymous struct/union: 4967 // struct STRUCT; 4968 // union UNION; 4969 // and 4970 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 4971 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 4972 if ((Tag && Tag->getDeclName()) || 4973 DS.getTypeSpecType() == DeclSpec::TST_typename) { 4974 RecordDecl *Record = nullptr; 4975 if (Tag) 4976 Record = dyn_cast<RecordDecl>(Tag); 4977 else if (const RecordType *RT = 4978 DS.getRepAsType().get()->getAsStructureType()) 4979 Record = RT->getDecl(); 4980 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 4981 Record = UT->getDecl(); 4982 4983 if (Record && getLangOpts().MicrosoftExt) { 4984 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record) 4985 << Record->isUnion() << DS.getSourceRange(); 4986 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 4987 } 4988 4989 DeclaresAnything = false; 4990 } 4991 } 4992 4993 // Skip all the checks below if we have a type error. 4994 if (DS.getTypeSpecType() == DeclSpec::TST_error || 4995 (TagD && TagD->isInvalidDecl())) 4996 return TagD; 4997 4998 if (getLangOpts().CPlusPlus && 4999 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 5000 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 5001 if (Enum->enumerator_begin() == Enum->enumerator_end() && 5002 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 5003 DeclaresAnything = false; 5004 5005 if (!DS.isMissingDeclaratorOk()) { 5006 // Customize diagnostic for a typedef missing a name. 5007 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 5008 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name) 5009 << DS.getSourceRange(); 5010 else 5011 DeclaresAnything = false; 5012 } 5013 5014 if (DS.isModulePrivateSpecified() && 5015 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 5016 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 5017 << Tag->getTagKind() 5018 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 5019 5020 ActOnDocumentableDecl(TagD); 5021 5022 // C 6.7/2: 5023 // A declaration [...] shall declare at least a declarator [...], a tag, 5024 // or the members of an enumeration. 5025 // C++ [dcl.dcl]p3: 5026 // [If there are no declarators], and except for the declaration of an 5027 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 5028 // names into the program, or shall redeclare a name introduced by a 5029 // previous declaration. 5030 if (!DeclaresAnything) { 5031 // In C, we allow this as a (popular) extension / bug. Don't bother 5032 // producing further diagnostics for redundant qualifiers after this. 5033 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty()) 5034 ? diag::err_no_declarators 5035 : diag::ext_no_declarators) 5036 << DS.getSourceRange(); 5037 return TagD; 5038 } 5039 5040 // C++ [dcl.stc]p1: 5041 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 5042 // init-declarator-list of the declaration shall not be empty. 5043 // C++ [dcl.fct.spec]p1: 5044 // If a cv-qualifier appears in a decl-specifier-seq, the 5045 // init-declarator-list of the declaration shall not be empty. 5046 // 5047 // Spurious qualifiers here appear to be valid in C. 5048 unsigned DiagID = diag::warn_standalone_specifier; 5049 if (getLangOpts().CPlusPlus) 5050 DiagID = diag::ext_standalone_specifier; 5051 5052 // Note that a linkage-specification sets a storage class, but 5053 // 'extern "C" struct foo;' is actually valid and not theoretically 5054 // useless. 5055 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 5056 if (SCS == DeclSpec::SCS_mutable) 5057 // Since mutable is not a viable storage class specifier in C, there is 5058 // no reason to treat it as an extension. Instead, diagnose as an error. 5059 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 5060 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 5061 Diag(DS.getStorageClassSpecLoc(), DiagID) 5062 << DeclSpec::getSpecifierName(SCS); 5063 } 5064 5065 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 5066 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 5067 << DeclSpec::getSpecifierName(TSCS); 5068 if (DS.getTypeQualifiers()) { 5069 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 5070 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 5071 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 5072 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 5073 // Restrict is covered above. 5074 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 5075 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 5076 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 5077 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 5078 } 5079 5080 // Warn about ignored type attributes, for example: 5081 // __attribute__((aligned)) struct A; 5082 // Attributes should be placed after tag to apply to type declaration. 5083 if (!DS.getAttributes().empty()) { 5084 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 5085 if (TypeSpecType == DeclSpec::TST_class || 5086 TypeSpecType == DeclSpec::TST_struct || 5087 TypeSpecType == DeclSpec::TST_interface || 5088 TypeSpecType == DeclSpec::TST_union || 5089 TypeSpecType == DeclSpec::TST_enum) { 5090 for (const ParsedAttr &AL : DS.getAttributes()) 5091 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored) 5092 << AL << GetDiagnosticTypeSpecifierID(TypeSpecType); 5093 } 5094 } 5095 5096 return TagD; 5097 } 5098 5099 /// We are trying to inject an anonymous member into the given scope; 5100 /// check if there's an existing declaration that can't be overloaded. 5101 /// 5102 /// \return true if this is a forbidden redeclaration 5103 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 5104 Scope *S, 5105 DeclContext *Owner, 5106 DeclarationName Name, 5107 SourceLocation NameLoc, 5108 bool IsUnion) { 5109 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 5110 Sema::ForVisibleRedeclaration); 5111 if (!SemaRef.LookupName(R, S)) return false; 5112 5113 // Pick a representative declaration. 5114 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 5115 assert(PrevDecl && "Expected a non-null Decl"); 5116 5117 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 5118 return false; 5119 5120 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 5121 << IsUnion << Name; 5122 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 5123 5124 return true; 5125 } 5126 5127 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 5128 /// anonymous struct or union AnonRecord into the owning context Owner 5129 /// and scope S. This routine will be invoked just after we realize 5130 /// that an unnamed union or struct is actually an anonymous union or 5131 /// struct, e.g., 5132 /// 5133 /// @code 5134 /// union { 5135 /// int i; 5136 /// float f; 5137 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 5138 /// // f into the surrounding scope.x 5139 /// @endcode 5140 /// 5141 /// This routine is recursive, injecting the names of nested anonymous 5142 /// structs/unions into the owning context and scope as well. 5143 static bool 5144 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 5145 RecordDecl *AnonRecord, AccessSpecifier AS, 5146 SmallVectorImpl<NamedDecl *> &Chaining) { 5147 bool Invalid = false; 5148 5149 // Look every FieldDecl and IndirectFieldDecl with a name. 5150 for (auto *D : AnonRecord->decls()) { 5151 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 5152 cast<NamedDecl>(D)->getDeclName()) { 5153 ValueDecl *VD = cast<ValueDecl>(D); 5154 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 5155 VD->getLocation(), 5156 AnonRecord->isUnion())) { 5157 // C++ [class.union]p2: 5158 // The names of the members of an anonymous union shall be 5159 // distinct from the names of any other entity in the 5160 // scope in which the anonymous union is declared. 5161 Invalid = true; 5162 } else { 5163 // C++ [class.union]p2: 5164 // For the purpose of name lookup, after the anonymous union 5165 // definition, the members of the anonymous union are 5166 // considered to have been defined in the scope in which the 5167 // anonymous union is declared. 5168 unsigned OldChainingSize = Chaining.size(); 5169 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 5170 Chaining.append(IF->chain_begin(), IF->chain_end()); 5171 else 5172 Chaining.push_back(VD); 5173 5174 assert(Chaining.size() >= 2); 5175 NamedDecl **NamedChain = 5176 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 5177 for (unsigned i = 0; i < Chaining.size(); i++) 5178 NamedChain[i] = Chaining[i]; 5179 5180 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 5181 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 5182 VD->getType(), {NamedChain, Chaining.size()}); 5183 5184 for (const auto *Attr : VD->attrs()) 5185 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 5186 5187 IndirectField->setAccess(AS); 5188 IndirectField->setImplicit(); 5189 SemaRef.PushOnScopeChains(IndirectField, S); 5190 5191 // That includes picking up the appropriate access specifier. 5192 if (AS != AS_none) IndirectField->setAccess(AS); 5193 5194 Chaining.resize(OldChainingSize); 5195 } 5196 } 5197 } 5198 5199 return Invalid; 5200 } 5201 5202 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 5203 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 5204 /// illegal input values are mapped to SC_None. 5205 static StorageClass 5206 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 5207 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 5208 assert(StorageClassSpec != DeclSpec::SCS_typedef && 5209 "Parser allowed 'typedef' as storage class VarDecl."); 5210 switch (StorageClassSpec) { 5211 case DeclSpec::SCS_unspecified: return SC_None; 5212 case DeclSpec::SCS_extern: 5213 if (DS.isExternInLinkageSpec()) 5214 return SC_None; 5215 return SC_Extern; 5216 case DeclSpec::SCS_static: return SC_Static; 5217 case DeclSpec::SCS_auto: return SC_Auto; 5218 case DeclSpec::SCS_register: return SC_Register; 5219 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 5220 // Illegal SCSs map to None: error reporting is up to the caller. 5221 case DeclSpec::SCS_mutable: // Fall through. 5222 case DeclSpec::SCS_typedef: return SC_None; 5223 } 5224 llvm_unreachable("unknown storage class specifier"); 5225 } 5226 5227 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 5228 assert(Record->hasInClassInitializer()); 5229 5230 for (const auto *I : Record->decls()) { 5231 const auto *FD = dyn_cast<FieldDecl>(I); 5232 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 5233 FD = IFD->getAnonField(); 5234 if (FD && FD->hasInClassInitializer()) 5235 return FD->getLocation(); 5236 } 5237 5238 llvm_unreachable("couldn't find in-class initializer"); 5239 } 5240 5241 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 5242 SourceLocation DefaultInitLoc) { 5243 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 5244 return; 5245 5246 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 5247 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 5248 } 5249 5250 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 5251 CXXRecordDecl *AnonUnion) { 5252 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 5253 return; 5254 5255 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 5256 } 5257 5258 /// BuildAnonymousStructOrUnion - Handle the declaration of an 5259 /// anonymous structure or union. Anonymous unions are a C++ feature 5260 /// (C++ [class.union]) and a C11 feature; anonymous structures 5261 /// are a C11 feature and GNU C++ extension. 5262 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 5263 AccessSpecifier AS, 5264 RecordDecl *Record, 5265 const PrintingPolicy &Policy) { 5266 DeclContext *Owner = Record->getDeclContext(); 5267 5268 // Diagnose whether this anonymous struct/union is an extension. 5269 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 5270 Diag(Record->getLocation(), diag::ext_anonymous_union); 5271 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 5272 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 5273 else if (!Record->isUnion() && !getLangOpts().C11) 5274 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 5275 5276 // C and C++ require different kinds of checks for anonymous 5277 // structs/unions. 5278 bool Invalid = false; 5279 if (getLangOpts().CPlusPlus) { 5280 const char *PrevSpec = nullptr; 5281 if (Record->isUnion()) { 5282 // C++ [class.union]p6: 5283 // C++17 [class.union.anon]p2: 5284 // Anonymous unions declared in a named namespace or in the 5285 // global namespace shall be declared static. 5286 unsigned DiagID; 5287 DeclContext *OwnerScope = Owner->getRedeclContext(); 5288 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 5289 (OwnerScope->isTranslationUnit() || 5290 (OwnerScope->isNamespace() && 5291 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) { 5292 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 5293 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 5294 5295 // Recover by adding 'static'. 5296 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 5297 PrevSpec, DiagID, Policy); 5298 } 5299 // C++ [class.union]p6: 5300 // A storage class is not allowed in a declaration of an 5301 // anonymous union in a class scope. 5302 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 5303 isa<RecordDecl>(Owner)) { 5304 Diag(DS.getStorageClassSpecLoc(), 5305 diag::err_anonymous_union_with_storage_spec) 5306 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 5307 5308 // Recover by removing the storage specifier. 5309 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 5310 SourceLocation(), 5311 PrevSpec, DiagID, Context.getPrintingPolicy()); 5312 } 5313 } 5314 5315 // Ignore const/volatile/restrict qualifiers. 5316 if (DS.getTypeQualifiers()) { 5317 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 5318 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 5319 << Record->isUnion() << "const" 5320 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 5321 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 5322 Diag(DS.getVolatileSpecLoc(), 5323 diag::ext_anonymous_struct_union_qualified) 5324 << Record->isUnion() << "volatile" 5325 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 5326 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 5327 Diag(DS.getRestrictSpecLoc(), 5328 diag::ext_anonymous_struct_union_qualified) 5329 << Record->isUnion() << "restrict" 5330 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 5331 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 5332 Diag(DS.getAtomicSpecLoc(), 5333 diag::ext_anonymous_struct_union_qualified) 5334 << Record->isUnion() << "_Atomic" 5335 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 5336 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 5337 Diag(DS.getUnalignedSpecLoc(), 5338 diag::ext_anonymous_struct_union_qualified) 5339 << Record->isUnion() << "__unaligned" 5340 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 5341 5342 DS.ClearTypeQualifiers(); 5343 } 5344 5345 // C++ [class.union]p2: 5346 // The member-specification of an anonymous union shall only 5347 // define non-static data members. [Note: nested types and 5348 // functions cannot be declared within an anonymous union. ] 5349 for (auto *Mem : Record->decls()) { 5350 // Ignore invalid declarations; we already diagnosed them. 5351 if (Mem->isInvalidDecl()) 5352 continue; 5353 5354 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 5355 // C++ [class.union]p3: 5356 // An anonymous union shall not have private or protected 5357 // members (clause 11). 5358 assert(FD->getAccess() != AS_none); 5359 if (FD->getAccess() != AS_public) { 5360 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 5361 << Record->isUnion() << (FD->getAccess() == AS_protected); 5362 Invalid = true; 5363 } 5364 5365 // C++ [class.union]p1 5366 // An object of a class with a non-trivial constructor, a non-trivial 5367 // copy constructor, a non-trivial destructor, or a non-trivial copy 5368 // assignment operator cannot be a member of a union, nor can an 5369 // array of such objects. 5370 if (CheckNontrivialField(FD)) 5371 Invalid = true; 5372 } else if (Mem->isImplicit()) { 5373 // Any implicit members are fine. 5374 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 5375 // This is a type that showed up in an 5376 // elaborated-type-specifier inside the anonymous struct or 5377 // union, but which actually declares a type outside of the 5378 // anonymous struct or union. It's okay. 5379 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 5380 if (!MemRecord->isAnonymousStructOrUnion() && 5381 MemRecord->getDeclName()) { 5382 // Visual C++ allows type definition in anonymous struct or union. 5383 if (getLangOpts().MicrosoftExt) 5384 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 5385 << Record->isUnion(); 5386 else { 5387 // This is a nested type declaration. 5388 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 5389 << Record->isUnion(); 5390 Invalid = true; 5391 } 5392 } else { 5393 // This is an anonymous type definition within another anonymous type. 5394 // This is a popular extension, provided by Plan9, MSVC and GCC, but 5395 // not part of standard C++. 5396 Diag(MemRecord->getLocation(), 5397 diag::ext_anonymous_record_with_anonymous_type) 5398 << Record->isUnion(); 5399 } 5400 } else if (isa<AccessSpecDecl>(Mem)) { 5401 // Any access specifier is fine. 5402 } else if (isa<StaticAssertDecl>(Mem)) { 5403 // In C++1z, static_assert declarations are also fine. 5404 } else { 5405 // We have something that isn't a non-static data 5406 // member. Complain about it. 5407 unsigned DK = diag::err_anonymous_record_bad_member; 5408 if (isa<TypeDecl>(Mem)) 5409 DK = diag::err_anonymous_record_with_type; 5410 else if (isa<FunctionDecl>(Mem)) 5411 DK = diag::err_anonymous_record_with_function; 5412 else if (isa<VarDecl>(Mem)) 5413 DK = diag::err_anonymous_record_with_static; 5414 5415 // Visual C++ allows type definition in anonymous struct or union. 5416 if (getLangOpts().MicrosoftExt && 5417 DK == diag::err_anonymous_record_with_type) 5418 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 5419 << Record->isUnion(); 5420 else { 5421 Diag(Mem->getLocation(), DK) << Record->isUnion(); 5422 Invalid = true; 5423 } 5424 } 5425 } 5426 5427 // C++11 [class.union]p8 (DR1460): 5428 // At most one variant member of a union may have a 5429 // brace-or-equal-initializer. 5430 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 5431 Owner->isRecord()) 5432 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 5433 cast<CXXRecordDecl>(Record)); 5434 } 5435 5436 if (!Record->isUnion() && !Owner->isRecord()) { 5437 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 5438 << getLangOpts().CPlusPlus; 5439 Invalid = true; 5440 } 5441 5442 // C++ [dcl.dcl]p3: 5443 // [If there are no declarators], and except for the declaration of an 5444 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 5445 // names into the program 5446 // C++ [class.mem]p2: 5447 // each such member-declaration shall either declare at least one member 5448 // name of the class or declare at least one unnamed bit-field 5449 // 5450 // For C this is an error even for a named struct, and is diagnosed elsewhere. 5451 if (getLangOpts().CPlusPlus && Record->field_empty()) 5452 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); 5453 5454 // Mock up a declarator. 5455 Declarator Dc(DS, DeclaratorContext::Member); 5456 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5457 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 5458 5459 // Create a declaration for this anonymous struct/union. 5460 NamedDecl *Anon = nullptr; 5461 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 5462 Anon = FieldDecl::Create( 5463 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(), 5464 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo, 5465 /*BitWidth=*/nullptr, /*Mutable=*/false, 5466 /*InitStyle=*/ICIS_NoInit); 5467 Anon->setAccess(AS); 5468 ProcessDeclAttributes(S, Anon, Dc); 5469 5470 if (getLangOpts().CPlusPlus) 5471 FieldCollector->Add(cast<FieldDecl>(Anon)); 5472 } else { 5473 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 5474 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 5475 if (SCSpec == DeclSpec::SCS_mutable) { 5476 // mutable can only appear on non-static class members, so it's always 5477 // an error here 5478 Diag(Record->getLocation(), diag::err_mutable_nonmember); 5479 Invalid = true; 5480 SC = SC_None; 5481 } 5482 5483 assert(DS.getAttributes().empty() && "No attribute expected"); 5484 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(), 5485 Record->getLocation(), /*IdentifierInfo=*/nullptr, 5486 Context.getTypeDeclType(Record), TInfo, SC); 5487 5488 // Default-initialize the implicit variable. This initialization will be 5489 // trivial in almost all cases, except if a union member has an in-class 5490 // initializer: 5491 // union { int n = 0; }; 5492 ActOnUninitializedDecl(Anon); 5493 } 5494 Anon->setImplicit(); 5495 5496 // Mark this as an anonymous struct/union type. 5497 Record->setAnonymousStructOrUnion(true); 5498 5499 // Add the anonymous struct/union object to the current 5500 // context. We'll be referencing this object when we refer to one of 5501 // its members. 5502 Owner->addDecl(Anon); 5503 5504 // Inject the members of the anonymous struct/union into the owning 5505 // context and into the identifier resolver chain for name lookup 5506 // purposes. 5507 SmallVector<NamedDecl*, 2> Chain; 5508 Chain.push_back(Anon); 5509 5510 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 5511 Invalid = true; 5512 5513 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 5514 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 5515 MangleNumberingContext *MCtx; 5516 Decl *ManglingContextDecl; 5517 std::tie(MCtx, ManglingContextDecl) = 5518 getCurrentMangleNumberContext(NewVD->getDeclContext()); 5519 if (MCtx) { 5520 Context.setManglingNumber( 5521 NewVD, MCtx->getManglingNumber( 5522 NewVD, getMSManglingNumber(getLangOpts(), S))); 5523 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 5524 } 5525 } 5526 } 5527 5528 if (Invalid) 5529 Anon->setInvalidDecl(); 5530 5531 return Anon; 5532 } 5533 5534 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 5535 /// Microsoft C anonymous structure. 5536 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 5537 /// Example: 5538 /// 5539 /// struct A { int a; }; 5540 /// struct B { struct A; int b; }; 5541 /// 5542 /// void foo() { 5543 /// B var; 5544 /// var.a = 3; 5545 /// } 5546 /// 5547 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 5548 RecordDecl *Record) { 5549 assert(Record && "expected a record!"); 5550 5551 // Mock up a declarator. 5552 Declarator Dc(DS, DeclaratorContext::TypeName); 5553 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5554 assert(TInfo && "couldn't build declarator info for anonymous struct"); 5555 5556 auto *ParentDecl = cast<RecordDecl>(CurContext); 5557 QualType RecTy = Context.getTypeDeclType(Record); 5558 5559 // Create a declaration for this anonymous struct. 5560 NamedDecl *Anon = 5561 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(), 5562 /*IdentifierInfo=*/nullptr, RecTy, TInfo, 5563 /*BitWidth=*/nullptr, /*Mutable=*/false, 5564 /*InitStyle=*/ICIS_NoInit); 5565 Anon->setImplicit(); 5566 5567 // Add the anonymous struct object to the current context. 5568 CurContext->addDecl(Anon); 5569 5570 // Inject the members of the anonymous struct into the current 5571 // context and into the identifier resolver chain for name lookup 5572 // purposes. 5573 SmallVector<NamedDecl*, 2> Chain; 5574 Chain.push_back(Anon); 5575 5576 RecordDecl *RecordDef = Record->getDefinition(); 5577 if (RequireCompleteSizedType(Anon->getLocation(), RecTy, 5578 diag::err_field_incomplete_or_sizeless) || 5579 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 5580 AS_none, Chain)) { 5581 Anon->setInvalidDecl(); 5582 ParentDecl->setInvalidDecl(); 5583 } 5584 5585 return Anon; 5586 } 5587 5588 /// GetNameForDeclarator - Determine the full declaration name for the 5589 /// given Declarator. 5590 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 5591 return GetNameFromUnqualifiedId(D.getName()); 5592 } 5593 5594 /// Retrieves the declaration name from a parsed unqualified-id. 5595 DeclarationNameInfo 5596 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 5597 DeclarationNameInfo NameInfo; 5598 NameInfo.setLoc(Name.StartLocation); 5599 5600 switch (Name.getKind()) { 5601 5602 case UnqualifiedIdKind::IK_ImplicitSelfParam: 5603 case UnqualifiedIdKind::IK_Identifier: 5604 NameInfo.setName(Name.Identifier); 5605 return NameInfo; 5606 5607 case UnqualifiedIdKind::IK_DeductionGuideName: { 5608 // C++ [temp.deduct.guide]p3: 5609 // The simple-template-id shall name a class template specialization. 5610 // The template-name shall be the same identifier as the template-name 5611 // of the simple-template-id. 5612 // These together intend to imply that the template-name shall name a 5613 // class template. 5614 // FIXME: template<typename T> struct X {}; 5615 // template<typename T> using Y = X<T>; 5616 // Y(int) -> Y<int>; 5617 // satisfies these rules but does not name a class template. 5618 TemplateName TN = Name.TemplateName.get().get(); 5619 auto *Template = TN.getAsTemplateDecl(); 5620 if (!Template || !isa<ClassTemplateDecl>(Template)) { 5621 Diag(Name.StartLocation, 5622 diag::err_deduction_guide_name_not_class_template) 5623 << (int)getTemplateNameKindForDiagnostics(TN) << TN; 5624 if (Template) 5625 Diag(Template->getLocation(), diag::note_template_decl_here); 5626 return DeclarationNameInfo(); 5627 } 5628 5629 NameInfo.setName( 5630 Context.DeclarationNames.getCXXDeductionGuideName(Template)); 5631 return NameInfo; 5632 } 5633 5634 case UnqualifiedIdKind::IK_OperatorFunctionId: 5635 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 5636 Name.OperatorFunctionId.Operator)); 5637 NameInfo.setCXXOperatorNameRange(SourceRange( 5638 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation)); 5639 return NameInfo; 5640 5641 case UnqualifiedIdKind::IK_LiteralOperatorId: 5642 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 5643 Name.Identifier)); 5644 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 5645 return NameInfo; 5646 5647 case UnqualifiedIdKind::IK_ConversionFunctionId: { 5648 TypeSourceInfo *TInfo; 5649 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 5650 if (Ty.isNull()) 5651 return DeclarationNameInfo(); 5652 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 5653 Context.getCanonicalType(Ty))); 5654 NameInfo.setNamedTypeInfo(TInfo); 5655 return NameInfo; 5656 } 5657 5658 case UnqualifiedIdKind::IK_ConstructorName: { 5659 TypeSourceInfo *TInfo; 5660 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 5661 if (Ty.isNull()) 5662 return DeclarationNameInfo(); 5663 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5664 Context.getCanonicalType(Ty))); 5665 NameInfo.setNamedTypeInfo(TInfo); 5666 return NameInfo; 5667 } 5668 5669 case UnqualifiedIdKind::IK_ConstructorTemplateId: { 5670 // In well-formed code, we can only have a constructor 5671 // template-id that refers to the current context, so go there 5672 // to find the actual type being constructed. 5673 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 5674 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 5675 return DeclarationNameInfo(); 5676 5677 // Determine the type of the class being constructed. 5678 QualType CurClassType = Context.getTypeDeclType(CurClass); 5679 5680 // FIXME: Check two things: that the template-id names the same type as 5681 // CurClassType, and that the template-id does not occur when the name 5682 // was qualified. 5683 5684 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5685 Context.getCanonicalType(CurClassType))); 5686 // FIXME: should we retrieve TypeSourceInfo? 5687 NameInfo.setNamedTypeInfo(nullptr); 5688 return NameInfo; 5689 } 5690 5691 case UnqualifiedIdKind::IK_DestructorName: { 5692 TypeSourceInfo *TInfo; 5693 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 5694 if (Ty.isNull()) 5695 return DeclarationNameInfo(); 5696 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 5697 Context.getCanonicalType(Ty))); 5698 NameInfo.setNamedTypeInfo(TInfo); 5699 return NameInfo; 5700 } 5701 5702 case UnqualifiedIdKind::IK_TemplateId: { 5703 TemplateName TName = Name.TemplateId->Template.get(); 5704 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 5705 return Context.getNameForTemplate(TName, TNameLoc); 5706 } 5707 5708 } // switch (Name.getKind()) 5709 5710 llvm_unreachable("Unknown name kind"); 5711 } 5712 5713 static QualType getCoreType(QualType Ty) { 5714 do { 5715 if (Ty->isPointerType() || Ty->isReferenceType()) 5716 Ty = Ty->getPointeeType(); 5717 else if (Ty->isArrayType()) 5718 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 5719 else 5720 return Ty.withoutLocalFastQualifiers(); 5721 } while (true); 5722 } 5723 5724 /// hasSimilarParameters - Determine whether the C++ functions Declaration 5725 /// and Definition have "nearly" matching parameters. This heuristic is 5726 /// used to improve diagnostics in the case where an out-of-line function 5727 /// definition doesn't match any declaration within the class or namespace. 5728 /// Also sets Params to the list of indices to the parameters that differ 5729 /// between the declaration and the definition. If hasSimilarParameters 5730 /// returns true and Params is empty, then all of the parameters match. 5731 static bool hasSimilarParameters(ASTContext &Context, 5732 FunctionDecl *Declaration, 5733 FunctionDecl *Definition, 5734 SmallVectorImpl<unsigned> &Params) { 5735 Params.clear(); 5736 if (Declaration->param_size() != Definition->param_size()) 5737 return false; 5738 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 5739 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 5740 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 5741 5742 // The parameter types are identical 5743 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy)) 5744 continue; 5745 5746 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 5747 QualType DefParamBaseTy = getCoreType(DefParamTy); 5748 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 5749 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 5750 5751 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 5752 (DeclTyName && DeclTyName == DefTyName)) 5753 Params.push_back(Idx); 5754 else // The two parameters aren't even close 5755 return false; 5756 } 5757 5758 return true; 5759 } 5760 5761 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 5762 /// declarator needs to be rebuilt in the current instantiation. 5763 /// Any bits of declarator which appear before the name are valid for 5764 /// consideration here. That's specifically the type in the decl spec 5765 /// and the base type in any member-pointer chunks. 5766 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 5767 DeclarationName Name) { 5768 // The types we specifically need to rebuild are: 5769 // - typenames, typeofs, and decltypes 5770 // - types which will become injected class names 5771 // Of course, we also need to rebuild any type referencing such a 5772 // type. It's safest to just say "dependent", but we call out a 5773 // few cases here. 5774 5775 DeclSpec &DS = D.getMutableDeclSpec(); 5776 switch (DS.getTypeSpecType()) { 5777 case DeclSpec::TST_typename: 5778 case DeclSpec::TST_typeofType: 5779 case DeclSpec::TST_underlyingType: 5780 case DeclSpec::TST_atomic: { 5781 // Grab the type from the parser. 5782 TypeSourceInfo *TSI = nullptr; 5783 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 5784 if (T.isNull() || !T->isInstantiationDependentType()) break; 5785 5786 // Make sure there's a type source info. This isn't really much 5787 // of a waste; most dependent types should have type source info 5788 // attached already. 5789 if (!TSI) 5790 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 5791 5792 // Rebuild the type in the current instantiation. 5793 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 5794 if (!TSI) return true; 5795 5796 // Store the new type back in the decl spec. 5797 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 5798 DS.UpdateTypeRep(LocType); 5799 break; 5800 } 5801 5802 case DeclSpec::TST_decltype: 5803 case DeclSpec::TST_typeofExpr: { 5804 Expr *E = DS.getRepAsExpr(); 5805 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 5806 if (Result.isInvalid()) return true; 5807 DS.UpdateExprRep(Result.get()); 5808 break; 5809 } 5810 5811 default: 5812 // Nothing to do for these decl specs. 5813 break; 5814 } 5815 5816 // It doesn't matter what order we do this in. 5817 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 5818 DeclaratorChunk &Chunk = D.getTypeObject(I); 5819 5820 // The only type information in the declarator which can come 5821 // before the declaration name is the base type of a member 5822 // pointer. 5823 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 5824 continue; 5825 5826 // Rebuild the scope specifier in-place. 5827 CXXScopeSpec &SS = Chunk.Mem.Scope(); 5828 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 5829 return true; 5830 } 5831 5832 return false; 5833 } 5834 5835 /// Returns true if the declaration is declared in a system header or from a 5836 /// system macro. 5837 static bool isFromSystemHeader(SourceManager &SM, const Decl *D) { 5838 return SM.isInSystemHeader(D->getLocation()) || 5839 SM.isInSystemMacro(D->getLocation()); 5840 } 5841 5842 void Sema::warnOnReservedIdentifier(const NamedDecl *D) { 5843 // Avoid warning twice on the same identifier, and don't warn on redeclaration 5844 // of system decl. 5845 if (D->getPreviousDecl() || D->isImplicit()) 5846 return; 5847 ReservedIdentifierStatus Status = D->isReserved(getLangOpts()); 5848 if (Status != ReservedIdentifierStatus::NotReserved && 5849 !isFromSystemHeader(Context.getSourceManager(), D)) { 5850 Diag(D->getLocation(), diag::warn_reserved_extern_symbol) 5851 << D << static_cast<int>(Status); 5852 } 5853 } 5854 5855 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 5856 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration); 5857 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 5858 5859 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 5860 Dcl && Dcl->getDeclContext()->isFileContext()) 5861 Dcl->setTopLevelDeclInObjCContainer(); 5862 5863 return Dcl; 5864 } 5865 5866 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 5867 /// If T is the name of a class, then each of the following shall have a 5868 /// name different from T: 5869 /// - every static data member of class T; 5870 /// - every member function of class T 5871 /// - every member of class T that is itself a type; 5872 /// \returns true if the declaration name violates these rules. 5873 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 5874 DeclarationNameInfo NameInfo) { 5875 DeclarationName Name = NameInfo.getName(); 5876 5877 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 5878 while (Record && Record->isAnonymousStructOrUnion()) 5879 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 5880 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 5881 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 5882 return true; 5883 } 5884 5885 return false; 5886 } 5887 5888 /// Diagnose a declaration whose declarator-id has the given 5889 /// nested-name-specifier. 5890 /// 5891 /// \param SS The nested-name-specifier of the declarator-id. 5892 /// 5893 /// \param DC The declaration context to which the nested-name-specifier 5894 /// resolves. 5895 /// 5896 /// \param Name The name of the entity being declared. 5897 /// 5898 /// \param Loc The location of the name of the entity being declared. 5899 /// 5900 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus 5901 /// we're declaring an explicit / partial specialization / instantiation. 5902 /// 5903 /// \returns true if we cannot safely recover from this error, false otherwise. 5904 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 5905 DeclarationName Name, 5906 SourceLocation Loc, bool IsTemplateId) { 5907 DeclContext *Cur = CurContext; 5908 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 5909 Cur = Cur->getParent(); 5910 5911 // If the user provided a superfluous scope specifier that refers back to the 5912 // class in which the entity is already declared, diagnose and ignore it. 5913 // 5914 // class X { 5915 // void X::f(); 5916 // }; 5917 // 5918 // Note, it was once ill-formed to give redundant qualification in all 5919 // contexts, but that rule was removed by DR482. 5920 if (Cur->Equals(DC)) { 5921 if (Cur->isRecord()) { 5922 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 5923 : diag::err_member_extra_qualification) 5924 << Name << FixItHint::CreateRemoval(SS.getRange()); 5925 SS.clear(); 5926 } else { 5927 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 5928 } 5929 return false; 5930 } 5931 5932 // Check whether the qualifying scope encloses the scope of the original 5933 // declaration. For a template-id, we perform the checks in 5934 // CheckTemplateSpecializationScope. 5935 if (!Cur->Encloses(DC) && !IsTemplateId) { 5936 if (Cur->isRecord()) 5937 Diag(Loc, diag::err_member_qualification) 5938 << Name << SS.getRange(); 5939 else if (isa<TranslationUnitDecl>(DC)) 5940 Diag(Loc, diag::err_invalid_declarator_global_scope) 5941 << Name << SS.getRange(); 5942 else if (isa<FunctionDecl>(Cur)) 5943 Diag(Loc, diag::err_invalid_declarator_in_function) 5944 << Name << SS.getRange(); 5945 else if (isa<BlockDecl>(Cur)) 5946 Diag(Loc, diag::err_invalid_declarator_in_block) 5947 << Name << SS.getRange(); 5948 else if (isa<ExportDecl>(Cur)) { 5949 if (!isa<NamespaceDecl>(DC)) 5950 Diag(Loc, diag::err_export_non_namespace_scope_name) 5951 << Name << SS.getRange(); 5952 else 5953 // The cases that DC is not NamespaceDecl should be handled in 5954 // CheckRedeclarationExported. 5955 return false; 5956 } else 5957 Diag(Loc, diag::err_invalid_declarator_scope) 5958 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 5959 5960 return true; 5961 } 5962 5963 if (Cur->isRecord()) { 5964 // Cannot qualify members within a class. 5965 Diag(Loc, diag::err_member_qualification) 5966 << Name << SS.getRange(); 5967 SS.clear(); 5968 5969 // C++ constructors and destructors with incorrect scopes can break 5970 // our AST invariants by having the wrong underlying types. If 5971 // that's the case, then drop this declaration entirely. 5972 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 5973 Name.getNameKind() == DeclarationName::CXXDestructorName) && 5974 !Context.hasSameType(Name.getCXXNameType(), 5975 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 5976 return true; 5977 5978 return false; 5979 } 5980 5981 // C++11 [dcl.meaning]p1: 5982 // [...] "The nested-name-specifier of the qualified declarator-id shall 5983 // not begin with a decltype-specifer" 5984 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 5985 while (SpecLoc.getPrefix()) 5986 SpecLoc = SpecLoc.getPrefix(); 5987 if (isa_and_nonnull<DecltypeType>( 5988 SpecLoc.getNestedNameSpecifier()->getAsType())) 5989 Diag(Loc, diag::err_decltype_in_declarator) 5990 << SpecLoc.getTypeLoc().getSourceRange(); 5991 5992 return false; 5993 } 5994 5995 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 5996 MultiTemplateParamsArg TemplateParamLists) { 5997 // TODO: consider using NameInfo for diagnostic. 5998 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5999 DeclarationName Name = NameInfo.getName(); 6000 6001 // All of these full declarators require an identifier. If it doesn't have 6002 // one, the ParsedFreeStandingDeclSpec action should be used. 6003 if (D.isDecompositionDeclarator()) { 6004 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 6005 } else if (!Name) { 6006 if (!D.isInvalidType()) // Reject this if we think it is valid. 6007 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident) 6008 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 6009 return nullptr; 6010 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 6011 return nullptr; 6012 6013 // The scope passed in may not be a decl scope. Zip up the scope tree until 6014 // we find one that is. 6015 while ((S->getFlags() & Scope::DeclScope) == 0 || 6016 (S->getFlags() & Scope::TemplateParamScope) != 0) 6017 S = S->getParent(); 6018 6019 DeclContext *DC = CurContext; 6020 if (D.getCXXScopeSpec().isInvalid()) 6021 D.setInvalidType(); 6022 else if (D.getCXXScopeSpec().isSet()) { 6023 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 6024 UPPC_DeclarationQualifier)) 6025 return nullptr; 6026 6027 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 6028 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 6029 if (!DC || isa<EnumDecl>(DC)) { 6030 // If we could not compute the declaration context, it's because the 6031 // declaration context is dependent but does not refer to a class, 6032 // class template, or class template partial specialization. Complain 6033 // and return early, to avoid the coming semantic disaster. 6034 Diag(D.getIdentifierLoc(), 6035 diag::err_template_qualified_declarator_no_match) 6036 << D.getCXXScopeSpec().getScopeRep() 6037 << D.getCXXScopeSpec().getRange(); 6038 return nullptr; 6039 } 6040 bool IsDependentContext = DC->isDependentContext(); 6041 6042 if (!IsDependentContext && 6043 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 6044 return nullptr; 6045 6046 // If a class is incomplete, do not parse entities inside it. 6047 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 6048 Diag(D.getIdentifierLoc(), 6049 diag::err_member_def_undefined_record) 6050 << Name << DC << D.getCXXScopeSpec().getRange(); 6051 return nullptr; 6052 } 6053 if (!D.getDeclSpec().isFriendSpecified()) { 6054 if (diagnoseQualifiedDeclaration( 6055 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(), 6056 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) { 6057 if (DC->isRecord()) 6058 return nullptr; 6059 6060 D.setInvalidType(); 6061 } 6062 } 6063 6064 // Check whether we need to rebuild the type of the given 6065 // declaration in the current instantiation. 6066 if (EnteringContext && IsDependentContext && 6067 TemplateParamLists.size() != 0) { 6068 ContextRAII SavedContext(*this, DC); 6069 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 6070 D.setInvalidType(); 6071 } 6072 } 6073 6074 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 6075 QualType R = TInfo->getType(); 6076 6077 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 6078 UPPC_DeclarationType)) 6079 D.setInvalidType(); 6080 6081 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 6082 forRedeclarationInCurContext()); 6083 6084 // See if this is a redefinition of a variable in the same scope. 6085 if (!D.getCXXScopeSpec().isSet()) { 6086 bool IsLinkageLookup = false; 6087 bool CreateBuiltins = false; 6088 6089 // If the declaration we're planning to build will be a function 6090 // or object with linkage, then look for another declaration with 6091 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 6092 // 6093 // If the declaration we're planning to build will be declared with 6094 // external linkage in the translation unit, create any builtin with 6095 // the same name. 6096 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 6097 /* Do nothing*/; 6098 else if (CurContext->isFunctionOrMethod() && 6099 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 6100 R->isFunctionType())) { 6101 IsLinkageLookup = true; 6102 CreateBuiltins = 6103 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 6104 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 6105 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 6106 CreateBuiltins = true; 6107 6108 if (IsLinkageLookup) { 6109 Previous.clear(LookupRedeclarationWithLinkage); 6110 Previous.setRedeclarationKind(ForExternalRedeclaration); 6111 } 6112 6113 LookupName(Previous, S, CreateBuiltins); 6114 } else { // Something like "int foo::x;" 6115 LookupQualifiedName(Previous, DC); 6116 6117 // C++ [dcl.meaning]p1: 6118 // When the declarator-id is qualified, the declaration shall refer to a 6119 // previously declared member of the class or namespace to which the 6120 // qualifier refers (or, in the case of a namespace, of an element of the 6121 // inline namespace set of that namespace (7.3.1)) or to a specialization 6122 // thereof; [...] 6123 // 6124 // Note that we already checked the context above, and that we do not have 6125 // enough information to make sure that Previous contains the declaration 6126 // we want to match. For example, given: 6127 // 6128 // class X { 6129 // void f(); 6130 // void f(float); 6131 // }; 6132 // 6133 // void X::f(int) { } // ill-formed 6134 // 6135 // In this case, Previous will point to the overload set 6136 // containing the two f's declared in X, but neither of them 6137 // matches. 6138 6139 // C++ [dcl.meaning]p1: 6140 // [...] the member shall not merely have been introduced by a 6141 // using-declaration in the scope of the class or namespace nominated by 6142 // the nested-name-specifier of the declarator-id. 6143 RemoveUsingDecls(Previous); 6144 } 6145 6146 if (Previous.isSingleResult() && 6147 Previous.getFoundDecl()->isTemplateParameter()) { 6148 // Maybe we will complain about the shadowed template parameter. 6149 if (!D.isInvalidType()) 6150 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 6151 Previous.getFoundDecl()); 6152 6153 // Just pretend that we didn't see the previous declaration. 6154 Previous.clear(); 6155 } 6156 6157 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 6158 // Forget that the previous declaration is the injected-class-name. 6159 Previous.clear(); 6160 6161 // In C++, the previous declaration we find might be a tag type 6162 // (class or enum). In this case, the new declaration will hide the 6163 // tag type. Note that this applies to functions, function templates, and 6164 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. 6165 if (Previous.isSingleTagDecl() && 6166 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 6167 (TemplateParamLists.size() == 0 || R->isFunctionType())) 6168 Previous.clear(); 6169 6170 // Check that there are no default arguments other than in the parameters 6171 // of a function declaration (C++ only). 6172 if (getLangOpts().CPlusPlus) 6173 CheckExtraCXXDefaultArguments(D); 6174 6175 NamedDecl *New; 6176 6177 bool AddToScope = true; 6178 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 6179 if (TemplateParamLists.size()) { 6180 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 6181 return nullptr; 6182 } 6183 6184 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 6185 } else if (R->isFunctionType()) { 6186 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 6187 TemplateParamLists, 6188 AddToScope); 6189 } else { 6190 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 6191 AddToScope); 6192 } 6193 6194 if (!New) 6195 return nullptr; 6196 6197 // If this has an identifier and is not a function template specialization, 6198 // add it to the scope stack. 6199 if (New->getDeclName() && AddToScope) 6200 PushOnScopeChains(New, S); 6201 6202 if (isInOpenMPDeclareTargetContext()) 6203 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 6204 6205 return New; 6206 } 6207 6208 /// Helper method to turn variable array types into constant array 6209 /// types in certain situations which would otherwise be errors (for 6210 /// GCC compatibility). 6211 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 6212 ASTContext &Context, 6213 bool &SizeIsNegative, 6214 llvm::APSInt &Oversized) { 6215 // This method tries to turn a variable array into a constant 6216 // array even when the size isn't an ICE. This is necessary 6217 // for compatibility with code that depends on gcc's buggy 6218 // constant expression folding, like struct {char x[(int)(char*)2];} 6219 SizeIsNegative = false; 6220 Oversized = 0; 6221 6222 if (T->isDependentType()) 6223 return QualType(); 6224 6225 QualifierCollector Qs; 6226 const Type *Ty = Qs.strip(T); 6227 6228 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 6229 QualType Pointee = PTy->getPointeeType(); 6230 QualType FixedType = 6231 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 6232 Oversized); 6233 if (FixedType.isNull()) return FixedType; 6234 FixedType = Context.getPointerType(FixedType); 6235 return Qs.apply(Context, FixedType); 6236 } 6237 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 6238 QualType Inner = PTy->getInnerType(); 6239 QualType FixedType = 6240 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 6241 Oversized); 6242 if (FixedType.isNull()) return FixedType; 6243 FixedType = Context.getParenType(FixedType); 6244 return Qs.apply(Context, FixedType); 6245 } 6246 6247 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 6248 if (!VLATy) 6249 return QualType(); 6250 6251 QualType ElemTy = VLATy->getElementType(); 6252 if (ElemTy->isVariablyModifiedType()) { 6253 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context, 6254 SizeIsNegative, Oversized); 6255 if (ElemTy.isNull()) 6256 return QualType(); 6257 } 6258 6259 Expr::EvalResult Result; 6260 if (!VLATy->getSizeExpr() || 6261 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context)) 6262 return QualType(); 6263 6264 llvm::APSInt Res = Result.Val.getInt(); 6265 6266 // Check whether the array size is negative. 6267 if (Res.isSigned() && Res.isNegative()) { 6268 SizeIsNegative = true; 6269 return QualType(); 6270 } 6271 6272 // Check whether the array is too large to be addressed. 6273 unsigned ActiveSizeBits = 6274 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() && 6275 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType()) 6276 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res) 6277 : Res.getActiveBits(); 6278 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 6279 Oversized = Res; 6280 return QualType(); 6281 } 6282 6283 QualType FoldedArrayType = Context.getConstantArrayType( 6284 ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0); 6285 return Qs.apply(Context, FoldedArrayType); 6286 } 6287 6288 static void 6289 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 6290 SrcTL = SrcTL.getUnqualifiedLoc(); 6291 DstTL = DstTL.getUnqualifiedLoc(); 6292 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 6293 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 6294 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 6295 DstPTL.getPointeeLoc()); 6296 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 6297 return; 6298 } 6299 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 6300 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 6301 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 6302 DstPTL.getInnerLoc()); 6303 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 6304 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 6305 return; 6306 } 6307 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 6308 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 6309 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 6310 TypeLoc DstElemTL = DstATL.getElementLoc(); 6311 if (VariableArrayTypeLoc SrcElemATL = 6312 SrcElemTL.getAs<VariableArrayTypeLoc>()) { 6313 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>(); 6314 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL); 6315 } else { 6316 DstElemTL.initializeFullCopy(SrcElemTL); 6317 } 6318 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 6319 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 6320 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 6321 } 6322 6323 /// Helper method to turn variable array types into constant array 6324 /// types in certain situations which would otherwise be errors (for 6325 /// GCC compatibility). 6326 static TypeSourceInfo* 6327 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 6328 ASTContext &Context, 6329 bool &SizeIsNegative, 6330 llvm::APSInt &Oversized) { 6331 QualType FixedTy 6332 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 6333 SizeIsNegative, Oversized); 6334 if (FixedTy.isNull()) 6335 return nullptr; 6336 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 6337 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 6338 FixedTInfo->getTypeLoc()); 6339 return FixedTInfo; 6340 } 6341 6342 /// Attempt to fold a variable-sized type to a constant-sized type, returning 6343 /// true if we were successful. 6344 bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, 6345 QualType &T, SourceLocation Loc, 6346 unsigned FailedFoldDiagID) { 6347 bool SizeIsNegative; 6348 llvm::APSInt Oversized; 6349 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 6350 TInfo, Context, SizeIsNegative, Oversized); 6351 if (FixedTInfo) { 6352 Diag(Loc, diag::ext_vla_folded_to_constant); 6353 TInfo = FixedTInfo; 6354 T = FixedTInfo->getType(); 6355 return true; 6356 } 6357 6358 if (SizeIsNegative) 6359 Diag(Loc, diag::err_typecheck_negative_array_size); 6360 else if (Oversized.getBoolValue()) 6361 Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10); 6362 else if (FailedFoldDiagID) 6363 Diag(Loc, FailedFoldDiagID); 6364 return false; 6365 } 6366 6367 /// Register the given locally-scoped extern "C" declaration so 6368 /// that it can be found later for redeclarations. We include any extern "C" 6369 /// declaration that is not visible in the translation unit here, not just 6370 /// function-scope declarations. 6371 void 6372 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 6373 if (!getLangOpts().CPlusPlus && 6374 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 6375 // Don't need to track declarations in the TU in C. 6376 return; 6377 6378 // Note that we have a locally-scoped external with this name. 6379 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 6380 } 6381 6382 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 6383 // FIXME: We can have multiple results via __attribute__((overloadable)). 6384 auto Result = Context.getExternCContextDecl()->lookup(Name); 6385 return Result.empty() ? nullptr : *Result.begin(); 6386 } 6387 6388 /// Diagnose function specifiers on a declaration of an identifier that 6389 /// does not identify a function. 6390 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 6391 // FIXME: We should probably indicate the identifier in question to avoid 6392 // confusion for constructs like "virtual int a(), b;" 6393 if (DS.isVirtualSpecified()) 6394 Diag(DS.getVirtualSpecLoc(), 6395 diag::err_virtual_non_function); 6396 6397 if (DS.hasExplicitSpecifier()) 6398 Diag(DS.getExplicitSpecLoc(), 6399 diag::err_explicit_non_function); 6400 6401 if (DS.isNoreturnSpecified()) 6402 Diag(DS.getNoreturnSpecLoc(), 6403 diag::err_noreturn_non_function); 6404 } 6405 6406 NamedDecl* 6407 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 6408 TypeSourceInfo *TInfo, LookupResult &Previous) { 6409 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 6410 if (D.getCXXScopeSpec().isSet()) { 6411 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 6412 << D.getCXXScopeSpec().getRange(); 6413 D.setInvalidType(); 6414 // Pretend we didn't see the scope specifier. 6415 DC = CurContext; 6416 Previous.clear(); 6417 } 6418 6419 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6420 6421 if (D.getDeclSpec().isInlineSpecified()) 6422 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6423 << getLangOpts().CPlusPlus17; 6424 if (D.getDeclSpec().hasConstexprSpecifier()) 6425 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 6426 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 6427 6428 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) { 6429 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName) 6430 Diag(D.getName().StartLocation, 6431 diag::err_deduction_guide_invalid_specifier) 6432 << "typedef"; 6433 else 6434 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 6435 << D.getName().getSourceRange(); 6436 return nullptr; 6437 } 6438 6439 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 6440 if (!NewTD) return nullptr; 6441 6442 // Handle attributes prior to checking for duplicates in MergeVarDecl 6443 ProcessDeclAttributes(S, NewTD, D); 6444 6445 CheckTypedefForVariablyModifiedType(S, NewTD); 6446 6447 bool Redeclaration = D.isRedeclaration(); 6448 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 6449 D.setRedeclaration(Redeclaration); 6450 return ND; 6451 } 6452 6453 void 6454 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 6455 // C99 6.7.7p2: If a typedef name specifies a variably modified type 6456 // then it shall have block scope. 6457 // Note that variably modified types must be fixed before merging the decl so 6458 // that redeclarations will match. 6459 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 6460 QualType T = TInfo->getType(); 6461 if (T->isVariablyModifiedType()) { 6462 setFunctionHasBranchProtectedScope(); 6463 6464 if (S->getFnParent() == nullptr) { 6465 bool SizeIsNegative; 6466 llvm::APSInt Oversized; 6467 TypeSourceInfo *FixedTInfo = 6468 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 6469 SizeIsNegative, 6470 Oversized); 6471 if (FixedTInfo) { 6472 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant); 6473 NewTD->setTypeSourceInfo(FixedTInfo); 6474 } else { 6475 if (SizeIsNegative) 6476 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 6477 else if (T->isVariableArrayType()) 6478 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 6479 else if (Oversized.getBoolValue()) 6480 Diag(NewTD->getLocation(), diag::err_array_too_large) 6481 << toString(Oversized, 10); 6482 else 6483 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 6484 NewTD->setInvalidDecl(); 6485 } 6486 } 6487 } 6488 } 6489 6490 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 6491 /// declares a typedef-name, either using the 'typedef' type specifier or via 6492 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 6493 NamedDecl* 6494 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 6495 LookupResult &Previous, bool &Redeclaration) { 6496 6497 // Find the shadowed declaration before filtering for scope. 6498 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); 6499 6500 // Merge the decl with the existing one if appropriate. If the decl is 6501 // in an outer scope, it isn't the same thing. 6502 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 6503 /*AllowInlineNamespace*/false); 6504 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 6505 if (!Previous.empty()) { 6506 Redeclaration = true; 6507 MergeTypedefNameDecl(S, NewTD, Previous); 6508 } else { 6509 inferGslPointerAttribute(NewTD); 6510 } 6511 6512 if (ShadowedDecl && !Redeclaration) 6513 CheckShadow(NewTD, ShadowedDecl, Previous); 6514 6515 // If this is the C FILE type, notify the AST context. 6516 if (IdentifierInfo *II = NewTD->getIdentifier()) 6517 if (!NewTD->isInvalidDecl() && 6518 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 6519 if (II->isStr("FILE")) 6520 Context.setFILEDecl(NewTD); 6521 else if (II->isStr("jmp_buf")) 6522 Context.setjmp_bufDecl(NewTD); 6523 else if (II->isStr("sigjmp_buf")) 6524 Context.setsigjmp_bufDecl(NewTD); 6525 else if (II->isStr("ucontext_t")) 6526 Context.setucontext_tDecl(NewTD); 6527 } 6528 6529 return NewTD; 6530 } 6531 6532 /// Determines whether the given declaration is an out-of-scope 6533 /// previous declaration. 6534 /// 6535 /// This routine should be invoked when name lookup has found a 6536 /// previous declaration (PrevDecl) that is not in the scope where a 6537 /// new declaration by the same name is being introduced. If the new 6538 /// declaration occurs in a local scope, previous declarations with 6539 /// linkage may still be considered previous declarations (C99 6540 /// 6.2.2p4-5, C++ [basic.link]p6). 6541 /// 6542 /// \param PrevDecl the previous declaration found by name 6543 /// lookup 6544 /// 6545 /// \param DC the context in which the new declaration is being 6546 /// declared. 6547 /// 6548 /// \returns true if PrevDecl is an out-of-scope previous declaration 6549 /// for a new delcaration with the same name. 6550 static bool 6551 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 6552 ASTContext &Context) { 6553 if (!PrevDecl) 6554 return false; 6555 6556 if (!PrevDecl->hasLinkage()) 6557 return false; 6558 6559 if (Context.getLangOpts().CPlusPlus) { 6560 // C++ [basic.link]p6: 6561 // If there is a visible declaration of an entity with linkage 6562 // having the same name and type, ignoring entities declared 6563 // outside the innermost enclosing namespace scope, the block 6564 // scope declaration declares that same entity and receives the 6565 // linkage of the previous declaration. 6566 DeclContext *OuterContext = DC->getRedeclContext(); 6567 if (!OuterContext->isFunctionOrMethod()) 6568 // This rule only applies to block-scope declarations. 6569 return false; 6570 6571 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 6572 if (PrevOuterContext->isRecord()) 6573 // We found a member function: ignore it. 6574 return false; 6575 6576 // Find the innermost enclosing namespace for the new and 6577 // previous declarations. 6578 OuterContext = OuterContext->getEnclosingNamespaceContext(); 6579 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 6580 6581 // The previous declaration is in a different namespace, so it 6582 // isn't the same function. 6583 if (!OuterContext->Equals(PrevOuterContext)) 6584 return false; 6585 } 6586 6587 return true; 6588 } 6589 6590 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) { 6591 CXXScopeSpec &SS = D.getCXXScopeSpec(); 6592 if (!SS.isSet()) return; 6593 DD->setQualifierInfo(SS.getWithLocInContext(S.Context)); 6594 } 6595 6596 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 6597 QualType type = decl->getType(); 6598 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 6599 if (lifetime == Qualifiers::OCL_Autoreleasing) { 6600 // Various kinds of declaration aren't allowed to be __autoreleasing. 6601 unsigned kind = -1U; 6602 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6603 if (var->hasAttr<BlocksAttr>()) 6604 kind = 0; // __block 6605 else if (!var->hasLocalStorage()) 6606 kind = 1; // global 6607 } else if (isa<ObjCIvarDecl>(decl)) { 6608 kind = 3; // ivar 6609 } else if (isa<FieldDecl>(decl)) { 6610 kind = 2; // field 6611 } 6612 6613 if (kind != -1U) { 6614 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 6615 << kind; 6616 } 6617 } else if (lifetime == Qualifiers::OCL_None) { 6618 // Try to infer lifetime. 6619 if (!type->isObjCLifetimeType()) 6620 return false; 6621 6622 lifetime = type->getObjCARCImplicitLifetime(); 6623 type = Context.getLifetimeQualifiedType(type, lifetime); 6624 decl->setType(type); 6625 } 6626 6627 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6628 // Thread-local variables cannot have lifetime. 6629 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 6630 var->getTLSKind()) { 6631 Diag(var->getLocation(), diag::err_arc_thread_ownership) 6632 << var->getType(); 6633 return true; 6634 } 6635 } 6636 6637 return false; 6638 } 6639 6640 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) { 6641 if (Decl->getType().hasAddressSpace()) 6642 return; 6643 if (Decl->getType()->isDependentType()) 6644 return; 6645 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) { 6646 QualType Type = Var->getType(); 6647 if (Type->isSamplerT() || Type->isVoidType()) 6648 return; 6649 LangAS ImplAS = LangAS::opencl_private; 6650 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the 6651 // __opencl_c_program_scope_global_variables feature, the address space 6652 // for a variable at program scope or a static or extern variable inside 6653 // a function are inferred to be __global. 6654 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) && 6655 Var->hasGlobalStorage()) 6656 ImplAS = LangAS::opencl_global; 6657 // If the original type from a decayed type is an array type and that array 6658 // type has no address space yet, deduce it now. 6659 if (auto DT = dyn_cast<DecayedType>(Type)) { 6660 auto OrigTy = DT->getOriginalType(); 6661 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) { 6662 // Add the address space to the original array type and then propagate 6663 // that to the element type through `getAsArrayType`. 6664 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS); 6665 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0); 6666 // Re-generate the decayed type. 6667 Type = Context.getDecayedType(OrigTy); 6668 } 6669 } 6670 Type = Context.getAddrSpaceQualType(Type, ImplAS); 6671 // Apply any qualifiers (including address space) from the array type to 6672 // the element type. This implements C99 6.7.3p8: "If the specification of 6673 // an array type includes any type qualifiers, the element type is so 6674 // qualified, not the array type." 6675 if (Type->isArrayType()) 6676 Type = QualType(Context.getAsArrayType(Type), 0); 6677 Decl->setType(Type); 6678 } 6679 } 6680 6681 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 6682 // Ensure that an auto decl is deduced otherwise the checks below might cache 6683 // the wrong linkage. 6684 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 6685 6686 // 'weak' only applies to declarations with external linkage. 6687 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 6688 if (!ND.isExternallyVisible()) { 6689 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 6690 ND.dropAttr<WeakAttr>(); 6691 } 6692 } 6693 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 6694 if (ND.isExternallyVisible()) { 6695 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 6696 ND.dropAttr<WeakRefAttr>(); 6697 ND.dropAttr<AliasAttr>(); 6698 } 6699 } 6700 6701 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 6702 if (VD->hasInit()) { 6703 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 6704 assert(VD->isThisDeclarationADefinition() && 6705 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 6706 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 6707 VD->dropAttr<AliasAttr>(); 6708 } 6709 } 6710 } 6711 6712 // 'selectany' only applies to externally visible variable declarations. 6713 // It does not apply to functions. 6714 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 6715 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 6716 S.Diag(Attr->getLocation(), 6717 diag::err_attribute_selectany_non_extern_data); 6718 ND.dropAttr<SelectAnyAttr>(); 6719 } 6720 } 6721 6722 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 6723 auto *VD = dyn_cast<VarDecl>(&ND); 6724 bool IsAnonymousNS = false; 6725 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6726 if (VD) { 6727 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext()); 6728 while (NS && !IsAnonymousNS) { 6729 IsAnonymousNS = NS->isAnonymousNamespace(); 6730 NS = dyn_cast<NamespaceDecl>(NS->getParent()); 6731 } 6732 } 6733 // dll attributes require external linkage. Static locals may have external 6734 // linkage but still cannot be explicitly imported or exported. 6735 // In Microsoft mode, a variable defined in anonymous namespace must have 6736 // external linkage in order to be exported. 6737 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft; 6738 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) || 6739 (!AnonNSInMicrosoftMode && 6740 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) { 6741 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 6742 << &ND << Attr; 6743 ND.setInvalidDecl(); 6744 } 6745 } 6746 6747 // Check the attributes on the function type, if any. 6748 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) { 6749 // Don't declare this variable in the second operand of the for-statement; 6750 // GCC miscompiles that by ending its lifetime before evaluating the 6751 // third operand. See gcc.gnu.org/PR86769. 6752 AttributedTypeLoc ATL; 6753 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc(); 6754 (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); 6755 TL = ATL.getModifiedLoc()) { 6756 // The [[lifetimebound]] attribute can be applied to the implicit object 6757 // parameter of a non-static member function (other than a ctor or dtor) 6758 // by applying it to the function type. 6759 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) { 6760 const auto *MD = dyn_cast<CXXMethodDecl>(FD); 6761 if (!MD || MD->isStatic()) { 6762 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param) 6763 << !MD << A->getRange(); 6764 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) { 6765 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor) 6766 << isa<CXXDestructorDecl>(MD) << A->getRange(); 6767 } 6768 } 6769 } 6770 } 6771 } 6772 6773 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 6774 NamedDecl *NewDecl, 6775 bool IsSpecialization, 6776 bool IsDefinition) { 6777 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl()) 6778 return; 6779 6780 bool IsTemplate = false; 6781 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 6782 OldDecl = OldTD->getTemplatedDecl(); 6783 IsTemplate = true; 6784 if (!IsSpecialization) 6785 IsDefinition = false; 6786 } 6787 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { 6788 NewDecl = NewTD->getTemplatedDecl(); 6789 IsTemplate = true; 6790 } 6791 6792 if (!OldDecl || !NewDecl) 6793 return; 6794 6795 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 6796 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 6797 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 6798 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 6799 6800 // dllimport and dllexport are inheritable attributes so we have to exclude 6801 // inherited attribute instances. 6802 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 6803 (NewExportAttr && !NewExportAttr->isInherited()); 6804 6805 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 6806 // the only exception being explicit specializations. 6807 // Implicitly generated declarations are also excluded for now because there 6808 // is no other way to switch these to use dllimport or dllexport. 6809 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 6810 6811 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 6812 // Allow with a warning for free functions and global variables. 6813 bool JustWarn = false; 6814 if (!OldDecl->isCXXClassMember()) { 6815 auto *VD = dyn_cast<VarDecl>(OldDecl); 6816 if (VD && !VD->getDescribedVarTemplate()) 6817 JustWarn = true; 6818 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 6819 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 6820 JustWarn = true; 6821 } 6822 6823 // We cannot change a declaration that's been used because IR has already 6824 // been emitted. Dllimported functions will still work though (modulo 6825 // address equality) as they can use the thunk. 6826 if (OldDecl->isUsed()) 6827 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 6828 JustWarn = false; 6829 6830 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 6831 : diag::err_attribute_dll_redeclaration; 6832 S.Diag(NewDecl->getLocation(), DiagID) 6833 << NewDecl 6834 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 6835 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6836 if (!JustWarn) { 6837 NewDecl->setInvalidDecl(); 6838 return; 6839 } 6840 } 6841 6842 // A redeclaration is not allowed to drop a dllimport attribute, the only 6843 // exceptions being inline function definitions (except for function 6844 // templates), local extern declarations, qualified friend declarations or 6845 // special MSVC extension: in the last case, the declaration is treated as if 6846 // it were marked dllexport. 6847 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 6848 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols(); 6849 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 6850 // Ignore static data because out-of-line definitions are diagnosed 6851 // separately. 6852 IsStaticDataMember = VD->isStaticDataMember(); 6853 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 6854 VarDecl::DeclarationOnly; 6855 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 6856 IsInline = FD->isInlined(); 6857 IsQualifiedFriend = FD->getQualifier() && 6858 FD->getFriendObjectKind() == Decl::FOK_Declared; 6859 } 6860 6861 if (OldImportAttr && !HasNewAttr && 6862 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember && 6863 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 6864 if (IsMicrosoftABI && IsDefinition) { 6865 S.Diag(NewDecl->getLocation(), 6866 diag::warn_redeclaration_without_import_attribute) 6867 << NewDecl; 6868 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6869 NewDecl->dropAttr<DLLImportAttr>(); 6870 NewDecl->addAttr( 6871 DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange())); 6872 } else { 6873 S.Diag(NewDecl->getLocation(), 6874 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 6875 << NewDecl << OldImportAttr; 6876 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6877 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 6878 OldDecl->dropAttr<DLLImportAttr>(); 6879 NewDecl->dropAttr<DLLImportAttr>(); 6880 } 6881 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) { 6882 // In MinGW, seeing a function declared inline drops the dllimport 6883 // attribute. 6884 OldDecl->dropAttr<DLLImportAttr>(); 6885 NewDecl->dropAttr<DLLImportAttr>(); 6886 S.Diag(NewDecl->getLocation(), 6887 diag::warn_dllimport_dropped_from_inline_function) 6888 << NewDecl << OldImportAttr; 6889 } 6890 6891 // A specialization of a class template member function is processed here 6892 // since it's a redeclaration. If the parent class is dllexport, the 6893 // specialization inherits that attribute. This doesn't happen automatically 6894 // since the parent class isn't instantiated until later. 6895 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) { 6896 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && 6897 !NewImportAttr && !NewExportAttr) { 6898 if (const DLLExportAttr *ParentExportAttr = 6899 MD->getParent()->getAttr<DLLExportAttr>()) { 6900 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context); 6901 NewAttr->setInherited(true); 6902 NewDecl->addAttr(NewAttr); 6903 } 6904 } 6905 } 6906 } 6907 6908 /// Given that we are within the definition of the given function, 6909 /// will that definition behave like C99's 'inline', where the 6910 /// definition is discarded except for optimization purposes? 6911 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 6912 // Try to avoid calling GetGVALinkageForFunction. 6913 6914 // All cases of this require the 'inline' keyword. 6915 if (!FD->isInlined()) return false; 6916 6917 // This is only possible in C++ with the gnu_inline attribute. 6918 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 6919 return false; 6920 6921 // Okay, go ahead and call the relatively-more-expensive function. 6922 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 6923 } 6924 6925 /// Determine whether a variable is extern "C" prior to attaching 6926 /// an initializer. We can't just call isExternC() here, because that 6927 /// will also compute and cache whether the declaration is externally 6928 /// visible, which might change when we attach the initializer. 6929 /// 6930 /// This can only be used if the declaration is known to not be a 6931 /// redeclaration of an internal linkage declaration. 6932 /// 6933 /// For instance: 6934 /// 6935 /// auto x = []{}; 6936 /// 6937 /// Attaching the initializer here makes this declaration not externally 6938 /// visible, because its type has internal linkage. 6939 /// 6940 /// FIXME: This is a hack. 6941 template<typename T> 6942 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 6943 if (S.getLangOpts().CPlusPlus) { 6944 // In C++, the overloadable attribute negates the effects of extern "C". 6945 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 6946 return false; 6947 6948 // So do CUDA's host/device attributes. 6949 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 6950 D->template hasAttr<CUDAHostAttr>())) 6951 return false; 6952 } 6953 return D->isExternC(); 6954 } 6955 6956 static bool shouldConsiderLinkage(const VarDecl *VD) { 6957 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 6958 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) || 6959 isa<OMPDeclareMapperDecl>(DC)) 6960 return VD->hasExternalStorage(); 6961 if (DC->isFileContext()) 6962 return true; 6963 if (DC->isRecord()) 6964 return false; 6965 if (isa<RequiresExprBodyDecl>(DC)) 6966 return false; 6967 llvm_unreachable("Unexpected context"); 6968 } 6969 6970 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 6971 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 6972 if (DC->isFileContext() || DC->isFunctionOrMethod() || 6973 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC)) 6974 return true; 6975 if (DC->isRecord()) 6976 return false; 6977 llvm_unreachable("Unexpected context"); 6978 } 6979 6980 static bool hasParsedAttr(Scope *S, const Declarator &PD, 6981 ParsedAttr::Kind Kind) { 6982 // Check decl attributes on the DeclSpec. 6983 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind)) 6984 return true; 6985 6986 // Walk the declarator structure, checking decl attributes that were in a type 6987 // position to the decl itself. 6988 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 6989 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind)) 6990 return true; 6991 } 6992 6993 // Finally, check attributes on the decl itself. 6994 return PD.getAttributes().hasAttribute(Kind); 6995 } 6996 6997 /// Adjust the \c DeclContext for a function or variable that might be a 6998 /// function-local external declaration. 6999 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 7000 if (!DC->isFunctionOrMethod()) 7001 return false; 7002 7003 // If this is a local extern function or variable declared within a function 7004 // template, don't add it into the enclosing namespace scope until it is 7005 // instantiated; it might have a dependent type right now. 7006 if (DC->isDependentContext()) 7007 return true; 7008 7009 // C++11 [basic.link]p7: 7010 // When a block scope declaration of an entity with linkage is not found to 7011 // refer to some other declaration, then that entity is a member of the 7012 // innermost enclosing namespace. 7013 // 7014 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 7015 // semantically-enclosing namespace, not a lexically-enclosing one. 7016 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 7017 DC = DC->getParent(); 7018 return true; 7019 } 7020 7021 /// Returns true if given declaration has external C language linkage. 7022 static bool isDeclExternC(const Decl *D) { 7023 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 7024 return FD->isExternC(); 7025 if (const auto *VD = dyn_cast<VarDecl>(D)) 7026 return VD->isExternC(); 7027 7028 llvm_unreachable("Unknown type of decl!"); 7029 } 7030 7031 /// Returns true if there hasn't been any invalid type diagnosed. 7032 static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) { 7033 DeclContext *DC = NewVD->getDeclContext(); 7034 QualType R = NewVD->getType(); 7035 7036 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 7037 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 7038 // argument. 7039 if (R->isImageType() || R->isPipeType()) { 7040 Se.Diag(NewVD->getLocation(), 7041 diag::err_opencl_type_can_only_be_used_as_function_parameter) 7042 << R; 7043 NewVD->setInvalidDecl(); 7044 return false; 7045 } 7046 7047 // OpenCL v1.2 s6.9.r: 7048 // The event type cannot be used to declare a program scope variable. 7049 // OpenCL v2.0 s6.9.q: 7050 // The clk_event_t and reserve_id_t types cannot be declared in program 7051 // scope. 7052 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) { 7053 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 7054 Se.Diag(NewVD->getLocation(), 7055 diag::err_invalid_type_for_program_scope_var) 7056 << R; 7057 NewVD->setInvalidDecl(); 7058 return false; 7059 } 7060 } 7061 7062 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 7063 if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers", 7064 Se.getLangOpts())) { 7065 QualType NR = R.getCanonicalType(); 7066 while (NR->isPointerType() || NR->isMemberFunctionPointerType() || 7067 NR->isReferenceType()) { 7068 if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() || 7069 NR->isFunctionReferenceType()) { 7070 Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer) 7071 << NR->isReferenceType(); 7072 NewVD->setInvalidDecl(); 7073 return false; 7074 } 7075 NR = NR->getPointeeType(); 7076 } 7077 } 7078 7079 if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16", 7080 Se.getLangOpts())) { 7081 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 7082 // half array type (unless the cl_khr_fp16 extension is enabled). 7083 if (Se.Context.getBaseElementType(R)->isHalfType()) { 7084 Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R; 7085 NewVD->setInvalidDecl(); 7086 return false; 7087 } 7088 } 7089 7090 // OpenCL v1.2 s6.9.r: 7091 // The event type cannot be used with the __local, __constant and __global 7092 // address space qualifiers. 7093 if (R->isEventT()) { 7094 if (R.getAddressSpace() != LangAS::opencl_private) { 7095 Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual); 7096 NewVD->setInvalidDecl(); 7097 return false; 7098 } 7099 } 7100 7101 if (R->isSamplerT()) { 7102 // OpenCL v1.2 s6.9.b p4: 7103 // The sampler type cannot be used with the __local and __global address 7104 // space qualifiers. 7105 if (R.getAddressSpace() == LangAS::opencl_local || 7106 R.getAddressSpace() == LangAS::opencl_global) { 7107 Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace); 7108 NewVD->setInvalidDecl(); 7109 } 7110 7111 // OpenCL v1.2 s6.12.14.1: 7112 // A global sampler must be declared with either the constant address 7113 // space qualifier or with the const qualifier. 7114 if (DC->isTranslationUnit() && 7115 !(R.getAddressSpace() == LangAS::opencl_constant || 7116 R.isConstQualified())) { 7117 Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler); 7118 NewVD->setInvalidDecl(); 7119 } 7120 if (NewVD->isInvalidDecl()) 7121 return false; 7122 } 7123 7124 return true; 7125 } 7126 7127 template <typename AttrTy> 7128 static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) { 7129 const TypedefNameDecl *TND = TT->getDecl(); 7130 if (const auto *Attribute = TND->getAttr<AttrTy>()) { 7131 AttrTy *Clone = Attribute->clone(S.Context); 7132 Clone->setInherited(true); 7133 D->addAttr(Clone); 7134 } 7135 } 7136 7137 NamedDecl *Sema::ActOnVariableDeclarator( 7138 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 7139 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 7140 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 7141 QualType R = TInfo->getType(); 7142 DeclarationName Name = GetNameForDeclarator(D).getName(); 7143 7144 IdentifierInfo *II = Name.getAsIdentifierInfo(); 7145 7146 if (D.isDecompositionDeclarator()) { 7147 // Take the name of the first declarator as our name for diagnostic 7148 // purposes. 7149 auto &Decomp = D.getDecompositionDeclarator(); 7150 if (!Decomp.bindings().empty()) { 7151 II = Decomp.bindings()[0].Name; 7152 Name = II; 7153 } 7154 } else if (!II) { 7155 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; 7156 return nullptr; 7157 } 7158 7159 7160 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 7161 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 7162 7163 // dllimport globals without explicit storage class are treated as extern. We 7164 // have to change the storage class this early to get the right DeclContext. 7165 if (SC == SC_None && !DC->isRecord() && 7166 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) && 7167 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport)) 7168 SC = SC_Extern; 7169 7170 DeclContext *OriginalDC = DC; 7171 bool IsLocalExternDecl = SC == SC_Extern && 7172 adjustContextForLocalExternDecl(DC); 7173 7174 if (SCSpec == DeclSpec::SCS_mutable) { 7175 // mutable can only appear on non-static class members, so it's always 7176 // an error here 7177 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 7178 D.setInvalidType(); 7179 SC = SC_None; 7180 } 7181 7182 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 7183 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 7184 D.getDeclSpec().getStorageClassSpecLoc())) { 7185 // In C++11, the 'register' storage class specifier is deprecated. 7186 // Suppress the warning in system macros, it's used in macros in some 7187 // popular C system headers, such as in glibc's htonl() macro. 7188 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7189 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 7190 : diag::warn_deprecated_register) 7191 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7192 } 7193 7194 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 7195 7196 if (!DC->isRecord() && S->getFnParent() == nullptr) { 7197 // C99 6.9p2: The storage-class specifiers auto and register shall not 7198 // appear in the declaration specifiers in an external declaration. 7199 // Global Register+Asm is a GNU extension we support. 7200 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 7201 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 7202 D.setInvalidType(); 7203 } 7204 } 7205 7206 // If this variable has a VLA type and an initializer, try to 7207 // fold to a constant-sized type. This is otherwise invalid. 7208 if (D.hasInitializer() && R->isVariableArrayType()) 7209 tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(), 7210 /*DiagID=*/0); 7211 7212 bool IsMemberSpecialization = false; 7213 bool IsVariableTemplateSpecialization = false; 7214 bool IsPartialSpecialization = false; 7215 bool IsVariableTemplate = false; 7216 VarDecl *NewVD = nullptr; 7217 VarTemplateDecl *NewTemplate = nullptr; 7218 TemplateParameterList *TemplateParams = nullptr; 7219 if (!getLangOpts().CPlusPlus) { 7220 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), 7221 II, R, TInfo, SC); 7222 7223 if (R->getContainedDeducedType()) 7224 ParsingInitForAutoVars.insert(NewVD); 7225 7226 if (D.isInvalidType()) 7227 NewVD->setInvalidDecl(); 7228 7229 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() && 7230 NewVD->hasLocalStorage()) 7231 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(), 7232 NTCUC_AutoVar, NTCUK_Destruct); 7233 } else { 7234 bool Invalid = false; 7235 7236 if (DC->isRecord() && !CurContext->isRecord()) { 7237 // This is an out-of-line definition of a static data member. 7238 switch (SC) { 7239 case SC_None: 7240 break; 7241 case SC_Static: 7242 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7243 diag::err_static_out_of_line) 7244 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7245 break; 7246 case SC_Auto: 7247 case SC_Register: 7248 case SC_Extern: 7249 // [dcl.stc] p2: The auto or register specifiers shall be applied only 7250 // to names of variables declared in a block or to function parameters. 7251 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 7252 // of class members 7253 7254 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7255 diag::err_storage_class_for_static_member) 7256 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7257 break; 7258 case SC_PrivateExtern: 7259 llvm_unreachable("C storage class in c++!"); 7260 } 7261 } 7262 7263 if (SC == SC_Static && CurContext->isRecord()) { 7264 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 7265 // Walk up the enclosing DeclContexts to check for any that are 7266 // incompatible with static data members. 7267 const DeclContext *FunctionOrMethod = nullptr; 7268 const CXXRecordDecl *AnonStruct = nullptr; 7269 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) { 7270 if (Ctxt->isFunctionOrMethod()) { 7271 FunctionOrMethod = Ctxt; 7272 break; 7273 } 7274 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt); 7275 if (ParentDecl && !ParentDecl->getDeclName()) { 7276 AnonStruct = ParentDecl; 7277 break; 7278 } 7279 } 7280 if (FunctionOrMethod) { 7281 // C++ [class.static.data]p5: A local class shall not have static data 7282 // members. 7283 Diag(D.getIdentifierLoc(), 7284 diag::err_static_data_member_not_allowed_in_local_class) 7285 << Name << RD->getDeclName() << RD->getTagKind(); 7286 } else if (AnonStruct) { 7287 // C++ [class.static.data]p4: Unnamed classes and classes contained 7288 // directly or indirectly within unnamed classes shall not contain 7289 // static data members. 7290 Diag(D.getIdentifierLoc(), 7291 diag::err_static_data_member_not_allowed_in_anon_struct) 7292 << Name << AnonStruct->getTagKind(); 7293 Invalid = true; 7294 } else if (RD->isUnion()) { 7295 // C++98 [class.union]p1: If a union contains a static data member, 7296 // the program is ill-formed. C++11 drops this restriction. 7297 Diag(D.getIdentifierLoc(), 7298 getLangOpts().CPlusPlus11 7299 ? diag::warn_cxx98_compat_static_data_member_in_union 7300 : diag::ext_static_data_member_in_union) << Name; 7301 } 7302 } 7303 } 7304 7305 // Match up the template parameter lists with the scope specifier, then 7306 // determine whether we have a template or a template specialization. 7307 bool InvalidScope = false; 7308 TemplateParams = MatchTemplateParametersToScopeSpecifier( 7309 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 7310 D.getCXXScopeSpec(), 7311 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 7312 ? D.getName().TemplateId 7313 : nullptr, 7314 TemplateParamLists, 7315 /*never a friend*/ false, IsMemberSpecialization, InvalidScope); 7316 Invalid |= InvalidScope; 7317 7318 if (TemplateParams) { 7319 if (!TemplateParams->size() && 7320 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 7321 // There is an extraneous 'template<>' for this variable. Complain 7322 // about it, but allow the declaration of the variable. 7323 Diag(TemplateParams->getTemplateLoc(), 7324 diag::err_template_variable_noparams) 7325 << II 7326 << SourceRange(TemplateParams->getTemplateLoc(), 7327 TemplateParams->getRAngleLoc()); 7328 TemplateParams = nullptr; 7329 } else { 7330 // Check that we can declare a template here. 7331 if (CheckTemplateDeclScope(S, TemplateParams)) 7332 return nullptr; 7333 7334 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 7335 // This is an explicit specialization or a partial specialization. 7336 IsVariableTemplateSpecialization = true; 7337 IsPartialSpecialization = TemplateParams->size() > 0; 7338 } else { // if (TemplateParams->size() > 0) 7339 // This is a template declaration. 7340 IsVariableTemplate = true; 7341 7342 // Only C++1y supports variable templates (N3651). 7343 Diag(D.getIdentifierLoc(), 7344 getLangOpts().CPlusPlus14 7345 ? diag::warn_cxx11_compat_variable_template 7346 : diag::ext_variable_template); 7347 } 7348 } 7349 } else { 7350 // Check that we can declare a member specialization here. 7351 if (!TemplateParamLists.empty() && IsMemberSpecialization && 7352 CheckTemplateDeclScope(S, TemplateParamLists.back())) 7353 return nullptr; 7354 assert((Invalid || 7355 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && 7356 "should have a 'template<>' for this decl"); 7357 } 7358 7359 if (IsVariableTemplateSpecialization) { 7360 SourceLocation TemplateKWLoc = 7361 TemplateParamLists.size() > 0 7362 ? TemplateParamLists[0]->getTemplateLoc() 7363 : SourceLocation(); 7364 DeclResult Res = ActOnVarTemplateSpecialization( 7365 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 7366 IsPartialSpecialization); 7367 if (Res.isInvalid()) 7368 return nullptr; 7369 NewVD = cast<VarDecl>(Res.get()); 7370 AddToScope = false; 7371 } else if (D.isDecompositionDeclarator()) { 7372 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(), 7373 D.getIdentifierLoc(), R, TInfo, SC, 7374 Bindings); 7375 } else 7376 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), 7377 D.getIdentifierLoc(), II, R, TInfo, SC); 7378 7379 // If this is supposed to be a variable template, create it as such. 7380 if (IsVariableTemplate) { 7381 NewTemplate = 7382 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 7383 TemplateParams, NewVD); 7384 NewVD->setDescribedVarTemplate(NewTemplate); 7385 } 7386 7387 // If this decl has an auto type in need of deduction, make a note of the 7388 // Decl so we can diagnose uses of it in its own initializer. 7389 if (R->getContainedDeducedType()) 7390 ParsingInitForAutoVars.insert(NewVD); 7391 7392 if (D.isInvalidType() || Invalid) { 7393 NewVD->setInvalidDecl(); 7394 if (NewTemplate) 7395 NewTemplate->setInvalidDecl(); 7396 } 7397 7398 SetNestedNameSpecifier(*this, NewVD, D); 7399 7400 // If we have any template parameter lists that don't directly belong to 7401 // the variable (matching the scope specifier), store them. 7402 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 7403 if (TemplateParamLists.size() > VDTemplateParamLists) 7404 NewVD->setTemplateParameterListsInfo( 7405 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 7406 } 7407 7408 if (D.getDeclSpec().isInlineSpecified()) { 7409 if (!getLangOpts().CPlusPlus) { 7410 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 7411 << 0; 7412 } else if (CurContext->isFunctionOrMethod()) { 7413 // 'inline' is not allowed on block scope variable declaration. 7414 Diag(D.getDeclSpec().getInlineSpecLoc(), 7415 diag::err_inline_declaration_block_scope) << Name 7416 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 7417 } else { 7418 Diag(D.getDeclSpec().getInlineSpecLoc(), 7419 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable 7420 : diag::ext_inline_variable); 7421 NewVD->setInlineSpecified(); 7422 } 7423 } 7424 7425 // Set the lexical context. If the declarator has a C++ scope specifier, the 7426 // lexical context will be different from the semantic context. 7427 NewVD->setLexicalDeclContext(CurContext); 7428 if (NewTemplate) 7429 NewTemplate->setLexicalDeclContext(CurContext); 7430 7431 if (IsLocalExternDecl) { 7432 if (D.isDecompositionDeclarator()) 7433 for (auto *B : Bindings) 7434 B->setLocalExternDecl(); 7435 else 7436 NewVD->setLocalExternDecl(); 7437 } 7438 7439 bool EmitTLSUnsupportedError = false; 7440 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 7441 // C++11 [dcl.stc]p4: 7442 // When thread_local is applied to a variable of block scope the 7443 // storage-class-specifier static is implied if it does not appear 7444 // explicitly. 7445 // Core issue: 'static' is not implied if the variable is declared 7446 // 'extern'. 7447 if (NewVD->hasLocalStorage() && 7448 (SCSpec != DeclSpec::SCS_unspecified || 7449 TSCS != DeclSpec::TSCS_thread_local || 7450 !DC->isFunctionOrMethod())) 7451 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7452 diag::err_thread_non_global) 7453 << DeclSpec::getSpecifierName(TSCS); 7454 else if (!Context.getTargetInfo().isTLSSupported()) { 7455 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || 7456 getLangOpts().SYCLIsDevice) { 7457 // Postpone error emission until we've collected attributes required to 7458 // figure out whether it's a host or device variable and whether the 7459 // error should be ignored. 7460 EmitTLSUnsupportedError = true; 7461 // We still need to mark the variable as TLS so it shows up in AST with 7462 // proper storage class for other tools to use even if we're not going 7463 // to emit any code for it. 7464 NewVD->setTSCSpec(TSCS); 7465 } else 7466 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7467 diag::err_thread_unsupported); 7468 } else 7469 NewVD->setTSCSpec(TSCS); 7470 } 7471 7472 switch (D.getDeclSpec().getConstexprSpecifier()) { 7473 case ConstexprSpecKind::Unspecified: 7474 break; 7475 7476 case ConstexprSpecKind::Consteval: 7477 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7478 diag::err_constexpr_wrong_decl_kind) 7479 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 7480 LLVM_FALLTHROUGH; 7481 7482 case ConstexprSpecKind::Constexpr: 7483 NewVD->setConstexpr(true); 7484 // C++1z [dcl.spec.constexpr]p1: 7485 // A static data member declared with the constexpr specifier is 7486 // implicitly an inline variable. 7487 if (NewVD->isStaticDataMember() && 7488 (getLangOpts().CPlusPlus17 || 7489 Context.getTargetInfo().getCXXABI().isMicrosoft())) 7490 NewVD->setImplicitlyInline(); 7491 break; 7492 7493 case ConstexprSpecKind::Constinit: 7494 if (!NewVD->hasGlobalStorage()) 7495 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7496 diag::err_constinit_local_variable); 7497 else 7498 NewVD->addAttr(ConstInitAttr::Create( 7499 Context, D.getDeclSpec().getConstexprSpecLoc(), 7500 AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit)); 7501 break; 7502 } 7503 7504 // C99 6.7.4p3 7505 // An inline definition of a function with external linkage shall 7506 // not contain a definition of a modifiable object with static or 7507 // thread storage duration... 7508 // We only apply this when the function is required to be defined 7509 // elsewhere, i.e. when the function is not 'extern inline'. Note 7510 // that a local variable with thread storage duration still has to 7511 // be marked 'static'. Also note that it's possible to get these 7512 // semantics in C++ using __attribute__((gnu_inline)). 7513 if (SC == SC_Static && S->getFnParent() != nullptr && 7514 !NewVD->getType().isConstQualified()) { 7515 FunctionDecl *CurFD = getCurFunctionDecl(); 7516 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 7517 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7518 diag::warn_static_local_in_extern_inline); 7519 MaybeSuggestAddingStaticToDecl(CurFD); 7520 } 7521 } 7522 7523 if (D.getDeclSpec().isModulePrivateSpecified()) { 7524 if (IsVariableTemplateSpecialization) 7525 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7526 << (IsPartialSpecialization ? 1 : 0) 7527 << FixItHint::CreateRemoval( 7528 D.getDeclSpec().getModulePrivateSpecLoc()); 7529 else if (IsMemberSpecialization) 7530 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7531 << 2 7532 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 7533 else if (NewVD->hasLocalStorage()) 7534 Diag(NewVD->getLocation(), diag::err_module_private_local) 7535 << 0 << NewVD 7536 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 7537 << FixItHint::CreateRemoval( 7538 D.getDeclSpec().getModulePrivateSpecLoc()); 7539 else { 7540 NewVD->setModulePrivate(); 7541 if (NewTemplate) 7542 NewTemplate->setModulePrivate(); 7543 for (auto *B : Bindings) 7544 B->setModulePrivate(); 7545 } 7546 } 7547 7548 if (getLangOpts().OpenCL) { 7549 deduceOpenCLAddressSpace(NewVD); 7550 7551 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec(); 7552 if (TSC != TSCS_unspecified) { 7553 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7554 diag::err_opencl_unknown_type_specifier) 7555 << getLangOpts().getOpenCLVersionString() 7556 << DeclSpec::getSpecifierName(TSC) << 1; 7557 NewVD->setInvalidDecl(); 7558 } 7559 } 7560 7561 // Handle attributes prior to checking for duplicates in MergeVarDecl 7562 ProcessDeclAttributes(S, NewVD, D); 7563 7564 // FIXME: This is probably the wrong location to be doing this and we should 7565 // probably be doing this for more attributes (especially for function 7566 // pointer attributes such as format, warn_unused_result, etc.). Ideally 7567 // the code to copy attributes would be generated by TableGen. 7568 if (R->isFunctionPointerType()) 7569 if (const auto *TT = R->getAs<TypedefType>()) 7570 copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT); 7571 7572 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || 7573 getLangOpts().SYCLIsDevice) { 7574 if (EmitTLSUnsupportedError && 7575 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || 7576 (getLangOpts().OpenMPIsDevice && 7577 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD)))) 7578 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7579 diag::err_thread_unsupported); 7580 7581 if (EmitTLSUnsupportedError && 7582 (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice))) 7583 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported); 7584 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 7585 // storage [duration]." 7586 if (SC == SC_None && S->getFnParent() != nullptr && 7587 (NewVD->hasAttr<CUDASharedAttr>() || 7588 NewVD->hasAttr<CUDAConstantAttr>())) { 7589 NewVD->setStorageClass(SC_Static); 7590 } 7591 } 7592 7593 // Ensure that dllimport globals without explicit storage class are treated as 7594 // extern. The storage class is set above using parsed attributes. Now we can 7595 // check the VarDecl itself. 7596 assert(!NewVD->hasAttr<DLLImportAttr>() || 7597 NewVD->getAttr<DLLImportAttr>()->isInherited() || 7598 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 7599 7600 // In auto-retain/release, infer strong retension for variables of 7601 // retainable type. 7602 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 7603 NewVD->setInvalidDecl(); 7604 7605 // Handle GNU asm-label extension (encoded as an attribute). 7606 if (Expr *E = (Expr*)D.getAsmLabel()) { 7607 // The parser guarantees this is a string. 7608 StringLiteral *SE = cast<StringLiteral>(E); 7609 StringRef Label = SE->getString(); 7610 if (S->getFnParent() != nullptr) { 7611 switch (SC) { 7612 case SC_None: 7613 case SC_Auto: 7614 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 7615 break; 7616 case SC_Register: 7617 // Local Named register 7618 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 7619 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 7620 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7621 break; 7622 case SC_Static: 7623 case SC_Extern: 7624 case SC_PrivateExtern: 7625 break; 7626 } 7627 } else if (SC == SC_Register) { 7628 // Global Named register 7629 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 7630 const auto &TI = Context.getTargetInfo(); 7631 bool HasSizeMismatch; 7632 7633 if (!TI.isValidGCCRegisterName(Label)) 7634 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7635 else if (!TI.validateGlobalRegisterVariable(Label, 7636 Context.getTypeSize(R), 7637 HasSizeMismatch)) 7638 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 7639 else if (HasSizeMismatch) 7640 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 7641 } 7642 7643 if (!R->isIntegralType(Context) && !R->isPointerType()) { 7644 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type); 7645 NewVD->setInvalidDecl(true); 7646 } 7647 } 7648 7649 NewVD->addAttr(AsmLabelAttr::Create(Context, Label, 7650 /*IsLiteralLabel=*/true, 7651 SE->getStrTokenLoc(0))); 7652 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 7653 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 7654 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 7655 if (I != ExtnameUndeclaredIdentifiers.end()) { 7656 if (isDeclExternC(NewVD)) { 7657 NewVD->addAttr(I->second); 7658 ExtnameUndeclaredIdentifiers.erase(I); 7659 } else 7660 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 7661 << /*Variable*/1 << NewVD; 7662 } 7663 } 7664 7665 // Find the shadowed declaration before filtering for scope. 7666 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 7667 ? getShadowedDeclaration(NewVD, Previous) 7668 : nullptr; 7669 7670 // Don't consider existing declarations that are in a different 7671 // scope and are out-of-semantic-context declarations (if the new 7672 // declaration has linkage). 7673 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 7674 D.getCXXScopeSpec().isNotEmpty() || 7675 IsMemberSpecialization || 7676 IsVariableTemplateSpecialization); 7677 7678 // Check whether the previous declaration is in the same block scope. This 7679 // affects whether we merge types with it, per C++11 [dcl.array]p3. 7680 if (getLangOpts().CPlusPlus && 7681 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 7682 NewVD->setPreviousDeclInSameBlockScope( 7683 Previous.isSingleResult() && !Previous.isShadowed() && 7684 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 7685 7686 if (!getLangOpts().CPlusPlus) { 7687 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7688 } else { 7689 // If this is an explicit specialization of a static data member, check it. 7690 if (IsMemberSpecialization && !NewVD->isInvalidDecl() && 7691 CheckMemberSpecialization(NewVD, Previous)) 7692 NewVD->setInvalidDecl(); 7693 7694 // Merge the decl with the existing one if appropriate. 7695 if (!Previous.empty()) { 7696 if (Previous.isSingleResult() && 7697 isa<FieldDecl>(Previous.getFoundDecl()) && 7698 D.getCXXScopeSpec().isSet()) { 7699 // The user tried to define a non-static data member 7700 // out-of-line (C++ [dcl.meaning]p1). 7701 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 7702 << D.getCXXScopeSpec().getRange(); 7703 Previous.clear(); 7704 NewVD->setInvalidDecl(); 7705 } 7706 } else if (D.getCXXScopeSpec().isSet()) { 7707 // No previous declaration in the qualifying scope. 7708 Diag(D.getIdentifierLoc(), diag::err_no_member) 7709 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 7710 << D.getCXXScopeSpec().getRange(); 7711 NewVD->setInvalidDecl(); 7712 } 7713 7714 if (!IsVariableTemplateSpecialization) 7715 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7716 7717 if (NewTemplate) { 7718 VarTemplateDecl *PrevVarTemplate = 7719 NewVD->getPreviousDecl() 7720 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 7721 : nullptr; 7722 7723 // Check the template parameter list of this declaration, possibly 7724 // merging in the template parameter list from the previous variable 7725 // template declaration. 7726 if (CheckTemplateParameterList( 7727 TemplateParams, 7728 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 7729 : nullptr, 7730 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 7731 DC->isDependentContext()) 7732 ? TPC_ClassTemplateMember 7733 : TPC_VarTemplate)) 7734 NewVD->setInvalidDecl(); 7735 7736 // If we are providing an explicit specialization of a static variable 7737 // template, make a note of that. 7738 if (PrevVarTemplate && 7739 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 7740 PrevVarTemplate->setMemberSpecialization(); 7741 } 7742 } 7743 7744 // Diagnose shadowed variables iff this isn't a redeclaration. 7745 if (ShadowedDecl && !D.isRedeclaration()) 7746 CheckShadow(NewVD, ShadowedDecl, Previous); 7747 7748 ProcessPragmaWeak(S, NewVD); 7749 7750 // If this is the first declaration of an extern C variable, update 7751 // the map of such variables. 7752 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 7753 isIncompleteDeclExternC(*this, NewVD)) 7754 RegisterLocallyScopedExternCDecl(NewVD, S); 7755 7756 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 7757 MangleNumberingContext *MCtx; 7758 Decl *ManglingContextDecl; 7759 std::tie(MCtx, ManglingContextDecl) = 7760 getCurrentMangleNumberContext(NewVD->getDeclContext()); 7761 if (MCtx) { 7762 Context.setManglingNumber( 7763 NewVD, MCtx->getManglingNumber( 7764 NewVD, getMSManglingNumber(getLangOpts(), S))); 7765 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 7766 } 7767 } 7768 7769 // Special handling of variable named 'main'. 7770 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 7771 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 7772 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 7773 7774 // C++ [basic.start.main]p3 7775 // A program that declares a variable main at global scope is ill-formed. 7776 if (getLangOpts().CPlusPlus) 7777 Diag(D.getBeginLoc(), diag::err_main_global_variable); 7778 7779 // In C, and external-linkage variable named main results in undefined 7780 // behavior. 7781 else if (NewVD->hasExternalFormalLinkage()) 7782 Diag(D.getBeginLoc(), diag::warn_main_redefined); 7783 } 7784 7785 if (D.isRedeclaration() && !Previous.empty()) { 7786 NamedDecl *Prev = Previous.getRepresentativeDecl(); 7787 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization, 7788 D.isFunctionDefinition()); 7789 } 7790 7791 if (NewTemplate) { 7792 if (NewVD->isInvalidDecl()) 7793 NewTemplate->setInvalidDecl(); 7794 ActOnDocumentableDecl(NewTemplate); 7795 return NewTemplate; 7796 } 7797 7798 if (IsMemberSpecialization && !NewVD->isInvalidDecl()) 7799 CompleteMemberSpecialization(NewVD, Previous); 7800 7801 return NewVD; 7802 } 7803 7804 /// Enum describing the %select options in diag::warn_decl_shadow. 7805 enum ShadowedDeclKind { 7806 SDK_Local, 7807 SDK_Global, 7808 SDK_StaticMember, 7809 SDK_Field, 7810 SDK_Typedef, 7811 SDK_Using, 7812 SDK_StructuredBinding 7813 }; 7814 7815 /// Determine what kind of declaration we're shadowing. 7816 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 7817 const DeclContext *OldDC) { 7818 if (isa<TypeAliasDecl>(ShadowedDecl)) 7819 return SDK_Using; 7820 else if (isa<TypedefDecl>(ShadowedDecl)) 7821 return SDK_Typedef; 7822 else if (isa<BindingDecl>(ShadowedDecl)) 7823 return SDK_StructuredBinding; 7824 else if (isa<RecordDecl>(OldDC)) 7825 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 7826 7827 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 7828 } 7829 7830 /// Return the location of the capture if the given lambda captures the given 7831 /// variable \p VD, or an invalid source location otherwise. 7832 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 7833 const VarDecl *VD) { 7834 for (const Capture &Capture : LSI->Captures) { 7835 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 7836 return Capture.getLocation(); 7837 } 7838 return SourceLocation(); 7839 } 7840 7841 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, 7842 const LookupResult &R) { 7843 // Only diagnose if we're shadowing an unambiguous field or variable. 7844 if (R.getResultKind() != LookupResult::Found) 7845 return false; 7846 7847 // Return false if warning is ignored. 7848 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); 7849 } 7850 7851 /// Return the declaration shadowed by the given variable \p D, or null 7852 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7853 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 7854 const LookupResult &R) { 7855 if (!shouldWarnIfShadowedDecl(Diags, R)) 7856 return nullptr; 7857 7858 // Don't diagnose declarations at file scope. 7859 if (D->hasGlobalStorage()) 7860 return nullptr; 7861 7862 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7863 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl 7864 : nullptr; 7865 } 7866 7867 /// Return the declaration shadowed by the given typedef \p D, or null 7868 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7869 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, 7870 const LookupResult &R) { 7871 // Don't warn if typedef declaration is part of a class 7872 if (D->getDeclContext()->isRecord()) 7873 return nullptr; 7874 7875 if (!shouldWarnIfShadowedDecl(Diags, R)) 7876 return nullptr; 7877 7878 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7879 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; 7880 } 7881 7882 /// Return the declaration shadowed by the given variable \p D, or null 7883 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7884 NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D, 7885 const LookupResult &R) { 7886 if (!shouldWarnIfShadowedDecl(Diags, R)) 7887 return nullptr; 7888 7889 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7890 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl 7891 : nullptr; 7892 } 7893 7894 /// Diagnose variable or built-in function shadowing. Implements 7895 /// -Wshadow. 7896 /// 7897 /// This method is called whenever a VarDecl is added to a "useful" 7898 /// scope. 7899 /// 7900 /// \param ShadowedDecl the declaration that is shadowed by the given variable 7901 /// \param R the lookup of the name 7902 /// 7903 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 7904 const LookupResult &R) { 7905 DeclContext *NewDC = D->getDeclContext(); 7906 7907 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 7908 // Fields are not shadowed by variables in C++ static methods. 7909 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 7910 if (MD->isStatic()) 7911 return; 7912 7913 // Fields shadowed by constructor parameters are a special case. Usually 7914 // the constructor initializes the field with the parameter. 7915 if (isa<CXXConstructorDecl>(NewDC)) 7916 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { 7917 // Remember that this was shadowed so we can either warn about its 7918 // modification or its existence depending on warning settings. 7919 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); 7920 return; 7921 } 7922 } 7923 7924 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 7925 if (shadowedVar->isExternC()) { 7926 // For shadowing external vars, make sure that we point to the global 7927 // declaration, not a locally scoped extern declaration. 7928 for (auto I : shadowedVar->redecls()) 7929 if (I->isFileVarDecl()) { 7930 ShadowedDecl = I; 7931 break; 7932 } 7933 } 7934 7935 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); 7936 7937 unsigned WarningDiag = diag::warn_decl_shadow; 7938 SourceLocation CaptureLoc; 7939 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && 7940 isa<CXXMethodDecl>(NewDC)) { 7941 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 7942 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 7943 if (RD->getLambdaCaptureDefault() == LCD_None) { 7944 // Try to avoid warnings for lambdas with an explicit capture list. 7945 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 7946 // Warn only when the lambda captures the shadowed decl explicitly. 7947 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 7948 if (CaptureLoc.isInvalid()) 7949 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 7950 } else { 7951 // Remember that this was shadowed so we can avoid the warning if the 7952 // shadowed decl isn't captured and the warning settings allow it. 7953 cast<LambdaScopeInfo>(getCurFunction()) 7954 ->ShadowingDecls.push_back( 7955 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); 7956 return; 7957 } 7958 } 7959 7960 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { 7961 // A variable can't shadow a local variable in an enclosing scope, if 7962 // they are separated by a non-capturing declaration context. 7963 for (DeclContext *ParentDC = NewDC; 7964 ParentDC && !ParentDC->Equals(OldDC); 7965 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { 7966 // Only block literals, captured statements, and lambda expressions 7967 // can capture; other scopes don't. 7968 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && 7969 !isLambdaCallOperator(ParentDC)) { 7970 return; 7971 } 7972 } 7973 } 7974 } 7975 } 7976 7977 // Only warn about certain kinds of shadowing for class members. 7978 if (NewDC && NewDC->isRecord()) { 7979 // In particular, don't warn about shadowing non-class members. 7980 if (!OldDC->isRecord()) 7981 return; 7982 7983 // TODO: should we warn about static data members shadowing 7984 // static data members from base classes? 7985 7986 // TODO: don't diagnose for inaccessible shadowed members. 7987 // This is hard to do perfectly because we might friend the 7988 // shadowing context, but that's just a false negative. 7989 } 7990 7991 7992 DeclarationName Name = R.getLookupName(); 7993 7994 // Emit warning and note. 7995 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 7996 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 7997 if (!CaptureLoc.isInvalid()) 7998 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7999 << Name << /*explicitly*/ 1; 8000 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 8001 } 8002 8003 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 8004 /// when these variables are captured by the lambda. 8005 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 8006 for (const auto &Shadow : LSI->ShadowingDecls) { 8007 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 8008 // Try to avoid the warning when the shadowed decl isn't captured. 8009 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 8010 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 8011 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 8012 ? diag::warn_decl_shadow_uncaptured_local 8013 : diag::warn_decl_shadow) 8014 << Shadow.VD->getDeclName() 8015 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 8016 if (!CaptureLoc.isInvalid()) 8017 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 8018 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 8019 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 8020 } 8021 } 8022 8023 /// Check -Wshadow without the advantage of a previous lookup. 8024 void Sema::CheckShadow(Scope *S, VarDecl *D) { 8025 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 8026 return; 8027 8028 LookupResult R(*this, D->getDeclName(), D->getLocation(), 8029 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); 8030 LookupName(R, S); 8031 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 8032 CheckShadow(D, ShadowedDecl, R); 8033 } 8034 8035 /// Check if 'E', which is an expression that is about to be modified, refers 8036 /// to a constructor parameter that shadows a field. 8037 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 8038 // Quickly ignore expressions that can't be shadowing ctor parameters. 8039 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 8040 return; 8041 E = E->IgnoreParenImpCasts(); 8042 auto *DRE = dyn_cast<DeclRefExpr>(E); 8043 if (!DRE) 8044 return; 8045 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 8046 auto I = ShadowingDecls.find(D); 8047 if (I == ShadowingDecls.end()) 8048 return; 8049 const NamedDecl *ShadowedDecl = I->second; 8050 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 8051 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 8052 Diag(D->getLocation(), diag::note_var_declared_here) << D; 8053 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 8054 8055 // Avoid issuing multiple warnings about the same decl. 8056 ShadowingDecls.erase(I); 8057 } 8058 8059 /// Check for conflict between this global or extern "C" declaration and 8060 /// previous global or extern "C" declarations. This is only used in C++. 8061 template<typename T> 8062 static bool checkGlobalOrExternCConflict( 8063 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 8064 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 8065 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 8066 8067 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 8068 // The common case: this global doesn't conflict with any extern "C" 8069 // declaration. 8070 return false; 8071 } 8072 8073 if (Prev) { 8074 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 8075 // Both the old and new declarations have C language linkage. This is a 8076 // redeclaration. 8077 Previous.clear(); 8078 Previous.addDecl(Prev); 8079 return true; 8080 } 8081 8082 // This is a global, non-extern "C" declaration, and there is a previous 8083 // non-global extern "C" declaration. Diagnose if this is a variable 8084 // declaration. 8085 if (!isa<VarDecl>(ND)) 8086 return false; 8087 } else { 8088 // The declaration is extern "C". Check for any declaration in the 8089 // translation unit which might conflict. 8090 if (IsGlobal) { 8091 // We have already performed the lookup into the translation unit. 8092 IsGlobal = false; 8093 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 8094 I != E; ++I) { 8095 if (isa<VarDecl>(*I)) { 8096 Prev = *I; 8097 break; 8098 } 8099 } 8100 } else { 8101 DeclContext::lookup_result R = 8102 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 8103 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 8104 I != E; ++I) { 8105 if (isa<VarDecl>(*I)) { 8106 Prev = *I; 8107 break; 8108 } 8109 // FIXME: If we have any other entity with this name in global scope, 8110 // the declaration is ill-formed, but that is a defect: it breaks the 8111 // 'stat' hack, for instance. Only variables can have mangled name 8112 // clashes with extern "C" declarations, so only they deserve a 8113 // diagnostic. 8114 } 8115 } 8116 8117 if (!Prev) 8118 return false; 8119 } 8120 8121 // Use the first declaration's location to ensure we point at something which 8122 // is lexically inside an extern "C" linkage-spec. 8123 assert(Prev && "should have found a previous declaration to diagnose"); 8124 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 8125 Prev = FD->getFirstDecl(); 8126 else 8127 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 8128 8129 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 8130 << IsGlobal << ND; 8131 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 8132 << IsGlobal; 8133 return false; 8134 } 8135 8136 /// Apply special rules for handling extern "C" declarations. Returns \c true 8137 /// if we have found that this is a redeclaration of some prior entity. 8138 /// 8139 /// Per C++ [dcl.link]p6: 8140 /// Two declarations [for a function or variable] with C language linkage 8141 /// with the same name that appear in different scopes refer to the same 8142 /// [entity]. An entity with C language linkage shall not be declared with 8143 /// the same name as an entity in global scope. 8144 template<typename T> 8145 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 8146 LookupResult &Previous) { 8147 if (!S.getLangOpts().CPlusPlus) { 8148 // In C, when declaring a global variable, look for a corresponding 'extern' 8149 // variable declared in function scope. We don't need this in C++, because 8150 // we find local extern decls in the surrounding file-scope DeclContext. 8151 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 8152 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 8153 Previous.clear(); 8154 Previous.addDecl(Prev); 8155 return true; 8156 } 8157 } 8158 return false; 8159 } 8160 8161 // A declaration in the translation unit can conflict with an extern "C" 8162 // declaration. 8163 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 8164 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 8165 8166 // An extern "C" declaration can conflict with a declaration in the 8167 // translation unit or can be a redeclaration of an extern "C" declaration 8168 // in another scope. 8169 if (isIncompleteDeclExternC(S,ND)) 8170 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 8171 8172 // Neither global nor extern "C": nothing to do. 8173 return false; 8174 } 8175 8176 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 8177 // If the decl is already known invalid, don't check it. 8178 if (NewVD->isInvalidDecl()) 8179 return; 8180 8181 QualType T = NewVD->getType(); 8182 8183 // Defer checking an 'auto' type until its initializer is attached. 8184 if (T->isUndeducedType()) 8185 return; 8186 8187 if (NewVD->hasAttrs()) 8188 CheckAlignasUnderalignment(NewVD); 8189 8190 if (T->isObjCObjectType()) { 8191 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 8192 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 8193 T = Context.getObjCObjectPointerType(T); 8194 NewVD->setType(T); 8195 } 8196 8197 // Emit an error if an address space was applied to decl with local storage. 8198 // This includes arrays of objects with address space qualifiers, but not 8199 // automatic variables that point to other address spaces. 8200 // ISO/IEC TR 18037 S5.1.2 8201 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && 8202 T.getAddressSpace() != LangAS::Default) { 8203 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; 8204 NewVD->setInvalidDecl(); 8205 return; 8206 } 8207 8208 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 8209 // scope. 8210 if (getLangOpts().OpenCLVersion == 120 && 8211 !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers", 8212 getLangOpts()) && 8213 NewVD->isStaticLocal()) { 8214 Diag(NewVD->getLocation(), diag::err_static_function_scope); 8215 NewVD->setInvalidDecl(); 8216 return; 8217 } 8218 8219 if (getLangOpts().OpenCL) { 8220 if (!diagnoseOpenCLTypes(*this, NewVD)) 8221 return; 8222 8223 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 8224 if (NewVD->hasAttr<BlocksAttr>()) { 8225 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 8226 return; 8227 } 8228 8229 if (T->isBlockPointerType()) { 8230 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 8231 // can't use 'extern' storage class. 8232 if (!T.isConstQualified()) { 8233 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 8234 << 0 /*const*/; 8235 NewVD->setInvalidDecl(); 8236 return; 8237 } 8238 if (NewVD->hasExternalStorage()) { 8239 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 8240 NewVD->setInvalidDecl(); 8241 return; 8242 } 8243 } 8244 8245 // FIXME: Adding local AS in C++ for OpenCL might make sense. 8246 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 8247 NewVD->hasExternalStorage()) { 8248 if (!T->isSamplerT() && !T->isDependentType() && 8249 !(T.getAddressSpace() == LangAS::opencl_constant || 8250 (T.getAddressSpace() == LangAS::opencl_global && 8251 getOpenCLOptions().areProgramScopeVariablesSupported( 8252 getLangOpts())))) { 8253 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 8254 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts())) 8255 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 8256 << Scope << "global or constant"; 8257 else 8258 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 8259 << Scope << "constant"; 8260 NewVD->setInvalidDecl(); 8261 return; 8262 } 8263 } else { 8264 if (T.getAddressSpace() == LangAS::opencl_global) { 8265 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 8266 << 1 /*is any function*/ << "global"; 8267 NewVD->setInvalidDecl(); 8268 return; 8269 } 8270 if (T.getAddressSpace() == LangAS::opencl_constant || 8271 T.getAddressSpace() == LangAS::opencl_local) { 8272 FunctionDecl *FD = getCurFunctionDecl(); 8273 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables 8274 // in functions. 8275 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 8276 if (T.getAddressSpace() == LangAS::opencl_constant) 8277 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 8278 << 0 /*non-kernel only*/ << "constant"; 8279 else 8280 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 8281 << 0 /*non-kernel only*/ << "local"; 8282 NewVD->setInvalidDecl(); 8283 return; 8284 } 8285 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be 8286 // in the outermost scope of a kernel function. 8287 if (FD && FD->hasAttr<OpenCLKernelAttr>()) { 8288 if (!getCurScope()->isFunctionScope()) { 8289 if (T.getAddressSpace() == LangAS::opencl_constant) 8290 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 8291 << "constant"; 8292 else 8293 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 8294 << "local"; 8295 NewVD->setInvalidDecl(); 8296 return; 8297 } 8298 } 8299 } else if (T.getAddressSpace() != LangAS::opencl_private && 8300 // If we are parsing a template we didn't deduce an addr 8301 // space yet. 8302 T.getAddressSpace() != LangAS::Default) { 8303 // Do not allow other address spaces on automatic variable. 8304 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; 8305 NewVD->setInvalidDecl(); 8306 return; 8307 } 8308 } 8309 } 8310 8311 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 8312 && !NewVD->hasAttr<BlocksAttr>()) { 8313 if (getLangOpts().getGC() != LangOptions::NonGC) 8314 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 8315 else { 8316 assert(!getLangOpts().ObjCAutoRefCount); 8317 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 8318 } 8319 } 8320 8321 bool isVM = T->isVariablyModifiedType(); 8322 if (isVM || NewVD->hasAttr<CleanupAttr>() || 8323 NewVD->hasAttr<BlocksAttr>()) 8324 setFunctionHasBranchProtectedScope(); 8325 8326 if ((isVM && NewVD->hasLinkage()) || 8327 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 8328 bool SizeIsNegative; 8329 llvm::APSInt Oversized; 8330 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 8331 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized); 8332 QualType FixedT; 8333 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType()) 8334 FixedT = FixedTInfo->getType(); 8335 else if (FixedTInfo) { 8336 // Type and type-as-written are canonically different. We need to fix up 8337 // both types separately. 8338 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 8339 Oversized); 8340 } 8341 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) { 8342 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 8343 // FIXME: This won't give the correct result for 8344 // int a[10][n]; 8345 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 8346 8347 if (NewVD->isFileVarDecl()) 8348 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 8349 << SizeRange; 8350 else if (NewVD->isStaticLocal()) 8351 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 8352 << SizeRange; 8353 else 8354 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 8355 << SizeRange; 8356 NewVD->setInvalidDecl(); 8357 return; 8358 } 8359 8360 if (!FixedTInfo) { 8361 if (NewVD->isFileVarDecl()) 8362 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 8363 else 8364 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 8365 NewVD->setInvalidDecl(); 8366 return; 8367 } 8368 8369 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant); 8370 NewVD->setType(FixedT); 8371 NewVD->setTypeSourceInfo(FixedTInfo); 8372 } 8373 8374 if (T->isVoidType()) { 8375 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 8376 // of objects and functions. 8377 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 8378 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 8379 << T; 8380 NewVD->setInvalidDecl(); 8381 return; 8382 } 8383 } 8384 8385 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 8386 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 8387 NewVD->setInvalidDecl(); 8388 return; 8389 } 8390 8391 if (!NewVD->hasLocalStorage() && T->isSizelessType()) { 8392 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T; 8393 NewVD->setInvalidDecl(); 8394 return; 8395 } 8396 8397 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 8398 Diag(NewVD->getLocation(), diag::err_block_on_vm); 8399 NewVD->setInvalidDecl(); 8400 return; 8401 } 8402 8403 if (NewVD->isConstexpr() && !T->isDependentType() && 8404 RequireLiteralType(NewVD->getLocation(), T, 8405 diag::err_constexpr_var_non_literal)) { 8406 NewVD->setInvalidDecl(); 8407 return; 8408 } 8409 8410 // PPC MMA non-pointer types are not allowed as non-local variable types. 8411 if (Context.getTargetInfo().getTriple().isPPC64() && 8412 !NewVD->isLocalVarDecl() && 8413 CheckPPCMMAType(T, NewVD->getLocation())) { 8414 NewVD->setInvalidDecl(); 8415 return; 8416 } 8417 } 8418 8419 /// Perform semantic checking on a newly-created variable 8420 /// declaration. 8421 /// 8422 /// This routine performs all of the type-checking required for a 8423 /// variable declaration once it has been built. It is used both to 8424 /// check variables after they have been parsed and their declarators 8425 /// have been translated into a declaration, and to check variables 8426 /// that have been instantiated from a template. 8427 /// 8428 /// Sets NewVD->isInvalidDecl() if an error was encountered. 8429 /// 8430 /// Returns true if the variable declaration is a redeclaration. 8431 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 8432 CheckVariableDeclarationType(NewVD); 8433 8434 // If the decl is already known invalid, don't check it. 8435 if (NewVD->isInvalidDecl()) 8436 return false; 8437 8438 // If we did not find anything by this name, look for a non-visible 8439 // extern "C" declaration with the same name. 8440 if (Previous.empty() && 8441 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 8442 Previous.setShadowed(); 8443 8444 if (!Previous.empty()) { 8445 MergeVarDecl(NewVD, Previous); 8446 return true; 8447 } 8448 return false; 8449 } 8450 8451 /// AddOverriddenMethods - See if a method overrides any in the base classes, 8452 /// and if so, check that it's a valid override and remember it. 8453 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 8454 llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden; 8455 8456 // Look for methods in base classes that this method might override. 8457 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false, 8458 /*DetectVirtual=*/false); 8459 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 8460 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl(); 8461 DeclarationName Name = MD->getDeclName(); 8462 8463 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8464 // We really want to find the base class destructor here. 8465 QualType T = Context.getTypeDeclType(BaseRecord); 8466 CanQualType CT = Context.getCanonicalType(T); 8467 Name = Context.DeclarationNames.getCXXDestructorName(CT); 8468 } 8469 8470 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) { 8471 CXXMethodDecl *BaseMD = 8472 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl()); 8473 if (!BaseMD || !BaseMD->isVirtual() || 8474 IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false, 8475 /*ConsiderCudaAttrs=*/true, 8476 // C++2a [class.virtual]p2 does not consider requires 8477 // clauses when overriding. 8478 /*ConsiderRequiresClauses=*/false)) 8479 continue; 8480 8481 if (Overridden.insert(BaseMD).second) { 8482 MD->addOverriddenMethod(BaseMD); 8483 CheckOverridingFunctionReturnType(MD, BaseMD); 8484 CheckOverridingFunctionAttributes(MD, BaseMD); 8485 CheckOverridingFunctionExceptionSpec(MD, BaseMD); 8486 CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD); 8487 } 8488 8489 // A method can only override one function from each base class. We 8490 // don't track indirectly overridden methods from bases of bases. 8491 return true; 8492 } 8493 8494 return false; 8495 }; 8496 8497 DC->lookupInBases(VisitBase, Paths); 8498 return !Overridden.empty(); 8499 } 8500 8501 namespace { 8502 // Struct for holding all of the extra arguments needed by 8503 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 8504 struct ActOnFDArgs { 8505 Scope *S; 8506 Declarator &D; 8507 MultiTemplateParamsArg TemplateParamLists; 8508 bool AddToScope; 8509 }; 8510 } // end anonymous namespace 8511 8512 namespace { 8513 8514 // Callback to only accept typo corrections that have a non-zero edit distance. 8515 // Also only accept corrections that have the same parent decl. 8516 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback { 8517 public: 8518 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 8519 CXXRecordDecl *Parent) 8520 : Context(Context), OriginalFD(TypoFD), 8521 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 8522 8523 bool ValidateCandidate(const TypoCorrection &candidate) override { 8524 if (candidate.getEditDistance() == 0) 8525 return false; 8526 8527 SmallVector<unsigned, 1> MismatchedParams; 8528 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 8529 CDeclEnd = candidate.end(); 8530 CDecl != CDeclEnd; ++CDecl) { 8531 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8532 8533 if (FD && !FD->hasBody() && 8534 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 8535 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 8536 CXXRecordDecl *Parent = MD->getParent(); 8537 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 8538 return true; 8539 } else if (!ExpectedParent) { 8540 return true; 8541 } 8542 } 8543 } 8544 8545 return false; 8546 } 8547 8548 std::unique_ptr<CorrectionCandidateCallback> clone() override { 8549 return std::make_unique<DifferentNameValidatorCCC>(*this); 8550 } 8551 8552 private: 8553 ASTContext &Context; 8554 FunctionDecl *OriginalFD; 8555 CXXRecordDecl *ExpectedParent; 8556 }; 8557 8558 } // end anonymous namespace 8559 8560 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { 8561 TypoCorrectedFunctionDefinitions.insert(F); 8562 } 8563 8564 /// Generate diagnostics for an invalid function redeclaration. 8565 /// 8566 /// This routine handles generating the diagnostic messages for an invalid 8567 /// function redeclaration, including finding possible similar declarations 8568 /// or performing typo correction if there are no previous declarations with 8569 /// the same name. 8570 /// 8571 /// Returns a NamedDecl iff typo correction was performed and substituting in 8572 /// the new declaration name does not cause new errors. 8573 static NamedDecl *DiagnoseInvalidRedeclaration( 8574 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 8575 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 8576 DeclarationName Name = NewFD->getDeclName(); 8577 DeclContext *NewDC = NewFD->getDeclContext(); 8578 SmallVector<unsigned, 1> MismatchedParams; 8579 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 8580 TypoCorrection Correction; 8581 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 8582 unsigned DiagMsg = 8583 IsLocalFriend ? diag::err_no_matching_local_friend : 8584 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match : 8585 diag::err_member_decl_does_not_match; 8586 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 8587 IsLocalFriend ? Sema::LookupLocalFriendName 8588 : Sema::LookupOrdinaryName, 8589 Sema::ForVisibleRedeclaration); 8590 8591 NewFD->setInvalidDecl(); 8592 if (IsLocalFriend) 8593 SemaRef.LookupName(Prev, S); 8594 else 8595 SemaRef.LookupQualifiedName(Prev, NewDC); 8596 assert(!Prev.isAmbiguous() && 8597 "Cannot have an ambiguity in previous-declaration lookup"); 8598 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 8599 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD, 8600 MD ? MD->getParent() : nullptr); 8601 if (!Prev.empty()) { 8602 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 8603 Func != FuncEnd; ++Func) { 8604 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 8605 if (FD && 8606 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8607 // Add 1 to the index so that 0 can mean the mismatch didn't 8608 // involve a parameter 8609 unsigned ParamNum = 8610 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 8611 NearMatches.push_back(std::make_pair(FD, ParamNum)); 8612 } 8613 } 8614 // If the qualified name lookup yielded nothing, try typo correction 8615 } else if ((Correction = SemaRef.CorrectTypo( 8616 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 8617 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery, 8618 IsLocalFriend ? nullptr : NewDC))) { 8619 // Set up everything for the call to ActOnFunctionDeclarator 8620 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 8621 ExtraArgs.D.getIdentifierLoc()); 8622 Previous.clear(); 8623 Previous.setLookupName(Correction.getCorrection()); 8624 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 8625 CDeclEnd = Correction.end(); 8626 CDecl != CDeclEnd; ++CDecl) { 8627 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8628 if (FD && !FD->hasBody() && 8629 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8630 Previous.addDecl(FD); 8631 } 8632 } 8633 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 8634 8635 NamedDecl *Result; 8636 // Retry building the function declaration with the new previous 8637 // declarations, and with errors suppressed. 8638 { 8639 // Trap errors. 8640 Sema::SFINAETrap Trap(SemaRef); 8641 8642 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 8643 // pieces need to verify the typo-corrected C++ declaration and hopefully 8644 // eliminate the need for the parameter pack ExtraArgs. 8645 Result = SemaRef.ActOnFunctionDeclarator( 8646 ExtraArgs.S, ExtraArgs.D, 8647 Correction.getCorrectionDecl()->getDeclContext(), 8648 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 8649 ExtraArgs.AddToScope); 8650 8651 if (Trap.hasErrorOccurred()) 8652 Result = nullptr; 8653 } 8654 8655 if (Result) { 8656 // Determine which correction we picked. 8657 Decl *Canonical = Result->getCanonicalDecl(); 8658 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 8659 I != E; ++I) 8660 if ((*I)->getCanonicalDecl() == Canonical) 8661 Correction.setCorrectionDecl(*I); 8662 8663 // Let Sema know about the correction. 8664 SemaRef.MarkTypoCorrectedFunctionDefinition(Result); 8665 SemaRef.diagnoseTypo( 8666 Correction, 8667 SemaRef.PDiag(IsLocalFriend 8668 ? diag::err_no_matching_local_friend_suggest 8669 : diag::err_member_decl_does_not_match_suggest) 8670 << Name << NewDC << IsDefinition); 8671 return Result; 8672 } 8673 8674 // Pretend the typo correction never occurred 8675 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 8676 ExtraArgs.D.getIdentifierLoc()); 8677 ExtraArgs.D.setRedeclaration(wasRedeclaration); 8678 Previous.clear(); 8679 Previous.setLookupName(Name); 8680 } 8681 8682 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 8683 << Name << NewDC << IsDefinition << NewFD->getLocation(); 8684 8685 bool NewFDisConst = false; 8686 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 8687 NewFDisConst = NewMD->isConst(); 8688 8689 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 8690 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 8691 NearMatch != NearMatchEnd; ++NearMatch) { 8692 FunctionDecl *FD = NearMatch->first; 8693 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 8694 bool FDisConst = MD && MD->isConst(); 8695 bool IsMember = MD || !IsLocalFriend; 8696 8697 // FIXME: These notes are poorly worded for the local friend case. 8698 if (unsigned Idx = NearMatch->second) { 8699 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 8700 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 8701 if (Loc.isInvalid()) Loc = FD->getLocation(); 8702 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 8703 : diag::note_local_decl_close_param_match) 8704 << Idx << FDParam->getType() 8705 << NewFD->getParamDecl(Idx - 1)->getType(); 8706 } else if (FDisConst != NewFDisConst) { 8707 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 8708 << NewFDisConst << FD->getSourceRange().getEnd() 8709 << (NewFDisConst 8710 ? FixItHint::CreateRemoval(ExtraArgs.D.getFunctionTypeInfo() 8711 .getConstQualifierLoc()) 8712 : FixItHint::CreateInsertion(ExtraArgs.D.getFunctionTypeInfo() 8713 .getRParenLoc() 8714 .getLocWithOffset(1), 8715 " const")); 8716 } else 8717 SemaRef.Diag(FD->getLocation(), 8718 IsMember ? diag::note_member_def_close_match 8719 : diag::note_local_decl_close_match); 8720 } 8721 return nullptr; 8722 } 8723 8724 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 8725 switch (D.getDeclSpec().getStorageClassSpec()) { 8726 default: llvm_unreachable("Unknown storage class!"); 8727 case DeclSpec::SCS_auto: 8728 case DeclSpec::SCS_register: 8729 case DeclSpec::SCS_mutable: 8730 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8731 diag::err_typecheck_sclass_func); 8732 D.getMutableDeclSpec().ClearStorageClassSpecs(); 8733 D.setInvalidType(); 8734 break; 8735 case DeclSpec::SCS_unspecified: break; 8736 case DeclSpec::SCS_extern: 8737 if (D.getDeclSpec().isExternInLinkageSpec()) 8738 return SC_None; 8739 return SC_Extern; 8740 case DeclSpec::SCS_static: { 8741 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 8742 // C99 6.7.1p5: 8743 // The declaration of an identifier for a function that has 8744 // block scope shall have no explicit storage-class specifier 8745 // other than extern 8746 // See also (C++ [dcl.stc]p4). 8747 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8748 diag::err_static_block_func); 8749 break; 8750 } else 8751 return SC_Static; 8752 } 8753 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 8754 } 8755 8756 // No explicit storage class has already been returned 8757 return SC_None; 8758 } 8759 8760 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 8761 DeclContext *DC, QualType &R, 8762 TypeSourceInfo *TInfo, 8763 StorageClass SC, 8764 bool &IsVirtualOkay) { 8765 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 8766 DeclarationName Name = NameInfo.getName(); 8767 8768 FunctionDecl *NewFD = nullptr; 8769 bool isInline = D.getDeclSpec().isInlineSpecified(); 8770 8771 if (!SemaRef.getLangOpts().CPlusPlus) { 8772 // Determine whether the function was written with a 8773 // prototype. This true when: 8774 // - there is a prototype in the declarator, or 8775 // - the type R of the function is some kind of typedef or other non- 8776 // attributed reference to a type name (which eventually refers to a 8777 // function type). 8778 bool HasPrototype = 8779 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 8780 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 8781 8782 NewFD = FunctionDecl::Create( 8783 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC, 8784 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype, 8785 ConstexprSpecKind::Unspecified, 8786 /*TrailingRequiresClause=*/nullptr); 8787 if (D.isInvalidType()) 8788 NewFD->setInvalidDecl(); 8789 8790 return NewFD; 8791 } 8792 8793 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier(); 8794 8795 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 8796 if (ConstexprKind == ConstexprSpecKind::Constinit) { 8797 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(), 8798 diag::err_constexpr_wrong_decl_kind) 8799 << static_cast<int>(ConstexprKind); 8800 ConstexprKind = ConstexprSpecKind::Unspecified; 8801 D.getMutableDeclSpec().ClearConstexprSpec(); 8802 } 8803 Expr *TrailingRequiresClause = D.getTrailingRequiresClause(); 8804 8805 // Check that the return type is not an abstract class type. 8806 // For record types, this is done by the AbstractClassUsageDiagnoser once 8807 // the class has been completely parsed. 8808 if (!DC->isRecord() && 8809 SemaRef.RequireNonAbstractType( 8810 D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(), 8811 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 8812 D.setInvalidType(); 8813 8814 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 8815 // This is a C++ constructor declaration. 8816 assert(DC->isRecord() && 8817 "Constructors can only be declared in a member context"); 8818 8819 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 8820 return CXXConstructorDecl::Create( 8821 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8822 TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(), 8823 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind, 8824 InheritedConstructor(), TrailingRequiresClause); 8825 8826 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8827 // This is a C++ destructor declaration. 8828 if (DC->isRecord()) { 8829 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 8830 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 8831 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 8832 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo, 8833 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 8834 /*isImplicitlyDeclared=*/false, ConstexprKind, 8835 TrailingRequiresClause); 8836 8837 // If the destructor needs an implicit exception specification, set it 8838 // now. FIXME: It'd be nice to be able to create the right type to start 8839 // with, but the type needs to reference the destructor declaration. 8840 if (SemaRef.getLangOpts().CPlusPlus11) 8841 SemaRef.AdjustDestructorExceptionSpec(NewDD); 8842 8843 IsVirtualOkay = true; 8844 return NewDD; 8845 8846 } else { 8847 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 8848 D.setInvalidType(); 8849 8850 // Create a FunctionDecl to satisfy the function definition parsing 8851 // code path. 8852 return FunctionDecl::Create( 8853 SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R, 8854 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 8855 /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause); 8856 } 8857 8858 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 8859 if (!DC->isRecord()) { 8860 SemaRef.Diag(D.getIdentifierLoc(), 8861 diag::err_conv_function_not_member); 8862 return nullptr; 8863 } 8864 8865 SemaRef.CheckConversionDeclarator(D, R, SC); 8866 if (D.isInvalidType()) 8867 return nullptr; 8868 8869 IsVirtualOkay = true; 8870 return CXXConversionDecl::Create( 8871 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8872 TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 8873 ExplicitSpecifier, ConstexprKind, SourceLocation(), 8874 TrailingRequiresClause); 8875 8876 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 8877 if (TrailingRequiresClause) 8878 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(), 8879 diag::err_trailing_requires_clause_on_deduction_guide) 8880 << TrailingRequiresClause->getSourceRange(); 8881 SemaRef.CheckDeductionGuideDeclarator(D, R, SC); 8882 8883 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8884 ExplicitSpecifier, NameInfo, R, TInfo, 8885 D.getEndLoc()); 8886 } else if (DC->isRecord()) { 8887 // If the name of the function is the same as the name of the record, 8888 // then this must be an invalid constructor that has a return type. 8889 // (The parser checks for a return type and makes the declarator a 8890 // constructor if it has no return type). 8891 if (Name.getAsIdentifierInfo() && 8892 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 8893 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 8894 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8895 << SourceRange(D.getIdentifierLoc()); 8896 return nullptr; 8897 } 8898 8899 // This is a C++ method declaration. 8900 CXXMethodDecl *Ret = CXXMethodDecl::Create( 8901 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8902 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 8903 ConstexprKind, SourceLocation(), TrailingRequiresClause); 8904 IsVirtualOkay = !Ret->isStatic(); 8905 return Ret; 8906 } else { 8907 bool isFriend = 8908 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 8909 if (!isFriend && SemaRef.CurContext->isRecord()) 8910 return nullptr; 8911 8912 // Determine whether the function was written with a 8913 // prototype. This true when: 8914 // - we're in C++ (where every function has a prototype), 8915 return FunctionDecl::Create( 8916 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC, 8917 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 8918 true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause); 8919 } 8920 } 8921 8922 enum OpenCLParamType { 8923 ValidKernelParam, 8924 PtrPtrKernelParam, 8925 PtrKernelParam, 8926 InvalidAddrSpacePtrKernelParam, 8927 InvalidKernelParam, 8928 RecordKernelParam 8929 }; 8930 8931 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) { 8932 // Size dependent types are just typedefs to normal integer types 8933 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to 8934 // integers other than by their names. 8935 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"}; 8936 8937 // Remove typedefs one by one until we reach a typedef 8938 // for a size dependent type. 8939 QualType DesugaredTy = Ty; 8940 do { 8941 ArrayRef<StringRef> Names(SizeTypeNames); 8942 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString()); 8943 if (Names.end() != Match) 8944 return true; 8945 8946 Ty = DesugaredTy; 8947 DesugaredTy = Ty.getSingleStepDesugaredType(C); 8948 } while (DesugaredTy != Ty); 8949 8950 return false; 8951 } 8952 8953 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 8954 if (PT->isDependentType()) 8955 return InvalidKernelParam; 8956 8957 if (PT->isPointerType() || PT->isReferenceType()) { 8958 QualType PointeeType = PT->getPointeeType(); 8959 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 8960 PointeeType.getAddressSpace() == LangAS::opencl_private || 8961 PointeeType.getAddressSpace() == LangAS::Default) 8962 return InvalidAddrSpacePtrKernelParam; 8963 8964 if (PointeeType->isPointerType()) { 8965 // This is a pointer to pointer parameter. 8966 // Recursively check inner type. 8967 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType); 8968 if (ParamKind == InvalidAddrSpacePtrKernelParam || 8969 ParamKind == InvalidKernelParam) 8970 return ParamKind; 8971 8972 return PtrPtrKernelParam; 8973 } 8974 8975 // C++ for OpenCL v1.0 s2.4: 8976 // Moreover the types used in parameters of the kernel functions must be: 8977 // Standard layout types for pointer parameters. The same applies to 8978 // reference if an implementation supports them in kernel parameters. 8979 if (S.getLangOpts().OpenCLCPlusPlus && 8980 !S.getOpenCLOptions().isAvailableOption( 8981 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) && 8982 !PointeeType->isAtomicType() && !PointeeType->isVoidType() && 8983 !PointeeType->isStandardLayoutType()) 8984 return InvalidKernelParam; 8985 8986 return PtrKernelParam; 8987 } 8988 8989 // OpenCL v1.2 s6.9.k: 8990 // Arguments to kernel functions in a program cannot be declared with the 8991 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8992 // uintptr_t or a struct and/or union that contain fields declared to be one 8993 // of these built-in scalar types. 8994 if (isOpenCLSizeDependentType(S.getASTContext(), PT)) 8995 return InvalidKernelParam; 8996 8997 if (PT->isImageType()) 8998 return PtrKernelParam; 8999 9000 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) 9001 return InvalidKernelParam; 9002 9003 // OpenCL extension spec v1.2 s9.5: 9004 // This extension adds support for half scalar and vector types as built-in 9005 // types that can be used for arithmetic operations, conversions etc. 9006 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) && 9007 PT->isHalfType()) 9008 return InvalidKernelParam; 9009 9010 // Look into an array argument to check if it has a forbidden type. 9011 if (PT->isArrayType()) { 9012 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType(); 9013 // Call ourself to check an underlying type of an array. Since the 9014 // getPointeeOrArrayElementType returns an innermost type which is not an 9015 // array, this recursive call only happens once. 9016 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0)); 9017 } 9018 9019 // C++ for OpenCL v1.0 s2.4: 9020 // Moreover the types used in parameters of the kernel functions must be: 9021 // Trivial and standard-layout types C++17 [basic.types] (plain old data 9022 // types) for parameters passed by value; 9023 if (S.getLangOpts().OpenCLCPlusPlus && 9024 !S.getOpenCLOptions().isAvailableOption( 9025 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) && 9026 !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context)) 9027 return InvalidKernelParam; 9028 9029 if (PT->isRecordType()) 9030 return RecordKernelParam; 9031 9032 return ValidKernelParam; 9033 } 9034 9035 static void checkIsValidOpenCLKernelParameter( 9036 Sema &S, 9037 Declarator &D, 9038 ParmVarDecl *Param, 9039 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 9040 QualType PT = Param->getType(); 9041 9042 // Cache the valid types we encounter to avoid rechecking structs that are 9043 // used again 9044 if (ValidTypes.count(PT.getTypePtr())) 9045 return; 9046 9047 switch (getOpenCLKernelParameterType(S, PT)) { 9048 case PtrPtrKernelParam: 9049 // OpenCL v3.0 s6.11.a: 9050 // A kernel function argument cannot be declared as a pointer to a pointer 9051 // type. [...] This restriction only applies to OpenCL C 1.2 or below. 9052 if (S.getLangOpts().getOpenCLCompatibleVersion() <= 120) { 9053 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 9054 D.setInvalidType(); 9055 return; 9056 } 9057 9058 ValidTypes.insert(PT.getTypePtr()); 9059 return; 9060 9061 case InvalidAddrSpacePtrKernelParam: 9062 // OpenCL v1.0 s6.5: 9063 // __kernel function arguments declared to be a pointer of a type can point 9064 // to one of the following address spaces only : __global, __local or 9065 // __constant. 9066 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 9067 D.setInvalidType(); 9068 return; 9069 9070 // OpenCL v1.2 s6.9.k: 9071 // Arguments to kernel functions in a program cannot be declared with the 9072 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 9073 // uintptr_t or a struct and/or union that contain fields declared to be 9074 // one of these built-in scalar types. 9075 9076 case InvalidKernelParam: 9077 // OpenCL v1.2 s6.8 n: 9078 // A kernel function argument cannot be declared 9079 // of event_t type. 9080 // Do not diagnose half type since it is diagnosed as invalid argument 9081 // type for any function elsewhere. 9082 if (!PT->isHalfType()) { 9083 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 9084 9085 // Explain what typedefs are involved. 9086 const TypedefType *Typedef = nullptr; 9087 while ((Typedef = PT->getAs<TypedefType>())) { 9088 SourceLocation Loc = Typedef->getDecl()->getLocation(); 9089 // SourceLocation may be invalid for a built-in type. 9090 if (Loc.isValid()) 9091 S.Diag(Loc, diag::note_entity_declared_at) << PT; 9092 PT = Typedef->desugar(); 9093 } 9094 } 9095 9096 D.setInvalidType(); 9097 return; 9098 9099 case PtrKernelParam: 9100 case ValidKernelParam: 9101 ValidTypes.insert(PT.getTypePtr()); 9102 return; 9103 9104 case RecordKernelParam: 9105 break; 9106 } 9107 9108 // Track nested structs we will inspect 9109 SmallVector<const Decl *, 4> VisitStack; 9110 9111 // Track where we are in the nested structs. Items will migrate from 9112 // VisitStack to HistoryStack as we do the DFS for bad field. 9113 SmallVector<const FieldDecl *, 4> HistoryStack; 9114 HistoryStack.push_back(nullptr); 9115 9116 // At this point we already handled everything except of a RecordType or 9117 // an ArrayType of a RecordType. 9118 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type."); 9119 const RecordType *RecTy = 9120 PT->getPointeeOrArrayElementType()->getAs<RecordType>(); 9121 const RecordDecl *OrigRecDecl = RecTy->getDecl(); 9122 9123 VisitStack.push_back(RecTy->getDecl()); 9124 assert(VisitStack.back() && "First decl null?"); 9125 9126 do { 9127 const Decl *Next = VisitStack.pop_back_val(); 9128 if (!Next) { 9129 assert(!HistoryStack.empty()); 9130 // Found a marker, we have gone up a level 9131 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 9132 ValidTypes.insert(Hist->getType().getTypePtr()); 9133 9134 continue; 9135 } 9136 9137 // Adds everything except the original parameter declaration (which is not a 9138 // field itself) to the history stack. 9139 const RecordDecl *RD; 9140 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 9141 HistoryStack.push_back(Field); 9142 9143 QualType FieldTy = Field->getType(); 9144 // Other field types (known to be valid or invalid) are handled while we 9145 // walk around RecordDecl::fields(). 9146 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) && 9147 "Unexpected type."); 9148 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType(); 9149 9150 RD = FieldRecTy->castAs<RecordType>()->getDecl(); 9151 } else { 9152 RD = cast<RecordDecl>(Next); 9153 } 9154 9155 // Add a null marker so we know when we've gone back up a level 9156 VisitStack.push_back(nullptr); 9157 9158 for (const auto *FD : RD->fields()) { 9159 QualType QT = FD->getType(); 9160 9161 if (ValidTypes.count(QT.getTypePtr())) 9162 continue; 9163 9164 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 9165 if (ParamType == ValidKernelParam) 9166 continue; 9167 9168 if (ParamType == RecordKernelParam) { 9169 VisitStack.push_back(FD); 9170 continue; 9171 } 9172 9173 // OpenCL v1.2 s6.9.p: 9174 // Arguments to kernel functions that are declared to be a struct or union 9175 // do not allow OpenCL objects to be passed as elements of the struct or 9176 // union. 9177 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 9178 ParamType == InvalidAddrSpacePtrKernelParam) { 9179 S.Diag(Param->getLocation(), 9180 diag::err_record_with_pointers_kernel_param) 9181 << PT->isUnionType() 9182 << PT; 9183 } else { 9184 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 9185 } 9186 9187 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type) 9188 << OrigRecDecl->getDeclName(); 9189 9190 // We have an error, now let's go back up through history and show where 9191 // the offending field came from 9192 for (ArrayRef<const FieldDecl *>::const_iterator 9193 I = HistoryStack.begin() + 1, 9194 E = HistoryStack.end(); 9195 I != E; ++I) { 9196 const FieldDecl *OuterField = *I; 9197 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 9198 << OuterField->getType(); 9199 } 9200 9201 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 9202 << QT->isPointerType() 9203 << QT; 9204 D.setInvalidType(); 9205 return; 9206 } 9207 } while (!VisitStack.empty()); 9208 } 9209 9210 /// Find the DeclContext in which a tag is implicitly declared if we see an 9211 /// elaborated type specifier in the specified context, and lookup finds 9212 /// nothing. 9213 static DeclContext *getTagInjectionContext(DeclContext *DC) { 9214 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 9215 DC = DC->getParent(); 9216 return DC; 9217 } 9218 9219 /// Find the Scope in which a tag is implicitly declared if we see an 9220 /// elaborated type specifier in the specified context, and lookup finds 9221 /// nothing. 9222 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 9223 while (S->isClassScope() || 9224 (LangOpts.CPlusPlus && 9225 S->isFunctionPrototypeScope()) || 9226 ((S->getFlags() & Scope::DeclScope) == 0) || 9227 (S->getEntity() && S->getEntity()->isTransparentContext())) 9228 S = S->getParent(); 9229 return S; 9230 } 9231 9232 NamedDecl* 9233 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 9234 TypeSourceInfo *TInfo, LookupResult &Previous, 9235 MultiTemplateParamsArg TemplateParamListsRef, 9236 bool &AddToScope) { 9237 QualType R = TInfo->getType(); 9238 9239 assert(R->isFunctionType()); 9240 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr()) 9241 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call); 9242 9243 SmallVector<TemplateParameterList *, 4> TemplateParamLists; 9244 llvm::append_range(TemplateParamLists, TemplateParamListsRef); 9245 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) { 9246 if (!TemplateParamLists.empty() && 9247 Invented->getDepth() == TemplateParamLists.back()->getDepth()) 9248 TemplateParamLists.back() = Invented; 9249 else 9250 TemplateParamLists.push_back(Invented); 9251 } 9252 9253 // TODO: consider using NameInfo for diagnostic. 9254 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 9255 DeclarationName Name = NameInfo.getName(); 9256 StorageClass SC = getFunctionStorageClass(*this, D); 9257 9258 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 9259 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 9260 diag::err_invalid_thread) 9261 << DeclSpec::getSpecifierName(TSCS); 9262 9263 if (D.isFirstDeclarationOfMember()) 9264 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 9265 D.getIdentifierLoc()); 9266 9267 bool isFriend = false; 9268 FunctionTemplateDecl *FunctionTemplate = nullptr; 9269 bool isMemberSpecialization = false; 9270 bool isFunctionTemplateSpecialization = false; 9271 9272 bool isDependentClassScopeExplicitSpecialization = false; 9273 bool HasExplicitTemplateArgs = false; 9274 TemplateArgumentListInfo TemplateArgs; 9275 9276 bool isVirtualOkay = false; 9277 9278 DeclContext *OriginalDC = DC; 9279 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 9280 9281 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 9282 isVirtualOkay); 9283 if (!NewFD) return nullptr; 9284 9285 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 9286 NewFD->setTopLevelDeclInObjCContainer(); 9287 9288 // Set the lexical context. If this is a function-scope declaration, or has a 9289 // C++ scope specifier, or is the object of a friend declaration, the lexical 9290 // context will be different from the semantic context. 9291 NewFD->setLexicalDeclContext(CurContext); 9292 9293 if (IsLocalExternDecl) 9294 NewFD->setLocalExternDecl(); 9295 9296 if (getLangOpts().CPlusPlus) { 9297 bool isInline = D.getDeclSpec().isInlineSpecified(); 9298 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 9299 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier(); 9300 isFriend = D.getDeclSpec().isFriendSpecified(); 9301 if (isFriend && !isInline && D.isFunctionDefinition()) { 9302 // C++ [class.friend]p5 9303 // A function can be defined in a friend declaration of a 9304 // class . . . . Such a function is implicitly inline. 9305 NewFD->setImplicitlyInline(); 9306 } 9307 9308 // If this is a method defined in an __interface, and is not a constructor 9309 // or an overloaded operator, then set the pure flag (isVirtual will already 9310 // return true). 9311 if (const CXXRecordDecl *Parent = 9312 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 9313 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 9314 NewFD->setPure(true); 9315 9316 // C++ [class.union]p2 9317 // A union can have member functions, but not virtual functions. 9318 if (isVirtual && Parent->isUnion()) { 9319 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 9320 NewFD->setInvalidDecl(); 9321 } 9322 if ((Parent->isClass() || Parent->isStruct()) && 9323 Parent->hasAttr<SYCLSpecialClassAttr>() && 9324 NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() && 9325 NewFD->getName() == "__init" && D.isFunctionDefinition()) { 9326 if (auto *Def = Parent->getDefinition()) 9327 Def->setInitMethod(true); 9328 } 9329 } 9330 9331 SetNestedNameSpecifier(*this, NewFD, D); 9332 isMemberSpecialization = false; 9333 isFunctionTemplateSpecialization = false; 9334 if (D.isInvalidType()) 9335 NewFD->setInvalidDecl(); 9336 9337 // Match up the template parameter lists with the scope specifier, then 9338 // determine whether we have a template or a template specialization. 9339 bool Invalid = false; 9340 TemplateParameterList *TemplateParams = 9341 MatchTemplateParametersToScopeSpecifier( 9342 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 9343 D.getCXXScopeSpec(), 9344 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 9345 ? D.getName().TemplateId 9346 : nullptr, 9347 TemplateParamLists, isFriend, isMemberSpecialization, 9348 Invalid); 9349 if (TemplateParams) { 9350 // Check that we can declare a template here. 9351 if (CheckTemplateDeclScope(S, TemplateParams)) 9352 NewFD->setInvalidDecl(); 9353 9354 if (TemplateParams->size() > 0) { 9355 // This is a function template 9356 9357 // A destructor cannot be a template. 9358 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 9359 Diag(NewFD->getLocation(), diag::err_destructor_template); 9360 NewFD->setInvalidDecl(); 9361 } 9362 9363 // If we're adding a template to a dependent context, we may need to 9364 // rebuilding some of the types used within the template parameter list, 9365 // now that we know what the current instantiation is. 9366 if (DC->isDependentContext()) { 9367 ContextRAII SavedContext(*this, DC); 9368 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 9369 Invalid = true; 9370 } 9371 9372 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 9373 NewFD->getLocation(), 9374 Name, TemplateParams, 9375 NewFD); 9376 FunctionTemplate->setLexicalDeclContext(CurContext); 9377 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 9378 9379 // For source fidelity, store the other template param lists. 9380 if (TemplateParamLists.size() > 1) { 9381 NewFD->setTemplateParameterListsInfo(Context, 9382 ArrayRef<TemplateParameterList *>(TemplateParamLists) 9383 .drop_back(1)); 9384 } 9385 } else { 9386 // This is a function template specialization. 9387 isFunctionTemplateSpecialization = true; 9388 // For source fidelity, store all the template param lists. 9389 if (TemplateParamLists.size() > 0) 9390 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 9391 9392 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 9393 if (isFriend) { 9394 // We want to remove the "template<>", found here. 9395 SourceRange RemoveRange = TemplateParams->getSourceRange(); 9396 9397 // If we remove the template<> and the name is not a 9398 // template-id, we're actually silently creating a problem: 9399 // the friend declaration will refer to an untemplated decl, 9400 // and clearly the user wants a template specialization. So 9401 // we need to insert '<>' after the name. 9402 SourceLocation InsertLoc; 9403 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 9404 InsertLoc = D.getName().getSourceRange().getEnd(); 9405 InsertLoc = getLocForEndOfToken(InsertLoc); 9406 } 9407 9408 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 9409 << Name << RemoveRange 9410 << FixItHint::CreateRemoval(RemoveRange) 9411 << FixItHint::CreateInsertion(InsertLoc, "<>"); 9412 Invalid = true; 9413 } 9414 } 9415 } else { 9416 // Check that we can declare a template here. 9417 if (!TemplateParamLists.empty() && isMemberSpecialization && 9418 CheckTemplateDeclScope(S, TemplateParamLists.back())) 9419 NewFD->setInvalidDecl(); 9420 9421 // All template param lists were matched against the scope specifier: 9422 // this is NOT (an explicit specialization of) a template. 9423 if (TemplateParamLists.size() > 0) 9424 // For source fidelity, store all the template param lists. 9425 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 9426 } 9427 9428 if (Invalid) { 9429 NewFD->setInvalidDecl(); 9430 if (FunctionTemplate) 9431 FunctionTemplate->setInvalidDecl(); 9432 } 9433 9434 // C++ [dcl.fct.spec]p5: 9435 // The virtual specifier shall only be used in declarations of 9436 // nonstatic class member functions that appear within a 9437 // member-specification of a class declaration; see 10.3. 9438 // 9439 if (isVirtual && !NewFD->isInvalidDecl()) { 9440 if (!isVirtualOkay) { 9441 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9442 diag::err_virtual_non_function); 9443 } else if (!CurContext->isRecord()) { 9444 // 'virtual' was specified outside of the class. 9445 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9446 diag::err_virtual_out_of_class) 9447 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 9448 } else if (NewFD->getDescribedFunctionTemplate()) { 9449 // C++ [temp.mem]p3: 9450 // A member function template shall not be virtual. 9451 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9452 diag::err_virtual_member_function_template) 9453 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 9454 } else { 9455 // Okay: Add virtual to the method. 9456 NewFD->setVirtualAsWritten(true); 9457 } 9458 9459 if (getLangOpts().CPlusPlus14 && 9460 NewFD->getReturnType()->isUndeducedType()) 9461 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 9462 } 9463 9464 if (getLangOpts().CPlusPlus14 && 9465 (NewFD->isDependentContext() || 9466 (isFriend && CurContext->isDependentContext())) && 9467 NewFD->getReturnType()->isUndeducedType()) { 9468 // If the function template is referenced directly (for instance, as a 9469 // member of the current instantiation), pretend it has a dependent type. 9470 // This is not really justified by the standard, but is the only sane 9471 // thing to do. 9472 // FIXME: For a friend function, we have not marked the function as being 9473 // a friend yet, so 'isDependentContext' on the FD doesn't work. 9474 const FunctionProtoType *FPT = 9475 NewFD->getType()->castAs<FunctionProtoType>(); 9476 QualType Result = SubstAutoTypeDependent(FPT->getReturnType()); 9477 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 9478 FPT->getExtProtoInfo())); 9479 } 9480 9481 // C++ [dcl.fct.spec]p3: 9482 // The inline specifier shall not appear on a block scope function 9483 // declaration. 9484 if (isInline && !NewFD->isInvalidDecl()) { 9485 if (CurContext->isFunctionOrMethod()) { 9486 // 'inline' is not allowed on block scope function declaration. 9487 Diag(D.getDeclSpec().getInlineSpecLoc(), 9488 diag::err_inline_declaration_block_scope) << Name 9489 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 9490 } 9491 } 9492 9493 // C++ [dcl.fct.spec]p6: 9494 // The explicit specifier shall be used only in the declaration of a 9495 // constructor or conversion function within its class definition; 9496 // see 12.3.1 and 12.3.2. 9497 if (hasExplicit && !NewFD->isInvalidDecl() && 9498 !isa<CXXDeductionGuideDecl>(NewFD)) { 9499 if (!CurContext->isRecord()) { 9500 // 'explicit' was specified outside of the class. 9501 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9502 diag::err_explicit_out_of_class) 9503 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9504 } else if (!isa<CXXConstructorDecl>(NewFD) && 9505 !isa<CXXConversionDecl>(NewFD)) { 9506 // 'explicit' was specified on a function that wasn't a constructor 9507 // or conversion function. 9508 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9509 diag::err_explicit_non_ctor_or_conv_function) 9510 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9511 } 9512 } 9513 9514 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 9515 if (ConstexprKind != ConstexprSpecKind::Unspecified) { 9516 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 9517 // are implicitly inline. 9518 NewFD->setImplicitlyInline(); 9519 9520 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 9521 // be either constructors or to return a literal type. Therefore, 9522 // destructors cannot be declared constexpr. 9523 if (isa<CXXDestructorDecl>(NewFD) && 9524 (!getLangOpts().CPlusPlus20 || 9525 ConstexprKind == ConstexprSpecKind::Consteval)) { 9526 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor) 9527 << static_cast<int>(ConstexprKind); 9528 NewFD->setConstexprKind(getLangOpts().CPlusPlus20 9529 ? ConstexprSpecKind::Unspecified 9530 : ConstexprSpecKind::Constexpr); 9531 } 9532 // C++20 [dcl.constexpr]p2: An allocation function, or a 9533 // deallocation function shall not be declared with the consteval 9534 // specifier. 9535 if (ConstexprKind == ConstexprSpecKind::Consteval && 9536 (NewFD->getOverloadedOperator() == OO_New || 9537 NewFD->getOverloadedOperator() == OO_Array_New || 9538 NewFD->getOverloadedOperator() == OO_Delete || 9539 NewFD->getOverloadedOperator() == OO_Array_Delete)) { 9540 Diag(D.getDeclSpec().getConstexprSpecLoc(), 9541 diag::err_invalid_consteval_decl_kind) 9542 << NewFD; 9543 NewFD->setConstexprKind(ConstexprSpecKind::Constexpr); 9544 } 9545 } 9546 9547 // If __module_private__ was specified, mark the function accordingly. 9548 if (D.getDeclSpec().isModulePrivateSpecified()) { 9549 if (isFunctionTemplateSpecialization) { 9550 SourceLocation ModulePrivateLoc 9551 = D.getDeclSpec().getModulePrivateSpecLoc(); 9552 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 9553 << 0 9554 << FixItHint::CreateRemoval(ModulePrivateLoc); 9555 } else { 9556 NewFD->setModulePrivate(); 9557 if (FunctionTemplate) 9558 FunctionTemplate->setModulePrivate(); 9559 } 9560 } 9561 9562 if (isFriend) { 9563 if (FunctionTemplate) { 9564 FunctionTemplate->setObjectOfFriendDecl(); 9565 FunctionTemplate->setAccess(AS_public); 9566 } 9567 NewFD->setObjectOfFriendDecl(); 9568 NewFD->setAccess(AS_public); 9569 } 9570 9571 // If a function is defined as defaulted or deleted, mark it as such now. 9572 // We'll do the relevant checks on defaulted / deleted functions later. 9573 switch (D.getFunctionDefinitionKind()) { 9574 case FunctionDefinitionKind::Declaration: 9575 case FunctionDefinitionKind::Definition: 9576 break; 9577 9578 case FunctionDefinitionKind::Defaulted: 9579 NewFD->setDefaulted(); 9580 break; 9581 9582 case FunctionDefinitionKind::Deleted: 9583 NewFD->setDeletedAsWritten(); 9584 break; 9585 } 9586 9587 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 9588 D.isFunctionDefinition()) { 9589 // C++ [class.mfct]p2: 9590 // A member function may be defined (8.4) in its class definition, in 9591 // which case it is an inline member function (7.1.2) 9592 NewFD->setImplicitlyInline(); 9593 } 9594 9595 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 9596 !CurContext->isRecord()) { 9597 // C++ [class.static]p1: 9598 // A data or function member of a class may be declared static 9599 // in a class definition, in which case it is a static member of 9600 // the class. 9601 9602 // Complain about the 'static' specifier if it's on an out-of-line 9603 // member function definition. 9604 9605 // MSVC permits the use of a 'static' storage specifier on an out-of-line 9606 // member function template declaration and class member template 9607 // declaration (MSVC versions before 2015), warn about this. 9608 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 9609 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 9610 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) || 9611 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate())) 9612 ? diag::ext_static_out_of_line : diag::err_static_out_of_line) 9613 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 9614 } 9615 9616 // C++11 [except.spec]p15: 9617 // A deallocation function with no exception-specification is treated 9618 // as if it were specified with noexcept(true). 9619 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 9620 if ((Name.getCXXOverloadedOperator() == OO_Delete || 9621 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 9622 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 9623 NewFD->setType(Context.getFunctionType( 9624 FPT->getReturnType(), FPT->getParamTypes(), 9625 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 9626 } 9627 9628 // Filter out previous declarations that don't match the scope. 9629 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 9630 D.getCXXScopeSpec().isNotEmpty() || 9631 isMemberSpecialization || 9632 isFunctionTemplateSpecialization); 9633 9634 // Handle GNU asm-label extension (encoded as an attribute). 9635 if (Expr *E = (Expr*) D.getAsmLabel()) { 9636 // The parser guarantees this is a string. 9637 StringLiteral *SE = cast<StringLiteral>(E); 9638 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(), 9639 /*IsLiteralLabel=*/true, 9640 SE->getStrTokenLoc(0))); 9641 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 9642 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 9643 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 9644 if (I != ExtnameUndeclaredIdentifiers.end()) { 9645 if (isDeclExternC(NewFD)) { 9646 NewFD->addAttr(I->second); 9647 ExtnameUndeclaredIdentifiers.erase(I); 9648 } else 9649 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 9650 << /*Variable*/0 << NewFD; 9651 } 9652 } 9653 9654 // Copy the parameter declarations from the declarator D to the function 9655 // declaration NewFD, if they are available. First scavenge them into Params. 9656 SmallVector<ParmVarDecl*, 16> Params; 9657 unsigned FTIIdx; 9658 if (D.isFunctionDeclarator(FTIIdx)) { 9659 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 9660 9661 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 9662 // function that takes no arguments, not a function that takes a 9663 // single void argument. 9664 // We let through "const void" here because Sema::GetTypeForDeclarator 9665 // already checks for that case. 9666 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 9667 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 9668 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 9669 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 9670 Param->setDeclContext(NewFD); 9671 Params.push_back(Param); 9672 9673 if (Param->isInvalidDecl()) 9674 NewFD->setInvalidDecl(); 9675 } 9676 } 9677 9678 if (!getLangOpts().CPlusPlus) { 9679 // In C, find all the tag declarations from the prototype and move them 9680 // into the function DeclContext. Remove them from the surrounding tag 9681 // injection context of the function, which is typically but not always 9682 // the TU. 9683 DeclContext *PrototypeTagContext = 9684 getTagInjectionContext(NewFD->getLexicalDeclContext()); 9685 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 9686 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 9687 9688 // We don't want to reparent enumerators. Look at their parent enum 9689 // instead. 9690 if (!TD) { 9691 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 9692 TD = cast<EnumDecl>(ECD->getDeclContext()); 9693 } 9694 if (!TD) 9695 continue; 9696 DeclContext *TagDC = TD->getLexicalDeclContext(); 9697 if (!TagDC->containsDecl(TD)) 9698 continue; 9699 TagDC->removeDecl(TD); 9700 TD->setDeclContext(NewFD); 9701 NewFD->addDecl(TD); 9702 9703 // Preserve the lexical DeclContext if it is not the surrounding tag 9704 // injection context of the FD. In this example, the semantic context of 9705 // E will be f and the lexical context will be S, while both the 9706 // semantic and lexical contexts of S will be f: 9707 // void f(struct S { enum E { a } f; } s); 9708 if (TagDC != PrototypeTagContext) 9709 TD->setLexicalDeclContext(TagDC); 9710 } 9711 } 9712 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 9713 // When we're declaring a function with a typedef, typeof, etc as in the 9714 // following example, we'll need to synthesize (unnamed) 9715 // parameters for use in the declaration. 9716 // 9717 // @code 9718 // typedef void fn(int); 9719 // fn f; 9720 // @endcode 9721 9722 // Synthesize a parameter for each argument type. 9723 for (const auto &AI : FT->param_types()) { 9724 ParmVarDecl *Param = 9725 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 9726 Param->setScopeInfo(0, Params.size()); 9727 Params.push_back(Param); 9728 } 9729 } else { 9730 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 9731 "Should not need args for typedef of non-prototype fn"); 9732 } 9733 9734 // Finally, we know we have the right number of parameters, install them. 9735 NewFD->setParams(Params); 9736 9737 if (D.getDeclSpec().isNoreturnSpecified()) 9738 NewFD->addAttr(C11NoReturnAttr::Create(Context, 9739 D.getDeclSpec().getNoreturnSpecLoc(), 9740 AttributeCommonInfo::AS_Keyword)); 9741 9742 // Functions returning a variably modified type violate C99 6.7.5.2p2 9743 // because all functions have linkage. 9744 if (!NewFD->isInvalidDecl() && 9745 NewFD->getReturnType()->isVariablyModifiedType()) { 9746 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 9747 NewFD->setInvalidDecl(); 9748 } 9749 9750 // Apply an implicit SectionAttr if '#pragma clang section text' is active 9751 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && 9752 !NewFD->hasAttr<SectionAttr>()) 9753 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit( 9754 Context, PragmaClangTextSection.SectionName, 9755 PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma)); 9756 9757 // Apply an implicit SectionAttr if #pragma code_seg is active. 9758 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 9759 !NewFD->hasAttr<SectionAttr>()) { 9760 NewFD->addAttr(SectionAttr::CreateImplicit( 9761 Context, CodeSegStack.CurrentValue->getString(), 9762 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 9763 SectionAttr::Declspec_allocate)); 9764 if (UnifySection(CodeSegStack.CurrentValue->getString(), 9765 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 9766 ASTContext::PSF_Read, 9767 NewFD)) 9768 NewFD->dropAttr<SectionAttr>(); 9769 } 9770 9771 // Apply an implicit CodeSegAttr from class declspec or 9772 // apply an implicit SectionAttr from #pragma code_seg if active. 9773 if (!NewFD->hasAttr<CodeSegAttr>()) { 9774 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD, 9775 D.isFunctionDefinition())) { 9776 NewFD->addAttr(SAttr); 9777 } 9778 } 9779 9780 // Handle attributes. 9781 ProcessDeclAttributes(S, NewFD, D); 9782 9783 if (getLangOpts().OpenCL) { 9784 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 9785 // type declaration will generate a compilation error. 9786 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); 9787 if (AddressSpace != LangAS::Default) { 9788 Diag(NewFD->getLocation(), 9789 diag::err_opencl_return_value_with_address_space); 9790 NewFD->setInvalidDecl(); 9791 } 9792 } 9793 9794 if (!getLangOpts().CPlusPlus) { 9795 // Perform semantic checking on the function declaration. 9796 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9797 CheckMain(NewFD, D.getDeclSpec()); 9798 9799 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9800 CheckMSVCRTEntryPoint(NewFD); 9801 9802 if (!NewFD->isInvalidDecl()) 9803 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9804 isMemberSpecialization)); 9805 else if (!Previous.empty()) 9806 // Recover gracefully from an invalid redeclaration. 9807 D.setRedeclaration(true); 9808 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9809 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9810 "previous declaration set still overloaded"); 9811 9812 // Diagnose no-prototype function declarations with calling conventions that 9813 // don't support variadic calls. Only do this in C and do it after merging 9814 // possibly prototyped redeclarations. 9815 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 9816 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 9817 CallingConv CC = FT->getExtInfo().getCC(); 9818 if (!supportsVariadicCall(CC)) { 9819 // Windows system headers sometimes accidentally use stdcall without 9820 // (void) parameters, so we relax this to a warning. 9821 int DiagID = 9822 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 9823 Diag(NewFD->getLocation(), DiagID) 9824 << FunctionType::getNameForCallConv(CC); 9825 } 9826 } 9827 9828 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() || 9829 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion()) 9830 checkNonTrivialCUnion(NewFD->getReturnType(), 9831 NewFD->getReturnTypeSourceRange().getBegin(), 9832 NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy); 9833 } else { 9834 // C++11 [replacement.functions]p3: 9835 // The program's definitions shall not be specified as inline. 9836 // 9837 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 9838 // 9839 // Suppress the diagnostic if the function is __attribute__((used)), since 9840 // that forces an external definition to be emitted. 9841 if (D.getDeclSpec().isInlineSpecified() && 9842 NewFD->isReplaceableGlobalAllocationFunction() && 9843 !NewFD->hasAttr<UsedAttr>()) 9844 Diag(D.getDeclSpec().getInlineSpecLoc(), 9845 diag::ext_operator_new_delete_declared_inline) 9846 << NewFD->getDeclName(); 9847 9848 // If the declarator is a template-id, translate the parser's template 9849 // argument list into our AST format. 9850 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 9851 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 9852 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 9853 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 9854 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 9855 TemplateId->NumArgs); 9856 translateTemplateArguments(TemplateArgsPtr, 9857 TemplateArgs); 9858 9859 HasExplicitTemplateArgs = true; 9860 9861 if (NewFD->isInvalidDecl()) { 9862 HasExplicitTemplateArgs = false; 9863 } else if (FunctionTemplate) { 9864 // Function template with explicit template arguments. 9865 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 9866 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 9867 9868 HasExplicitTemplateArgs = false; 9869 } else { 9870 assert((isFunctionTemplateSpecialization || 9871 D.getDeclSpec().isFriendSpecified()) && 9872 "should have a 'template<>' for this decl"); 9873 // "friend void foo<>(int);" is an implicit specialization decl. 9874 isFunctionTemplateSpecialization = true; 9875 } 9876 } else if (isFriend && isFunctionTemplateSpecialization) { 9877 // This combination is only possible in a recovery case; the user 9878 // wrote something like: 9879 // template <> friend void foo(int); 9880 // which we're recovering from as if the user had written: 9881 // friend void foo<>(int); 9882 // Go ahead and fake up a template id. 9883 HasExplicitTemplateArgs = true; 9884 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 9885 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 9886 } 9887 9888 // We do not add HD attributes to specializations here because 9889 // they may have different constexpr-ness compared to their 9890 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 9891 // may end up with different effective targets. Instead, a 9892 // specialization inherits its target attributes from its template 9893 // in the CheckFunctionTemplateSpecialization() call below. 9894 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization) 9895 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 9896 9897 // If it's a friend (and only if it's a friend), it's possible 9898 // that either the specialized function type or the specialized 9899 // template is dependent, and therefore matching will fail. In 9900 // this case, don't check the specialization yet. 9901 if (isFunctionTemplateSpecialization && isFriend && 9902 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 9903 TemplateSpecializationType::anyInstantiationDependentTemplateArguments( 9904 TemplateArgs.arguments()))) { 9905 assert(HasExplicitTemplateArgs && 9906 "friend function specialization without template args"); 9907 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 9908 Previous)) 9909 NewFD->setInvalidDecl(); 9910 } else if (isFunctionTemplateSpecialization) { 9911 if (CurContext->isDependentContext() && CurContext->isRecord() 9912 && !isFriend) { 9913 isDependentClassScopeExplicitSpecialization = true; 9914 } else if (!NewFD->isInvalidDecl() && 9915 CheckFunctionTemplateSpecialization( 9916 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), 9917 Previous)) 9918 NewFD->setInvalidDecl(); 9919 9920 // C++ [dcl.stc]p1: 9921 // A storage-class-specifier shall not be specified in an explicit 9922 // specialization (14.7.3) 9923 FunctionTemplateSpecializationInfo *Info = 9924 NewFD->getTemplateSpecializationInfo(); 9925 if (Info && SC != SC_None) { 9926 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 9927 Diag(NewFD->getLocation(), 9928 diag::err_explicit_specialization_inconsistent_storage_class) 9929 << SC 9930 << FixItHint::CreateRemoval( 9931 D.getDeclSpec().getStorageClassSpecLoc()); 9932 9933 else 9934 Diag(NewFD->getLocation(), 9935 diag::ext_explicit_specialization_storage_class) 9936 << FixItHint::CreateRemoval( 9937 D.getDeclSpec().getStorageClassSpecLoc()); 9938 } 9939 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 9940 if (CheckMemberSpecialization(NewFD, Previous)) 9941 NewFD->setInvalidDecl(); 9942 } 9943 9944 // Perform semantic checking on the function declaration. 9945 if (!isDependentClassScopeExplicitSpecialization) { 9946 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9947 CheckMain(NewFD, D.getDeclSpec()); 9948 9949 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9950 CheckMSVCRTEntryPoint(NewFD); 9951 9952 if (!NewFD->isInvalidDecl()) 9953 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9954 isMemberSpecialization)); 9955 else if (!Previous.empty()) 9956 // Recover gracefully from an invalid redeclaration. 9957 D.setRedeclaration(true); 9958 } 9959 9960 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9961 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9962 "previous declaration set still overloaded"); 9963 9964 NamedDecl *PrincipalDecl = (FunctionTemplate 9965 ? cast<NamedDecl>(FunctionTemplate) 9966 : NewFD); 9967 9968 if (isFriend && NewFD->getPreviousDecl()) { 9969 AccessSpecifier Access = AS_public; 9970 if (!NewFD->isInvalidDecl()) 9971 Access = NewFD->getPreviousDecl()->getAccess(); 9972 9973 NewFD->setAccess(Access); 9974 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 9975 } 9976 9977 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 9978 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 9979 PrincipalDecl->setNonMemberOperator(); 9980 9981 // If we have a function template, check the template parameter 9982 // list. This will check and merge default template arguments. 9983 if (FunctionTemplate) { 9984 FunctionTemplateDecl *PrevTemplate = 9985 FunctionTemplate->getPreviousDecl(); 9986 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 9987 PrevTemplate ? PrevTemplate->getTemplateParameters() 9988 : nullptr, 9989 D.getDeclSpec().isFriendSpecified() 9990 ? (D.isFunctionDefinition() 9991 ? TPC_FriendFunctionTemplateDefinition 9992 : TPC_FriendFunctionTemplate) 9993 : (D.getCXXScopeSpec().isSet() && 9994 DC && DC->isRecord() && 9995 DC->isDependentContext()) 9996 ? TPC_ClassTemplateMember 9997 : TPC_FunctionTemplate); 9998 } 9999 10000 if (NewFD->isInvalidDecl()) { 10001 // Ignore all the rest of this. 10002 } else if (!D.isRedeclaration()) { 10003 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 10004 AddToScope }; 10005 // Fake up an access specifier if it's supposed to be a class member. 10006 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 10007 NewFD->setAccess(AS_public); 10008 10009 // Qualified decls generally require a previous declaration. 10010 if (D.getCXXScopeSpec().isSet()) { 10011 // ...with the major exception of templated-scope or 10012 // dependent-scope friend declarations. 10013 10014 // TODO: we currently also suppress this check in dependent 10015 // contexts because (1) the parameter depth will be off when 10016 // matching friend templates and (2) we might actually be 10017 // selecting a friend based on a dependent factor. But there 10018 // are situations where these conditions don't apply and we 10019 // can actually do this check immediately. 10020 // 10021 // Unless the scope is dependent, it's always an error if qualified 10022 // redeclaration lookup found nothing at all. Diagnose that now; 10023 // nothing will diagnose that error later. 10024 if (isFriend && 10025 (D.getCXXScopeSpec().getScopeRep()->isDependent() || 10026 (!Previous.empty() && CurContext->isDependentContext()))) { 10027 // ignore these 10028 } else if (NewFD->isCPUDispatchMultiVersion() || 10029 NewFD->isCPUSpecificMultiVersion()) { 10030 // ignore this, we allow the redeclaration behavior here to create new 10031 // versions of the function. 10032 } else { 10033 // The user tried to provide an out-of-line definition for a 10034 // function that is a member of a class or namespace, but there 10035 // was no such member function declared (C++ [class.mfct]p2, 10036 // C++ [namespace.memdef]p2). For example: 10037 // 10038 // class X { 10039 // void f() const; 10040 // }; 10041 // 10042 // void X::f() { } // ill-formed 10043 // 10044 // Complain about this problem, and attempt to suggest close 10045 // matches (e.g., those that differ only in cv-qualifiers and 10046 // whether the parameter types are references). 10047 10048 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 10049 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 10050 AddToScope = ExtraArgs.AddToScope; 10051 return Result; 10052 } 10053 } 10054 10055 // Unqualified local friend declarations are required to resolve 10056 // to something. 10057 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 10058 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 10059 *this, Previous, NewFD, ExtraArgs, true, S)) { 10060 AddToScope = ExtraArgs.AddToScope; 10061 return Result; 10062 } 10063 } 10064 } else if (!D.isFunctionDefinition() && 10065 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 10066 !isFriend && !isFunctionTemplateSpecialization && 10067 !isMemberSpecialization) { 10068 // An out-of-line member function declaration must also be a 10069 // definition (C++ [class.mfct]p2). 10070 // Note that this is not the case for explicit specializations of 10071 // function templates or member functions of class templates, per 10072 // C++ [temp.expl.spec]p2. We also allow these declarations as an 10073 // extension for compatibility with old SWIG code which likes to 10074 // generate them. 10075 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 10076 << D.getCXXScopeSpec().getRange(); 10077 } 10078 } 10079 10080 // If this is the first declaration of a library builtin function, add 10081 // attributes as appropriate. 10082 if (!D.isRedeclaration() && 10083 NewFD->getDeclContext()->getRedeclContext()->isFileContext()) { 10084 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) { 10085 if (unsigned BuiltinID = II->getBuiltinID()) { 10086 if (NewFD->getLanguageLinkage() == CLanguageLinkage) { 10087 // Validate the type matches unless this builtin is specified as 10088 // matching regardless of its declared type. 10089 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) { 10090 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 10091 } else { 10092 ASTContext::GetBuiltinTypeError Error; 10093 LookupNecessaryTypesForBuiltin(S, BuiltinID); 10094 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error); 10095 10096 if (!Error && !BuiltinType.isNull() && 10097 Context.hasSameFunctionTypeIgnoringExceptionSpec( 10098 NewFD->getType(), BuiltinType)) 10099 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 10100 } 10101 } else if (BuiltinID == Builtin::BI__GetExceptionInfo && 10102 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 10103 // FIXME: We should consider this a builtin only in the std namespace. 10104 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 10105 } 10106 } 10107 } 10108 } 10109 10110 ProcessPragmaWeak(S, NewFD); 10111 checkAttributesAfterMerging(*this, *NewFD); 10112 10113 AddKnownFunctionAttributes(NewFD); 10114 10115 if (NewFD->hasAttr<OverloadableAttr>() && 10116 !NewFD->getType()->getAs<FunctionProtoType>()) { 10117 Diag(NewFD->getLocation(), 10118 diag::err_attribute_overloadable_no_prototype) 10119 << NewFD; 10120 10121 // Turn this into a variadic function with no parameters. 10122 const auto *FT = NewFD->getType()->castAs<FunctionType>(); 10123 FunctionProtoType::ExtProtoInfo EPI( 10124 Context.getDefaultCallingConvention(true, false)); 10125 EPI.Variadic = true; 10126 EPI.ExtInfo = FT->getExtInfo(); 10127 10128 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 10129 NewFD->setType(R); 10130 } 10131 10132 // If there's a #pragma GCC visibility in scope, and this isn't a class 10133 // member, set the visibility of this function. 10134 if (!DC->isRecord() && NewFD->isExternallyVisible()) 10135 AddPushedVisibilityAttribute(NewFD); 10136 10137 // If there's a #pragma clang arc_cf_code_audited in scope, consider 10138 // marking the function. 10139 AddCFAuditedAttribute(NewFD); 10140 10141 // If this is a function definition, check if we have to apply optnone due to 10142 // a pragma. 10143 if(D.isFunctionDefinition()) 10144 AddRangeBasedOptnone(NewFD); 10145 10146 // If this is the first declaration of an extern C variable, update 10147 // the map of such variables. 10148 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 10149 isIncompleteDeclExternC(*this, NewFD)) 10150 RegisterLocallyScopedExternCDecl(NewFD, S); 10151 10152 // Set this FunctionDecl's range up to the right paren. 10153 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 10154 10155 if (D.isRedeclaration() && !Previous.empty()) { 10156 NamedDecl *Prev = Previous.getRepresentativeDecl(); 10157 checkDLLAttributeRedeclaration(*this, Prev, NewFD, 10158 isMemberSpecialization || 10159 isFunctionTemplateSpecialization, 10160 D.isFunctionDefinition()); 10161 } 10162 10163 if (getLangOpts().CUDA) { 10164 IdentifierInfo *II = NewFD->getIdentifier(); 10165 if (II && II->isStr(getCudaConfigureFuncName()) && 10166 !NewFD->isInvalidDecl() && 10167 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 10168 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType()) 10169 Diag(NewFD->getLocation(), diag::err_config_scalar_return) 10170 << getCudaConfigureFuncName(); 10171 Context.setcudaConfigureCallDecl(NewFD); 10172 } 10173 10174 // Variadic functions, other than a *declaration* of printf, are not allowed 10175 // in device-side CUDA code, unless someone passed 10176 // -fcuda-allow-variadic-functions. 10177 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 10178 (NewFD->hasAttr<CUDADeviceAttr>() || 10179 NewFD->hasAttr<CUDAGlobalAttr>()) && 10180 !(II && II->isStr("printf") && NewFD->isExternC() && 10181 !D.isFunctionDefinition())) { 10182 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 10183 } 10184 } 10185 10186 MarkUnusedFileScopedDecl(NewFD); 10187 10188 10189 10190 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) { 10191 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 10192 if (SC == SC_Static) { 10193 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 10194 D.setInvalidType(); 10195 } 10196 10197 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 10198 if (!NewFD->getReturnType()->isVoidType()) { 10199 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 10200 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 10201 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 10202 : FixItHint()); 10203 D.setInvalidType(); 10204 } 10205 10206 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 10207 for (auto Param : NewFD->parameters()) 10208 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 10209 10210 if (getLangOpts().OpenCLCPlusPlus) { 10211 if (DC->isRecord()) { 10212 Diag(D.getIdentifierLoc(), diag::err_method_kernel); 10213 D.setInvalidType(); 10214 } 10215 if (FunctionTemplate) { 10216 Diag(D.getIdentifierLoc(), diag::err_template_kernel); 10217 D.setInvalidType(); 10218 } 10219 } 10220 } 10221 10222 if (getLangOpts().CPlusPlus) { 10223 if (FunctionTemplate) { 10224 if (NewFD->isInvalidDecl()) 10225 FunctionTemplate->setInvalidDecl(); 10226 return FunctionTemplate; 10227 } 10228 10229 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 10230 CompleteMemberSpecialization(NewFD, Previous); 10231 } 10232 10233 for (const ParmVarDecl *Param : NewFD->parameters()) { 10234 QualType PT = Param->getType(); 10235 10236 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 10237 // types. 10238 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) { 10239 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 10240 QualType ElemTy = PipeTy->getElementType(); 10241 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 10242 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 10243 D.setInvalidType(); 10244 } 10245 } 10246 } 10247 } 10248 10249 // Here we have an function template explicit specialization at class scope. 10250 // The actual specialization will be postponed to template instatiation 10251 // time via the ClassScopeFunctionSpecializationDecl node. 10252 if (isDependentClassScopeExplicitSpecialization) { 10253 ClassScopeFunctionSpecializationDecl *NewSpec = 10254 ClassScopeFunctionSpecializationDecl::Create( 10255 Context, CurContext, NewFD->getLocation(), 10256 cast<CXXMethodDecl>(NewFD), 10257 HasExplicitTemplateArgs, TemplateArgs); 10258 CurContext->addDecl(NewSpec); 10259 AddToScope = false; 10260 } 10261 10262 // Diagnose availability attributes. Availability cannot be used on functions 10263 // that are run during load/unload. 10264 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { 10265 if (NewFD->hasAttr<ConstructorAttr>()) { 10266 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 10267 << 1; 10268 NewFD->dropAttr<AvailabilityAttr>(); 10269 } 10270 if (NewFD->hasAttr<DestructorAttr>()) { 10271 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 10272 << 2; 10273 NewFD->dropAttr<AvailabilityAttr>(); 10274 } 10275 } 10276 10277 // Diagnose no_builtin attribute on function declaration that are not a 10278 // definition. 10279 // FIXME: We should really be doing this in 10280 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to 10281 // the FunctionDecl and at this point of the code 10282 // FunctionDecl::isThisDeclarationADefinition() which always returns `false` 10283 // because Sema::ActOnStartOfFunctionDef has not been called yet. 10284 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>()) 10285 switch (D.getFunctionDefinitionKind()) { 10286 case FunctionDefinitionKind::Defaulted: 10287 case FunctionDefinitionKind::Deleted: 10288 Diag(NBA->getLocation(), 10289 diag::err_attribute_no_builtin_on_defaulted_deleted_function) 10290 << NBA->getSpelling(); 10291 break; 10292 case FunctionDefinitionKind::Declaration: 10293 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition) 10294 << NBA->getSpelling(); 10295 break; 10296 case FunctionDefinitionKind::Definition: 10297 break; 10298 } 10299 10300 return NewFD; 10301 } 10302 10303 /// Return a CodeSegAttr from a containing class. The Microsoft docs say 10304 /// when __declspec(code_seg) "is applied to a class, all member functions of 10305 /// the class and nested classes -- this includes compiler-generated special 10306 /// member functions -- are put in the specified segment." 10307 /// The actual behavior is a little more complicated. The Microsoft compiler 10308 /// won't check outer classes if there is an active value from #pragma code_seg. 10309 /// The CodeSeg is always applied from the direct parent but only from outer 10310 /// classes when the #pragma code_seg stack is empty. See: 10311 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer 10312 /// available since MS has removed the page. 10313 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) { 10314 const auto *Method = dyn_cast<CXXMethodDecl>(FD); 10315 if (!Method) 10316 return nullptr; 10317 const CXXRecordDecl *Parent = Method->getParent(); 10318 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 10319 Attr *NewAttr = SAttr->clone(S.getASTContext()); 10320 NewAttr->setImplicit(true); 10321 return NewAttr; 10322 } 10323 10324 // The Microsoft compiler won't check outer classes for the CodeSeg 10325 // when the #pragma code_seg stack is active. 10326 if (S.CodeSegStack.CurrentValue) 10327 return nullptr; 10328 10329 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) { 10330 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 10331 Attr *NewAttr = SAttr->clone(S.getASTContext()); 10332 NewAttr->setImplicit(true); 10333 return NewAttr; 10334 } 10335 } 10336 return nullptr; 10337 } 10338 10339 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a 10340 /// containing class. Otherwise it will return implicit SectionAttr if the 10341 /// function is a definition and there is an active value on CodeSegStack 10342 /// (from the current #pragma code-seg value). 10343 /// 10344 /// \param FD Function being declared. 10345 /// \param IsDefinition Whether it is a definition or just a declarartion. 10346 /// \returns A CodeSegAttr or SectionAttr to apply to the function or 10347 /// nullptr if no attribute should be added. 10348 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, 10349 bool IsDefinition) { 10350 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD)) 10351 return A; 10352 if (!FD->hasAttr<SectionAttr>() && IsDefinition && 10353 CodeSegStack.CurrentValue) 10354 return SectionAttr::CreateImplicit( 10355 getASTContext(), CodeSegStack.CurrentValue->getString(), 10356 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 10357 SectionAttr::Declspec_allocate); 10358 return nullptr; 10359 } 10360 10361 /// Determines if we can perform a correct type check for \p D as a 10362 /// redeclaration of \p PrevDecl. If not, we can generally still perform a 10363 /// best-effort check. 10364 /// 10365 /// \param NewD The new declaration. 10366 /// \param OldD The old declaration. 10367 /// \param NewT The portion of the type of the new declaration to check. 10368 /// \param OldT The portion of the type of the old declaration to check. 10369 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, 10370 QualType NewT, QualType OldT) { 10371 if (!NewD->getLexicalDeclContext()->isDependentContext()) 10372 return true; 10373 10374 // For dependently-typed local extern declarations and friends, we can't 10375 // perform a correct type check in general until instantiation: 10376 // 10377 // int f(); 10378 // template<typename T> void g() { T f(); } 10379 // 10380 // (valid if g() is only instantiated with T = int). 10381 if (NewT->isDependentType() && 10382 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind())) 10383 return false; 10384 10385 // Similarly, if the previous declaration was a dependent local extern 10386 // declaration, we don't really know its type yet. 10387 if (OldT->isDependentType() && OldD->isLocalExternDecl()) 10388 return false; 10389 10390 return true; 10391 } 10392 10393 /// Checks if the new declaration declared in dependent context must be 10394 /// put in the same redeclaration chain as the specified declaration. 10395 /// 10396 /// \param D Declaration that is checked. 10397 /// \param PrevDecl Previous declaration found with proper lookup method for the 10398 /// same declaration name. 10399 /// \returns True if D must be added to the redeclaration chain which PrevDecl 10400 /// belongs to. 10401 /// 10402 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 10403 if (!D->getLexicalDeclContext()->isDependentContext()) 10404 return true; 10405 10406 // Don't chain dependent friend function definitions until instantiation, to 10407 // permit cases like 10408 // 10409 // void func(); 10410 // template<typename T> class C1 { friend void func() {} }; 10411 // template<typename T> class C2 { friend void func() {} }; 10412 // 10413 // ... which is valid if only one of C1 and C2 is ever instantiated. 10414 // 10415 // FIXME: This need only apply to function definitions. For now, we proxy 10416 // this by checking for a file-scope function. We do not want this to apply 10417 // to friend declarations nominating member functions, because that gets in 10418 // the way of access checks. 10419 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext()) 10420 return false; 10421 10422 auto *VD = dyn_cast<ValueDecl>(D); 10423 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl); 10424 return !VD || !PrevVD || 10425 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(), 10426 PrevVD->getType()); 10427 } 10428 10429 /// Check the target attribute of the function for MultiVersion 10430 /// validity. 10431 /// 10432 /// Returns true if there was an error, false otherwise. 10433 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { 10434 const auto *TA = FD->getAttr<TargetAttr>(); 10435 assert(TA && "MultiVersion Candidate requires a target attribute"); 10436 ParsedTargetAttr ParseInfo = TA->parse(); 10437 const TargetInfo &TargetInfo = S.Context.getTargetInfo(); 10438 enum ErrType { Feature = 0, Architecture = 1 }; 10439 10440 if (!ParseInfo.Architecture.empty() && 10441 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) { 10442 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10443 << Architecture << ParseInfo.Architecture; 10444 return true; 10445 } 10446 10447 for (const auto &Feat : ParseInfo.Features) { 10448 auto BareFeat = StringRef{Feat}.substr(1); 10449 if (Feat[0] == '-') { 10450 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10451 << Feature << ("no-" + BareFeat).str(); 10452 return true; 10453 } 10454 10455 if (!TargetInfo.validateCpuSupports(BareFeat) || 10456 !TargetInfo.isValidFeatureName(BareFeat)) { 10457 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10458 << Feature << BareFeat; 10459 return true; 10460 } 10461 } 10462 return false; 10463 } 10464 10465 // Provide a white-list of attributes that are allowed to be combined with 10466 // multiversion functions. 10467 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, 10468 MultiVersionKind MVKind) { 10469 // Note: this list/diagnosis must match the list in 10470 // checkMultiversionAttributesAllSame. 10471 switch (Kind) { 10472 default: 10473 return false; 10474 case attr::Used: 10475 return MVKind == MultiVersionKind::Target; 10476 case attr::NonNull: 10477 case attr::NoThrow: 10478 return true; 10479 } 10480 } 10481 10482 static bool checkNonMultiVersionCompatAttributes(Sema &S, 10483 const FunctionDecl *FD, 10484 const FunctionDecl *CausedFD, 10485 MultiVersionKind MVKind) { 10486 const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) { 10487 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr) 10488 << static_cast<unsigned>(MVKind) << A; 10489 if (CausedFD) 10490 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here); 10491 return true; 10492 }; 10493 10494 for (const Attr *A : FD->attrs()) { 10495 switch (A->getKind()) { 10496 case attr::CPUDispatch: 10497 case attr::CPUSpecific: 10498 if (MVKind != MultiVersionKind::CPUDispatch && 10499 MVKind != MultiVersionKind::CPUSpecific) 10500 return Diagnose(S, A); 10501 break; 10502 case attr::Target: 10503 if (MVKind != MultiVersionKind::Target) 10504 return Diagnose(S, A); 10505 break; 10506 case attr::TargetClones: 10507 if (MVKind != MultiVersionKind::TargetClones) 10508 return Diagnose(S, A); 10509 break; 10510 default: 10511 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind)) 10512 return Diagnose(S, A); 10513 break; 10514 } 10515 } 10516 return false; 10517 } 10518 10519 bool Sema::areMultiversionVariantFunctionsCompatible( 10520 const FunctionDecl *OldFD, const FunctionDecl *NewFD, 10521 const PartialDiagnostic &NoProtoDiagID, 10522 const PartialDiagnosticAt &NoteCausedDiagIDAt, 10523 const PartialDiagnosticAt &NoSupportDiagIDAt, 10524 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, 10525 bool ConstexprSupported, bool CLinkageMayDiffer) { 10526 enum DoesntSupport { 10527 FuncTemplates = 0, 10528 VirtFuncs = 1, 10529 DeducedReturn = 2, 10530 Constructors = 3, 10531 Destructors = 4, 10532 DeletedFuncs = 5, 10533 DefaultedFuncs = 6, 10534 ConstexprFuncs = 7, 10535 ConstevalFuncs = 8, 10536 Lambda = 9, 10537 }; 10538 enum Different { 10539 CallingConv = 0, 10540 ReturnType = 1, 10541 ConstexprSpec = 2, 10542 InlineSpec = 3, 10543 Linkage = 4, 10544 LanguageLinkage = 5, 10545 }; 10546 10547 if (NoProtoDiagID.getDiagID() != 0 && OldFD && 10548 !OldFD->getType()->getAs<FunctionProtoType>()) { 10549 Diag(OldFD->getLocation(), NoProtoDiagID); 10550 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second); 10551 return true; 10552 } 10553 10554 if (NoProtoDiagID.getDiagID() != 0 && 10555 !NewFD->getType()->getAs<FunctionProtoType>()) 10556 return Diag(NewFD->getLocation(), NoProtoDiagID); 10557 10558 if (!TemplatesSupported && 10559 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 10560 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10561 << FuncTemplates; 10562 10563 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { 10564 if (NewCXXFD->isVirtual()) 10565 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10566 << VirtFuncs; 10567 10568 if (isa<CXXConstructorDecl>(NewCXXFD)) 10569 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10570 << Constructors; 10571 10572 if (isa<CXXDestructorDecl>(NewCXXFD)) 10573 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10574 << Destructors; 10575 } 10576 10577 if (NewFD->isDeleted()) 10578 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10579 << DeletedFuncs; 10580 10581 if (NewFD->isDefaulted()) 10582 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10583 << DefaultedFuncs; 10584 10585 if (!ConstexprSupported && NewFD->isConstexpr()) 10586 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10587 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs); 10588 10589 QualType NewQType = Context.getCanonicalType(NewFD->getType()); 10590 const auto *NewType = cast<FunctionType>(NewQType); 10591 QualType NewReturnType = NewType->getReturnType(); 10592 10593 if (NewReturnType->isUndeducedType()) 10594 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10595 << DeducedReturn; 10596 10597 // Ensure the return type is identical. 10598 if (OldFD) { 10599 QualType OldQType = Context.getCanonicalType(OldFD->getType()); 10600 const auto *OldType = cast<FunctionType>(OldQType); 10601 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 10602 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 10603 10604 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) 10605 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv; 10606 10607 QualType OldReturnType = OldType->getReturnType(); 10608 10609 if (OldReturnType != NewReturnType) 10610 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType; 10611 10612 if (OldFD->getConstexprKind() != NewFD->getConstexprKind()) 10613 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec; 10614 10615 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) 10616 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec; 10617 10618 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage()) 10619 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage; 10620 10621 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC()) 10622 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage; 10623 10624 if (CheckEquivalentExceptionSpec( 10625 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), 10626 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) 10627 return true; 10628 } 10629 return false; 10630 } 10631 10632 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, 10633 const FunctionDecl *NewFD, 10634 bool CausesMV, 10635 MultiVersionKind MVKind) { 10636 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10637 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10638 if (OldFD) 10639 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10640 return true; 10641 } 10642 10643 bool IsCPUSpecificCPUDispatchMVKind = 10644 MVKind == MultiVersionKind::CPUDispatch || 10645 MVKind == MultiVersionKind::CPUSpecific; 10646 10647 if (CausesMV && OldFD && 10648 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind)) 10649 return true; 10650 10651 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind)) 10652 return true; 10653 10654 // Only allow transition to MultiVersion if it hasn't been used. 10655 if (OldFD && CausesMV && OldFD->isUsed(false)) 10656 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 10657 10658 return S.areMultiversionVariantFunctionsCompatible( 10659 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto), 10660 PartialDiagnosticAt(NewFD->getLocation(), 10661 S.PDiag(diag::note_multiversioning_caused_here)), 10662 PartialDiagnosticAt(NewFD->getLocation(), 10663 S.PDiag(diag::err_multiversion_doesnt_support) 10664 << static_cast<unsigned>(MVKind)), 10665 PartialDiagnosticAt(NewFD->getLocation(), 10666 S.PDiag(diag::err_multiversion_diff)), 10667 /*TemplatesSupported=*/false, 10668 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind, 10669 /*CLinkageMayDiffer=*/false); 10670 } 10671 10672 /// Check the validity of a multiversion function declaration that is the 10673 /// first of its kind. Also sets the multiversion'ness' of the function itself. 10674 /// 10675 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10676 /// 10677 /// Returns true if there was an error, false otherwise. 10678 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD, 10679 MultiVersionKind MVKind, 10680 const TargetAttr *TA) { 10681 assert(MVKind != MultiVersionKind::None && 10682 "Function lacks multiversion attribute"); 10683 10684 // Target only causes MV if it is default, otherwise this is a normal 10685 // function. 10686 if (MVKind == MultiVersionKind::Target && !TA->isDefaultVersion()) 10687 return false; 10688 10689 if (MVKind == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) { 10690 FD->setInvalidDecl(); 10691 return true; 10692 } 10693 10694 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) { 10695 FD->setInvalidDecl(); 10696 return true; 10697 } 10698 10699 FD->setIsMultiVersion(); 10700 return false; 10701 } 10702 10703 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) { 10704 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) { 10705 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None) 10706 return true; 10707 } 10708 10709 return false; 10710 } 10711 10712 static bool CheckTargetCausesMultiVersioning( 10713 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA, 10714 bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous) { 10715 const auto *OldTA = OldFD->getAttr<TargetAttr>(); 10716 ParsedTargetAttr NewParsed = NewTA->parse(); 10717 // Sort order doesn't matter, it just needs to be consistent. 10718 llvm::sort(NewParsed.Features); 10719 10720 // If the old decl is NOT MultiVersioned yet, and we don't cause that 10721 // to change, this is a simple redeclaration. 10722 if (!NewTA->isDefaultVersion() && 10723 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) 10724 return false; 10725 10726 // Otherwise, this decl causes MultiVersioning. 10727 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true, 10728 MultiVersionKind::Target)) { 10729 NewFD->setInvalidDecl(); 10730 return true; 10731 } 10732 10733 if (CheckMultiVersionValue(S, NewFD)) { 10734 NewFD->setInvalidDecl(); 10735 return true; 10736 } 10737 10738 // If this is 'default', permit the forward declaration. 10739 if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) { 10740 Redeclaration = true; 10741 OldDecl = OldFD; 10742 OldFD->setIsMultiVersion(); 10743 NewFD->setIsMultiVersion(); 10744 return false; 10745 } 10746 10747 if (CheckMultiVersionValue(S, OldFD)) { 10748 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10749 NewFD->setInvalidDecl(); 10750 return true; 10751 } 10752 10753 ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>()); 10754 10755 if (OldParsed == NewParsed) { 10756 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10757 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10758 NewFD->setInvalidDecl(); 10759 return true; 10760 } 10761 10762 for (const auto *FD : OldFD->redecls()) { 10763 const auto *CurTA = FD->getAttr<TargetAttr>(); 10764 // We allow forward declarations before ANY multiversioning attributes, but 10765 // nothing after the fact. 10766 if (PreviousDeclsHaveMultiVersionAttribute(FD) && 10767 (!CurTA || CurTA->isInherited())) { 10768 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl) 10769 << 0; 10770 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10771 NewFD->setInvalidDecl(); 10772 return true; 10773 } 10774 } 10775 10776 OldFD->setIsMultiVersion(); 10777 NewFD->setIsMultiVersion(); 10778 Redeclaration = false; 10779 OldDecl = nullptr; 10780 Previous.clear(); 10781 return false; 10782 } 10783 10784 static bool MultiVersionTypesCompatible(MultiVersionKind Old, 10785 MultiVersionKind New) { 10786 if (Old == New || Old == MultiVersionKind::None || 10787 New == MultiVersionKind::None) 10788 return true; 10789 10790 return (Old == MultiVersionKind::CPUDispatch && 10791 New == MultiVersionKind::CPUSpecific) || 10792 (Old == MultiVersionKind::CPUSpecific && 10793 New == MultiVersionKind::CPUDispatch); 10794 } 10795 10796 /// Check the validity of a new function declaration being added to an existing 10797 /// multiversioned declaration collection. 10798 static bool CheckMultiVersionAdditionalDecl( 10799 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, 10800 MultiVersionKind NewMVKind, const TargetAttr *NewTA, 10801 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, 10802 const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl, 10803 LookupResult &Previous) { 10804 10805 MultiVersionKind OldMVKind = OldFD->getMultiVersionKind(); 10806 // Disallow mixing of multiversioning types. 10807 if (!MultiVersionTypesCompatible(OldMVKind, NewMVKind)) { 10808 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10809 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10810 NewFD->setInvalidDecl(); 10811 return true; 10812 } 10813 10814 ParsedTargetAttr NewParsed; 10815 if (NewTA) { 10816 NewParsed = NewTA->parse(); 10817 llvm::sort(NewParsed.Features); 10818 } 10819 10820 bool UseMemberUsingDeclRules = 10821 S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); 10822 10823 bool MayNeedOverloadableChecks = 10824 AllowOverloadingOfFunction(Previous, S.Context, NewFD); 10825 10826 // Next, check ALL non-overloads to see if this is a redeclaration of a 10827 // previous member of the MultiVersion set. 10828 for (NamedDecl *ND : Previous) { 10829 FunctionDecl *CurFD = ND->getAsFunction(); 10830 if (!CurFD) 10831 continue; 10832 if (MayNeedOverloadableChecks && 10833 S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) 10834 continue; 10835 10836 switch (NewMVKind) { 10837 case MultiVersionKind::None: 10838 assert(OldMVKind == MultiVersionKind::TargetClones && 10839 "Only target_clones can be omitted in subsequent declarations"); 10840 break; 10841 case MultiVersionKind::Target: { 10842 const auto *CurTA = CurFD->getAttr<TargetAttr>(); 10843 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { 10844 NewFD->setIsMultiVersion(); 10845 Redeclaration = true; 10846 OldDecl = ND; 10847 return false; 10848 } 10849 10850 ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>()); 10851 if (CurParsed == NewParsed) { 10852 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10853 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10854 NewFD->setInvalidDecl(); 10855 return true; 10856 } 10857 break; 10858 } 10859 case MultiVersionKind::TargetClones: { 10860 const auto *CurClones = CurFD->getAttr<TargetClonesAttr>(); 10861 Redeclaration = true; 10862 OldDecl = CurFD; 10863 NewFD->setIsMultiVersion(); 10864 10865 if (CurClones && NewClones && 10866 (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() || 10867 !std::equal(CurClones->featuresStrs_begin(), 10868 CurClones->featuresStrs_end(), 10869 NewClones->featuresStrs_begin()))) { 10870 S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match); 10871 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10872 NewFD->setInvalidDecl(); 10873 return true; 10874 } 10875 10876 return false; 10877 } 10878 case MultiVersionKind::CPUSpecific: 10879 case MultiVersionKind::CPUDispatch: { 10880 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>(); 10881 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>(); 10882 // Handle CPUDispatch/CPUSpecific versions. 10883 // Only 1 CPUDispatch function is allowed, this will make it go through 10884 // the redeclaration errors. 10885 if (NewMVKind == MultiVersionKind::CPUDispatch && 10886 CurFD->hasAttr<CPUDispatchAttr>()) { 10887 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() && 10888 std::equal( 10889 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(), 10890 NewCPUDisp->cpus_begin(), 10891 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10892 return Cur->getName() == New->getName(); 10893 })) { 10894 NewFD->setIsMultiVersion(); 10895 Redeclaration = true; 10896 OldDecl = ND; 10897 return false; 10898 } 10899 10900 // If the declarations don't match, this is an error condition. 10901 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch); 10902 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10903 NewFD->setInvalidDecl(); 10904 return true; 10905 } 10906 if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) { 10907 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() && 10908 std::equal( 10909 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(), 10910 NewCPUSpec->cpus_begin(), 10911 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10912 return Cur->getName() == New->getName(); 10913 })) { 10914 NewFD->setIsMultiVersion(); 10915 Redeclaration = true; 10916 OldDecl = ND; 10917 return false; 10918 } 10919 10920 // Only 1 version of CPUSpecific is allowed for each CPU. 10921 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) { 10922 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) { 10923 if (CurII == NewII) { 10924 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs) 10925 << NewII; 10926 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10927 NewFD->setInvalidDecl(); 10928 return true; 10929 } 10930 } 10931 } 10932 } 10933 break; 10934 } 10935 } 10936 } 10937 10938 // Else, this is simply a non-redecl case. Checking the 'value' is only 10939 // necessary in the Target case, since The CPUSpecific/Dispatch cases are 10940 // handled in the attribute adding step. 10941 if (NewMVKind == MultiVersionKind::Target && 10942 CheckMultiVersionValue(S, NewFD)) { 10943 NewFD->setInvalidDecl(); 10944 return true; 10945 } 10946 10947 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, 10948 !OldFD->isMultiVersion(), NewMVKind)) { 10949 NewFD->setInvalidDecl(); 10950 return true; 10951 } 10952 10953 // Permit forward declarations in the case where these two are compatible. 10954 if (!OldFD->isMultiVersion()) { 10955 OldFD->setIsMultiVersion(); 10956 NewFD->setIsMultiVersion(); 10957 Redeclaration = true; 10958 OldDecl = OldFD; 10959 return false; 10960 } 10961 10962 NewFD->setIsMultiVersion(); 10963 Redeclaration = false; 10964 OldDecl = nullptr; 10965 Previous.clear(); 10966 return false; 10967 } 10968 10969 /// Check the validity of a mulitversion function declaration. 10970 /// Also sets the multiversion'ness' of the function itself. 10971 /// 10972 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10973 /// 10974 /// Returns true if there was an error, false otherwise. 10975 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, 10976 bool &Redeclaration, NamedDecl *&OldDecl, 10977 LookupResult &Previous) { 10978 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 10979 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>(); 10980 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>(); 10981 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>(); 10982 MultiVersionKind MVKind = NewFD->getMultiVersionKind(); 10983 10984 // Main isn't allowed to become a multiversion function, however it IS 10985 // permitted to have 'main' be marked with the 'target' optimization hint. 10986 if (NewFD->isMain()) { 10987 if (MVKind != MultiVersionKind::None && 10988 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion())) { 10989 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); 10990 NewFD->setInvalidDecl(); 10991 return true; 10992 } 10993 return false; 10994 } 10995 10996 if (!OldDecl || !OldDecl->getAsFunction() || 10997 OldDecl->getDeclContext()->getRedeclContext() != 10998 NewFD->getDeclContext()->getRedeclContext()) { 10999 // If there's no previous declaration, AND this isn't attempting to cause 11000 // multiversioning, this isn't an error condition. 11001 if (MVKind == MultiVersionKind::None) 11002 return false; 11003 return CheckMultiVersionFirstFunction(S, NewFD, MVKind, NewTA); 11004 } 11005 11006 FunctionDecl *OldFD = OldDecl->getAsFunction(); 11007 11008 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None) 11009 return false; 11010 11011 // Multiversioned redeclarations aren't allowed to omit the attribute, except 11012 // for target_clones. 11013 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None && 11014 OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones) { 11015 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl) 11016 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target); 11017 NewFD->setInvalidDecl(); 11018 return true; 11019 } 11020 11021 if (!OldFD->isMultiVersion()) { 11022 switch (MVKind) { 11023 case MultiVersionKind::Target: 11024 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA, 11025 Redeclaration, OldDecl, Previous); 11026 case MultiVersionKind::TargetClones: 11027 if (OldFD->isUsed(false)) { 11028 NewFD->setInvalidDecl(); 11029 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 11030 } 11031 OldFD->setIsMultiVersion(); 11032 break; 11033 case MultiVersionKind::CPUDispatch: 11034 case MultiVersionKind::CPUSpecific: 11035 case MultiVersionKind::None: 11036 break; 11037 } 11038 } 11039 11040 // At this point, we have a multiversion function decl (in OldFD) AND an 11041 // appropriate attribute in the current function decl. Resolve that these are 11042 // still compatible with previous declarations. 11043 return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, MVKind, NewTA, 11044 NewCPUDisp, NewCPUSpec, NewClones, 11045 Redeclaration, OldDecl, Previous); 11046 } 11047 11048 /// Perform semantic checking of a new function declaration. 11049 /// 11050 /// Performs semantic analysis of the new function declaration 11051 /// NewFD. This routine performs all semantic checking that does not 11052 /// require the actual declarator involved in the declaration, and is 11053 /// used both for the declaration of functions as they are parsed 11054 /// (called via ActOnDeclarator) and for the declaration of functions 11055 /// that have been instantiated via C++ template instantiation (called 11056 /// via InstantiateDecl). 11057 /// 11058 /// \param IsMemberSpecialization whether this new function declaration is 11059 /// a member specialization (that replaces any definition provided by the 11060 /// previous declaration). 11061 /// 11062 /// This sets NewFD->isInvalidDecl() to true if there was an error. 11063 /// 11064 /// \returns true if the function declaration is a redeclaration. 11065 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 11066 LookupResult &Previous, 11067 bool IsMemberSpecialization) { 11068 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 11069 "Variably modified return types are not handled here"); 11070 11071 // Determine whether the type of this function should be merged with 11072 // a previous visible declaration. This never happens for functions in C++, 11073 // and always happens in C if the previous declaration was visible. 11074 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 11075 !Previous.isShadowed(); 11076 11077 bool Redeclaration = false; 11078 NamedDecl *OldDecl = nullptr; 11079 bool MayNeedOverloadableChecks = false; 11080 11081 // Merge or overload the declaration with an existing declaration of 11082 // the same name, if appropriate. 11083 if (!Previous.empty()) { 11084 // Determine whether NewFD is an overload of PrevDecl or 11085 // a declaration that requires merging. If it's an overload, 11086 // there's no more work to do here; we'll just add the new 11087 // function to the scope. 11088 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { 11089 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 11090 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 11091 Redeclaration = true; 11092 OldDecl = Candidate; 11093 } 11094 } else { 11095 MayNeedOverloadableChecks = true; 11096 switch (CheckOverload(S, NewFD, Previous, OldDecl, 11097 /*NewIsUsingDecl*/ false)) { 11098 case Ovl_Match: 11099 Redeclaration = true; 11100 break; 11101 11102 case Ovl_NonFunction: 11103 Redeclaration = true; 11104 break; 11105 11106 case Ovl_Overload: 11107 Redeclaration = false; 11108 break; 11109 } 11110 } 11111 } 11112 11113 // Check for a previous extern "C" declaration with this name. 11114 if (!Redeclaration && 11115 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 11116 if (!Previous.empty()) { 11117 // This is an extern "C" declaration with the same name as a previous 11118 // declaration, and thus redeclares that entity... 11119 Redeclaration = true; 11120 OldDecl = Previous.getFoundDecl(); 11121 MergeTypeWithPrevious = false; 11122 11123 // ... except in the presence of __attribute__((overloadable)). 11124 if (OldDecl->hasAttr<OverloadableAttr>() || 11125 NewFD->hasAttr<OverloadableAttr>()) { 11126 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 11127 MayNeedOverloadableChecks = true; 11128 Redeclaration = false; 11129 OldDecl = nullptr; 11130 } 11131 } 11132 } 11133 } 11134 11135 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous)) 11136 return Redeclaration; 11137 11138 // PPC MMA non-pointer types are not allowed as function return types. 11139 if (Context.getTargetInfo().getTriple().isPPC64() && 11140 CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) { 11141 NewFD->setInvalidDecl(); 11142 } 11143 11144 // C++11 [dcl.constexpr]p8: 11145 // A constexpr specifier for a non-static member function that is not 11146 // a constructor declares that member function to be const. 11147 // 11148 // This needs to be delayed until we know whether this is an out-of-line 11149 // definition of a static member function. 11150 // 11151 // This rule is not present in C++1y, so we produce a backwards 11152 // compatibility warning whenever it happens in C++11. 11153 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 11154 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 11155 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 11156 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) { 11157 CXXMethodDecl *OldMD = nullptr; 11158 if (OldDecl) 11159 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 11160 if (!OldMD || !OldMD->isStatic()) { 11161 const FunctionProtoType *FPT = 11162 MD->getType()->castAs<FunctionProtoType>(); 11163 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 11164 EPI.TypeQuals.addConst(); 11165 MD->setType(Context.getFunctionType(FPT->getReturnType(), 11166 FPT->getParamTypes(), EPI)); 11167 11168 // Warn that we did this, if we're not performing template instantiation. 11169 // In that case, we'll have warned already when the template was defined. 11170 if (!inTemplateInstantiation()) { 11171 SourceLocation AddConstLoc; 11172 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 11173 .IgnoreParens().getAs<FunctionTypeLoc>()) 11174 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 11175 11176 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 11177 << FixItHint::CreateInsertion(AddConstLoc, " const"); 11178 } 11179 } 11180 } 11181 11182 if (Redeclaration) { 11183 // NewFD and OldDecl represent declarations that need to be 11184 // merged. 11185 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 11186 NewFD->setInvalidDecl(); 11187 return Redeclaration; 11188 } 11189 11190 Previous.clear(); 11191 Previous.addDecl(OldDecl); 11192 11193 if (FunctionTemplateDecl *OldTemplateDecl = 11194 dyn_cast<FunctionTemplateDecl>(OldDecl)) { 11195 auto *OldFD = OldTemplateDecl->getTemplatedDecl(); 11196 FunctionTemplateDecl *NewTemplateDecl 11197 = NewFD->getDescribedFunctionTemplate(); 11198 assert(NewTemplateDecl && "Template/non-template mismatch"); 11199 11200 // The call to MergeFunctionDecl above may have created some state in 11201 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we 11202 // can add it as a redeclaration. 11203 NewTemplateDecl->mergePrevDecl(OldTemplateDecl); 11204 11205 NewFD->setPreviousDeclaration(OldFD); 11206 if (NewFD->isCXXClassMember()) { 11207 NewFD->setAccess(OldTemplateDecl->getAccess()); 11208 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 11209 } 11210 11211 // If this is an explicit specialization of a member that is a function 11212 // template, mark it as a member specialization. 11213 if (IsMemberSpecialization && 11214 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 11215 NewTemplateDecl->setMemberSpecialization(); 11216 assert(OldTemplateDecl->isMemberSpecialization()); 11217 // Explicit specializations of a member template do not inherit deleted 11218 // status from the parent member template that they are specializing. 11219 if (OldFD->isDeleted()) { 11220 // FIXME: This assert will not hold in the presence of modules. 11221 assert(OldFD->getCanonicalDecl() == OldFD); 11222 // FIXME: We need an update record for this AST mutation. 11223 OldFD->setDeletedAsWritten(false); 11224 } 11225 } 11226 11227 } else { 11228 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 11229 auto *OldFD = cast<FunctionDecl>(OldDecl); 11230 // This needs to happen first so that 'inline' propagates. 11231 NewFD->setPreviousDeclaration(OldFD); 11232 if (NewFD->isCXXClassMember()) 11233 NewFD->setAccess(OldFD->getAccess()); 11234 } 11235 } 11236 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && 11237 !NewFD->getAttr<OverloadableAttr>()) { 11238 assert((Previous.empty() || 11239 llvm::any_of(Previous, 11240 [](const NamedDecl *ND) { 11241 return ND->hasAttr<OverloadableAttr>(); 11242 })) && 11243 "Non-redecls shouldn't happen without overloadable present"); 11244 11245 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { 11246 const auto *FD = dyn_cast<FunctionDecl>(ND); 11247 return FD && !FD->hasAttr<OverloadableAttr>(); 11248 }); 11249 11250 if (OtherUnmarkedIter != Previous.end()) { 11251 Diag(NewFD->getLocation(), 11252 diag::err_attribute_overloadable_multiple_unmarked_overloads); 11253 Diag((*OtherUnmarkedIter)->getLocation(), 11254 diag::note_attribute_overloadable_prev_overload) 11255 << false; 11256 11257 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 11258 } 11259 } 11260 11261 if (LangOpts.OpenMP) 11262 ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD); 11263 11264 // Semantic checking for this function declaration (in isolation). 11265 11266 if (getLangOpts().CPlusPlus) { 11267 // C++-specific checks. 11268 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 11269 CheckConstructor(Constructor); 11270 } else if (CXXDestructorDecl *Destructor = 11271 dyn_cast<CXXDestructorDecl>(NewFD)) { 11272 CXXRecordDecl *Record = Destructor->getParent(); 11273 QualType ClassType = Context.getTypeDeclType(Record); 11274 11275 // FIXME: Shouldn't we be able to perform this check even when the class 11276 // type is dependent? Both gcc and edg can handle that. 11277 if (!ClassType->isDependentType()) { 11278 DeclarationName Name 11279 = Context.DeclarationNames.getCXXDestructorName( 11280 Context.getCanonicalType(ClassType)); 11281 if (NewFD->getDeclName() != Name) { 11282 Diag(NewFD->getLocation(), diag::err_destructor_name); 11283 NewFD->setInvalidDecl(); 11284 return Redeclaration; 11285 } 11286 } 11287 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 11288 if (auto *TD = Guide->getDescribedFunctionTemplate()) 11289 CheckDeductionGuideTemplate(TD); 11290 11291 // A deduction guide is not on the list of entities that can be 11292 // explicitly specialized. 11293 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 11294 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized) 11295 << /*explicit specialization*/ 1; 11296 } 11297 11298 // Find any virtual functions that this function overrides. 11299 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 11300 if (!Method->isFunctionTemplateSpecialization() && 11301 !Method->getDescribedFunctionTemplate() && 11302 Method->isCanonicalDecl()) { 11303 AddOverriddenMethods(Method->getParent(), Method); 11304 } 11305 if (Method->isVirtual() && NewFD->getTrailingRequiresClause()) 11306 // C++2a [class.virtual]p6 11307 // A virtual method shall not have a requires-clause. 11308 Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(), 11309 diag::err_constrained_virtual_method); 11310 11311 if (Method->isStatic()) 11312 checkThisInStaticMemberFunctionType(Method); 11313 } 11314 11315 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD)) 11316 ActOnConversionDeclarator(Conversion); 11317 11318 // Extra checking for C++ overloaded operators (C++ [over.oper]). 11319 if (NewFD->isOverloadedOperator() && 11320 CheckOverloadedOperatorDeclaration(NewFD)) { 11321 NewFD->setInvalidDecl(); 11322 return Redeclaration; 11323 } 11324 11325 // Extra checking for C++0x literal operators (C++0x [over.literal]). 11326 if (NewFD->getLiteralIdentifier() && 11327 CheckLiteralOperatorDeclaration(NewFD)) { 11328 NewFD->setInvalidDecl(); 11329 return Redeclaration; 11330 } 11331 11332 // In C++, check default arguments now that we have merged decls. Unless 11333 // the lexical context is the class, because in this case this is done 11334 // during delayed parsing anyway. 11335 if (!CurContext->isRecord()) 11336 CheckCXXDefaultArguments(NewFD); 11337 11338 // If this function is declared as being extern "C", then check to see if 11339 // the function returns a UDT (class, struct, or union type) that is not C 11340 // compatible, and if it does, warn the user. 11341 // But, issue any diagnostic on the first declaration only. 11342 if (Previous.empty() && NewFD->isExternC()) { 11343 QualType R = NewFD->getReturnType(); 11344 if (R->isIncompleteType() && !R->isVoidType()) 11345 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 11346 << NewFD << R; 11347 else if (!R.isPODType(Context) && !R->isVoidType() && 11348 !R->isObjCObjectPointerType()) 11349 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 11350 } 11351 11352 // C++1z [dcl.fct]p6: 11353 // [...] whether the function has a non-throwing exception-specification 11354 // [is] part of the function type 11355 // 11356 // This results in an ABI break between C++14 and C++17 for functions whose 11357 // declared type includes an exception-specification in a parameter or 11358 // return type. (Exception specifications on the function itself are OK in 11359 // most cases, and exception specifications are not permitted in most other 11360 // contexts where they could make it into a mangling.) 11361 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { 11362 auto HasNoexcept = [&](QualType T) -> bool { 11363 // Strip off declarator chunks that could be between us and a function 11364 // type. We don't need to look far, exception specifications are very 11365 // restricted prior to C++17. 11366 if (auto *RT = T->getAs<ReferenceType>()) 11367 T = RT->getPointeeType(); 11368 else if (T->isAnyPointerType()) 11369 T = T->getPointeeType(); 11370 else if (auto *MPT = T->getAs<MemberPointerType>()) 11371 T = MPT->getPointeeType(); 11372 if (auto *FPT = T->getAs<FunctionProtoType>()) 11373 if (FPT->isNothrow()) 11374 return true; 11375 return false; 11376 }; 11377 11378 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 11379 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 11380 for (QualType T : FPT->param_types()) 11381 AnyNoexcept |= HasNoexcept(T); 11382 if (AnyNoexcept) 11383 Diag(NewFD->getLocation(), 11384 diag::warn_cxx17_compat_exception_spec_in_signature) 11385 << NewFD; 11386 } 11387 11388 if (!Redeclaration && LangOpts.CUDA) 11389 checkCUDATargetOverload(NewFD, Previous); 11390 } 11391 return Redeclaration; 11392 } 11393 11394 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 11395 // C++11 [basic.start.main]p3: 11396 // A program that [...] declares main to be inline, static or 11397 // constexpr is ill-formed. 11398 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 11399 // appear in a declaration of main. 11400 // static main is not an error under C99, but we should warn about it. 11401 // We accept _Noreturn main as an extension. 11402 if (FD->getStorageClass() == SC_Static) 11403 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 11404 ? diag::err_static_main : diag::warn_static_main) 11405 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 11406 if (FD->isInlineSpecified()) 11407 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 11408 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 11409 if (DS.isNoreturnSpecified()) { 11410 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 11411 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 11412 Diag(NoreturnLoc, diag::ext_noreturn_main); 11413 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 11414 << FixItHint::CreateRemoval(NoreturnRange); 11415 } 11416 if (FD->isConstexpr()) { 11417 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 11418 << FD->isConsteval() 11419 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 11420 FD->setConstexprKind(ConstexprSpecKind::Unspecified); 11421 } 11422 11423 if (getLangOpts().OpenCL) { 11424 Diag(FD->getLocation(), diag::err_opencl_no_main) 11425 << FD->hasAttr<OpenCLKernelAttr>(); 11426 FD->setInvalidDecl(); 11427 return; 11428 } 11429 11430 // Functions named main in hlsl are default entries, but don't have specific 11431 // signatures they are required to conform to. 11432 if (getLangOpts().HLSL) 11433 return; 11434 11435 QualType T = FD->getType(); 11436 assert(T->isFunctionType() && "function decl is not of function type"); 11437 const FunctionType* FT = T->castAs<FunctionType>(); 11438 11439 // Set default calling convention for main() 11440 if (FT->getCallConv() != CC_C) { 11441 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); 11442 FD->setType(QualType(FT, 0)); 11443 T = Context.getCanonicalType(FD->getType()); 11444 } 11445 11446 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 11447 // In C with GNU extensions we allow main() to have non-integer return 11448 // type, but we should warn about the extension, and we disable the 11449 // implicit-return-zero rule. 11450 11451 // GCC in C mode accepts qualified 'int'. 11452 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 11453 FD->setHasImplicitReturnZero(true); 11454 else { 11455 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 11456 SourceRange RTRange = FD->getReturnTypeSourceRange(); 11457 if (RTRange.isValid()) 11458 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 11459 << FixItHint::CreateReplacement(RTRange, "int"); 11460 } 11461 } else { 11462 // In C and C++, main magically returns 0 if you fall off the end; 11463 // set the flag which tells us that. 11464 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 11465 11466 // All the standards say that main() should return 'int'. 11467 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 11468 FD->setHasImplicitReturnZero(true); 11469 else { 11470 // Otherwise, this is just a flat-out error. 11471 SourceRange RTRange = FD->getReturnTypeSourceRange(); 11472 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 11473 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 11474 : FixItHint()); 11475 FD->setInvalidDecl(true); 11476 } 11477 } 11478 11479 // Treat protoless main() as nullary. 11480 if (isa<FunctionNoProtoType>(FT)) return; 11481 11482 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 11483 unsigned nparams = FTP->getNumParams(); 11484 assert(FD->getNumParams() == nparams); 11485 11486 bool HasExtraParameters = (nparams > 3); 11487 11488 if (FTP->isVariadic()) { 11489 Diag(FD->getLocation(), diag::ext_variadic_main); 11490 // FIXME: if we had information about the location of the ellipsis, we 11491 // could add a FixIt hint to remove it as a parameter. 11492 } 11493 11494 // Darwin passes an undocumented fourth argument of type char**. If 11495 // other platforms start sprouting these, the logic below will start 11496 // getting shifty. 11497 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 11498 HasExtraParameters = false; 11499 11500 if (HasExtraParameters) { 11501 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 11502 FD->setInvalidDecl(true); 11503 nparams = 3; 11504 } 11505 11506 // FIXME: a lot of the following diagnostics would be improved 11507 // if we had some location information about types. 11508 11509 QualType CharPP = 11510 Context.getPointerType(Context.getPointerType(Context.CharTy)); 11511 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 11512 11513 for (unsigned i = 0; i < nparams; ++i) { 11514 QualType AT = FTP->getParamType(i); 11515 11516 bool mismatch = true; 11517 11518 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 11519 mismatch = false; 11520 else if (Expected[i] == CharPP) { 11521 // As an extension, the following forms are okay: 11522 // char const ** 11523 // char const * const * 11524 // char * const * 11525 11526 QualifierCollector qs; 11527 const PointerType* PT; 11528 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 11529 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 11530 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 11531 Context.CharTy)) { 11532 qs.removeConst(); 11533 mismatch = !qs.empty(); 11534 } 11535 } 11536 11537 if (mismatch) { 11538 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 11539 // TODO: suggest replacing given type with expected type 11540 FD->setInvalidDecl(true); 11541 } 11542 } 11543 11544 if (nparams == 1 && !FD->isInvalidDecl()) { 11545 Diag(FD->getLocation(), diag::warn_main_one_arg); 11546 } 11547 11548 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11549 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11550 FD->setInvalidDecl(); 11551 } 11552 } 11553 11554 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) { 11555 11556 // Default calling convention for main and wmain is __cdecl 11557 if (FD->getName() == "main" || FD->getName() == "wmain") 11558 return false; 11559 11560 // Default calling convention for MinGW is __cdecl 11561 const llvm::Triple &T = S.Context.getTargetInfo().getTriple(); 11562 if (T.isWindowsGNUEnvironment()) 11563 return false; 11564 11565 // Default calling convention for WinMain, wWinMain and DllMain 11566 // is __stdcall on 32 bit Windows 11567 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86) 11568 return true; 11569 11570 return false; 11571 } 11572 11573 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 11574 QualType T = FD->getType(); 11575 assert(T->isFunctionType() && "function decl is not of function type"); 11576 const FunctionType *FT = T->castAs<FunctionType>(); 11577 11578 // Set an implicit return of 'zero' if the function can return some integral, 11579 // enumeration, pointer or nullptr type. 11580 if (FT->getReturnType()->isIntegralOrEnumerationType() || 11581 FT->getReturnType()->isAnyPointerType() || 11582 FT->getReturnType()->isNullPtrType()) 11583 // DllMain is exempt because a return value of zero means it failed. 11584 if (FD->getName() != "DllMain") 11585 FD->setHasImplicitReturnZero(true); 11586 11587 // Explicity specified calling conventions are applied to MSVC entry points 11588 if (!hasExplicitCallingConv(T)) { 11589 if (isDefaultStdCall(FD, *this)) { 11590 if (FT->getCallConv() != CC_X86StdCall) { 11591 FT = Context.adjustFunctionType( 11592 FT, FT->getExtInfo().withCallingConv(CC_X86StdCall)); 11593 FD->setType(QualType(FT, 0)); 11594 } 11595 } else if (FT->getCallConv() != CC_C) { 11596 FT = Context.adjustFunctionType(FT, 11597 FT->getExtInfo().withCallingConv(CC_C)); 11598 FD->setType(QualType(FT, 0)); 11599 } 11600 } 11601 11602 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11603 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11604 FD->setInvalidDecl(); 11605 } 11606 } 11607 11608 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 11609 // FIXME: Need strict checking. In C89, we need to check for 11610 // any assignment, increment, decrement, function-calls, or 11611 // commas outside of a sizeof. In C99, it's the same list, 11612 // except that the aforementioned are allowed in unevaluated 11613 // expressions. Everything else falls under the 11614 // "may accept other forms of constant expressions" exception. 11615 // 11616 // Regular C++ code will not end up here (exceptions: language extensions, 11617 // OpenCL C++ etc), so the constant expression rules there don't matter. 11618 if (Init->isValueDependent()) { 11619 assert(Init->containsErrors() && 11620 "Dependent code should only occur in error-recovery path."); 11621 return true; 11622 } 11623 const Expr *Culprit; 11624 if (Init->isConstantInitializer(Context, false, &Culprit)) 11625 return false; 11626 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 11627 << Culprit->getSourceRange(); 11628 return true; 11629 } 11630 11631 namespace { 11632 // Visits an initialization expression to see if OrigDecl is evaluated in 11633 // its own initialization and throws a warning if it does. 11634 class SelfReferenceChecker 11635 : public EvaluatedExprVisitor<SelfReferenceChecker> { 11636 Sema &S; 11637 Decl *OrigDecl; 11638 bool isRecordType; 11639 bool isPODType; 11640 bool isReferenceType; 11641 11642 bool isInitList; 11643 llvm::SmallVector<unsigned, 4> InitFieldIndex; 11644 11645 public: 11646 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 11647 11648 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 11649 S(S), OrigDecl(OrigDecl) { 11650 isPODType = false; 11651 isRecordType = false; 11652 isReferenceType = false; 11653 isInitList = false; 11654 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 11655 isPODType = VD->getType().isPODType(S.Context); 11656 isRecordType = VD->getType()->isRecordType(); 11657 isReferenceType = VD->getType()->isReferenceType(); 11658 } 11659 } 11660 11661 // For most expressions, just call the visitor. For initializer lists, 11662 // track the index of the field being initialized since fields are 11663 // initialized in order allowing use of previously initialized fields. 11664 void CheckExpr(Expr *E) { 11665 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 11666 if (!InitList) { 11667 Visit(E); 11668 return; 11669 } 11670 11671 // Track and increment the index here. 11672 isInitList = true; 11673 InitFieldIndex.push_back(0); 11674 for (auto Child : InitList->children()) { 11675 CheckExpr(cast<Expr>(Child)); 11676 ++InitFieldIndex.back(); 11677 } 11678 InitFieldIndex.pop_back(); 11679 } 11680 11681 // Returns true if MemberExpr is checked and no further checking is needed. 11682 // Returns false if additional checking is required. 11683 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 11684 llvm::SmallVector<FieldDecl*, 4> Fields; 11685 Expr *Base = E; 11686 bool ReferenceField = false; 11687 11688 // Get the field members used. 11689 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11690 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 11691 if (!FD) 11692 return false; 11693 Fields.push_back(FD); 11694 if (FD->getType()->isReferenceType()) 11695 ReferenceField = true; 11696 Base = ME->getBase()->IgnoreParenImpCasts(); 11697 } 11698 11699 // Keep checking only if the base Decl is the same. 11700 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 11701 if (!DRE || DRE->getDecl() != OrigDecl) 11702 return false; 11703 11704 // A reference field can be bound to an unininitialized field. 11705 if (CheckReference && !ReferenceField) 11706 return true; 11707 11708 // Convert FieldDecls to their index number. 11709 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 11710 for (const FieldDecl *I : llvm::reverse(Fields)) 11711 UsedFieldIndex.push_back(I->getFieldIndex()); 11712 11713 // See if a warning is needed by checking the first difference in index 11714 // numbers. If field being used has index less than the field being 11715 // initialized, then the use is safe. 11716 for (auto UsedIter = UsedFieldIndex.begin(), 11717 UsedEnd = UsedFieldIndex.end(), 11718 OrigIter = InitFieldIndex.begin(), 11719 OrigEnd = InitFieldIndex.end(); 11720 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 11721 if (*UsedIter < *OrigIter) 11722 return true; 11723 if (*UsedIter > *OrigIter) 11724 break; 11725 } 11726 11727 // TODO: Add a different warning which will print the field names. 11728 HandleDeclRefExpr(DRE); 11729 return true; 11730 } 11731 11732 // For most expressions, the cast is directly above the DeclRefExpr. 11733 // For conditional operators, the cast can be outside the conditional 11734 // operator if both expressions are DeclRefExpr's. 11735 void HandleValue(Expr *E) { 11736 E = E->IgnoreParens(); 11737 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 11738 HandleDeclRefExpr(DRE); 11739 return; 11740 } 11741 11742 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 11743 Visit(CO->getCond()); 11744 HandleValue(CO->getTrueExpr()); 11745 HandleValue(CO->getFalseExpr()); 11746 return; 11747 } 11748 11749 if (BinaryConditionalOperator *BCO = 11750 dyn_cast<BinaryConditionalOperator>(E)) { 11751 Visit(BCO->getCond()); 11752 HandleValue(BCO->getFalseExpr()); 11753 return; 11754 } 11755 11756 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 11757 HandleValue(OVE->getSourceExpr()); 11758 return; 11759 } 11760 11761 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11762 if (BO->getOpcode() == BO_Comma) { 11763 Visit(BO->getLHS()); 11764 HandleValue(BO->getRHS()); 11765 return; 11766 } 11767 } 11768 11769 if (isa<MemberExpr>(E)) { 11770 if (isInitList) { 11771 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 11772 false /*CheckReference*/)) 11773 return; 11774 } 11775 11776 Expr *Base = E->IgnoreParenImpCasts(); 11777 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11778 // Check for static member variables and don't warn on them. 11779 if (!isa<FieldDecl>(ME->getMemberDecl())) 11780 return; 11781 Base = ME->getBase()->IgnoreParenImpCasts(); 11782 } 11783 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 11784 HandleDeclRefExpr(DRE); 11785 return; 11786 } 11787 11788 Visit(E); 11789 } 11790 11791 // Reference types not handled in HandleValue are handled here since all 11792 // uses of references are bad, not just r-value uses. 11793 void VisitDeclRefExpr(DeclRefExpr *E) { 11794 if (isReferenceType) 11795 HandleDeclRefExpr(E); 11796 } 11797 11798 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 11799 if (E->getCastKind() == CK_LValueToRValue) { 11800 HandleValue(E->getSubExpr()); 11801 return; 11802 } 11803 11804 Inherited::VisitImplicitCastExpr(E); 11805 } 11806 11807 void VisitMemberExpr(MemberExpr *E) { 11808 if (isInitList) { 11809 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 11810 return; 11811 } 11812 11813 // Don't warn on arrays since they can be treated as pointers. 11814 if (E->getType()->canDecayToPointerType()) return; 11815 11816 // Warn when a non-static method call is followed by non-static member 11817 // field accesses, which is followed by a DeclRefExpr. 11818 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 11819 bool Warn = (MD && !MD->isStatic()); 11820 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 11821 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11822 if (!isa<FieldDecl>(ME->getMemberDecl())) 11823 Warn = false; 11824 Base = ME->getBase()->IgnoreParenImpCasts(); 11825 } 11826 11827 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 11828 if (Warn) 11829 HandleDeclRefExpr(DRE); 11830 return; 11831 } 11832 11833 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 11834 // Visit that expression. 11835 Visit(Base); 11836 } 11837 11838 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 11839 Expr *Callee = E->getCallee(); 11840 11841 if (isa<UnresolvedLookupExpr>(Callee)) 11842 return Inherited::VisitCXXOperatorCallExpr(E); 11843 11844 Visit(Callee); 11845 for (auto Arg: E->arguments()) 11846 HandleValue(Arg->IgnoreParenImpCasts()); 11847 } 11848 11849 void VisitUnaryOperator(UnaryOperator *E) { 11850 // For POD record types, addresses of its own members are well-defined. 11851 if (E->getOpcode() == UO_AddrOf && isRecordType && 11852 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 11853 if (!isPODType) 11854 HandleValue(E->getSubExpr()); 11855 return; 11856 } 11857 11858 if (E->isIncrementDecrementOp()) { 11859 HandleValue(E->getSubExpr()); 11860 return; 11861 } 11862 11863 Inherited::VisitUnaryOperator(E); 11864 } 11865 11866 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 11867 11868 void VisitCXXConstructExpr(CXXConstructExpr *E) { 11869 if (E->getConstructor()->isCopyConstructor()) { 11870 Expr *ArgExpr = E->getArg(0); 11871 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 11872 if (ILE->getNumInits() == 1) 11873 ArgExpr = ILE->getInit(0); 11874 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 11875 if (ICE->getCastKind() == CK_NoOp) 11876 ArgExpr = ICE->getSubExpr(); 11877 HandleValue(ArgExpr); 11878 return; 11879 } 11880 Inherited::VisitCXXConstructExpr(E); 11881 } 11882 11883 void VisitCallExpr(CallExpr *E) { 11884 // Treat std::move as a use. 11885 if (E->isCallToStdMove()) { 11886 HandleValue(E->getArg(0)); 11887 return; 11888 } 11889 11890 Inherited::VisitCallExpr(E); 11891 } 11892 11893 void VisitBinaryOperator(BinaryOperator *E) { 11894 if (E->isCompoundAssignmentOp()) { 11895 HandleValue(E->getLHS()); 11896 Visit(E->getRHS()); 11897 return; 11898 } 11899 11900 Inherited::VisitBinaryOperator(E); 11901 } 11902 11903 // A custom visitor for BinaryConditionalOperator is needed because the 11904 // regular visitor would check the condition and true expression separately 11905 // but both point to the same place giving duplicate diagnostics. 11906 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 11907 Visit(E->getCond()); 11908 Visit(E->getFalseExpr()); 11909 } 11910 11911 void HandleDeclRefExpr(DeclRefExpr *DRE) { 11912 Decl* ReferenceDecl = DRE->getDecl(); 11913 if (OrigDecl != ReferenceDecl) return; 11914 unsigned diag; 11915 if (isReferenceType) { 11916 diag = diag::warn_uninit_self_reference_in_reference_init; 11917 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 11918 diag = diag::warn_static_self_reference_in_init; 11919 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 11920 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 11921 DRE->getDecl()->getType()->isRecordType()) { 11922 diag = diag::warn_uninit_self_reference_in_init; 11923 } else { 11924 // Local variables will be handled by the CFG analysis. 11925 return; 11926 } 11927 11928 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE, 11929 S.PDiag(diag) 11930 << DRE->getDecl() << OrigDecl->getLocation() 11931 << DRE->getSourceRange()); 11932 } 11933 }; 11934 11935 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 11936 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 11937 bool DirectInit) { 11938 // Parameters arguments are occassionially constructed with itself, 11939 // for instance, in recursive functions. Skip them. 11940 if (isa<ParmVarDecl>(OrigDecl)) 11941 return; 11942 11943 E = E->IgnoreParens(); 11944 11945 // Skip checking T a = a where T is not a record or reference type. 11946 // Doing so is a way to silence uninitialized warnings. 11947 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 11948 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 11949 if (ICE->getCastKind() == CK_LValueToRValue) 11950 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 11951 if (DRE->getDecl() == OrigDecl) 11952 return; 11953 11954 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 11955 } 11956 } // end anonymous namespace 11957 11958 namespace { 11959 // Simple wrapper to add the name of a variable or (if no variable is 11960 // available) a DeclarationName into a diagnostic. 11961 struct VarDeclOrName { 11962 VarDecl *VDecl; 11963 DeclarationName Name; 11964 11965 friend const Sema::SemaDiagnosticBuilder & 11966 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 11967 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 11968 } 11969 }; 11970 } // end anonymous namespace 11971 11972 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 11973 DeclarationName Name, QualType Type, 11974 TypeSourceInfo *TSI, 11975 SourceRange Range, bool DirectInit, 11976 Expr *Init) { 11977 bool IsInitCapture = !VDecl; 11978 assert((!VDecl || !VDecl->isInitCapture()) && 11979 "init captures are expected to be deduced prior to initialization"); 11980 11981 VarDeclOrName VN{VDecl, Name}; 11982 11983 DeducedType *Deduced = Type->getContainedDeducedType(); 11984 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 11985 11986 // C++11 [dcl.spec.auto]p3 11987 if (!Init) { 11988 assert(VDecl && "no init for init capture deduction?"); 11989 11990 // Except for class argument deduction, and then for an initializing 11991 // declaration only, i.e. no static at class scope or extern. 11992 if (!isa<DeducedTemplateSpecializationType>(Deduced) || 11993 VDecl->hasExternalStorage() || 11994 VDecl->isStaticDataMember()) { 11995 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 11996 << VDecl->getDeclName() << Type; 11997 return QualType(); 11998 } 11999 } 12000 12001 ArrayRef<Expr*> DeduceInits; 12002 if (Init) 12003 DeduceInits = Init; 12004 12005 if (DirectInit) { 12006 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) 12007 DeduceInits = PL->exprs(); 12008 } 12009 12010 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 12011 assert(VDecl && "non-auto type for init capture deduction?"); 12012 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 12013 InitializationKind Kind = InitializationKind::CreateForInit( 12014 VDecl->getLocation(), DirectInit, Init); 12015 // FIXME: Initialization should not be taking a mutable list of inits. 12016 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 12017 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 12018 InitsCopy); 12019 } 12020 12021 if (DirectInit) { 12022 if (auto *IL = dyn_cast<InitListExpr>(Init)) 12023 DeduceInits = IL->inits(); 12024 } 12025 12026 // Deduction only works if we have exactly one source expression. 12027 if (DeduceInits.empty()) { 12028 // It isn't possible to write this directly, but it is possible to 12029 // end up in this situation with "auto x(some_pack...);" 12030 Diag(Init->getBeginLoc(), IsInitCapture 12031 ? diag::err_init_capture_no_expression 12032 : diag::err_auto_var_init_no_expression) 12033 << VN << Type << Range; 12034 return QualType(); 12035 } 12036 12037 if (DeduceInits.size() > 1) { 12038 Diag(DeduceInits[1]->getBeginLoc(), 12039 IsInitCapture ? diag::err_init_capture_multiple_expressions 12040 : diag::err_auto_var_init_multiple_expressions) 12041 << VN << Type << Range; 12042 return QualType(); 12043 } 12044 12045 Expr *DeduceInit = DeduceInits[0]; 12046 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 12047 Diag(Init->getBeginLoc(), IsInitCapture 12048 ? diag::err_init_capture_paren_braces 12049 : diag::err_auto_var_init_paren_braces) 12050 << isa<InitListExpr>(Init) << VN << Type << Range; 12051 return QualType(); 12052 } 12053 12054 // Expressions default to 'id' when we're in a debugger. 12055 bool DefaultedAnyToId = false; 12056 if (getLangOpts().DebuggerCastResultToId && 12057 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 12058 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 12059 if (Result.isInvalid()) { 12060 return QualType(); 12061 } 12062 Init = Result.get(); 12063 DefaultedAnyToId = true; 12064 } 12065 12066 // C++ [dcl.decomp]p1: 12067 // If the assignment-expression [...] has array type A and no ref-qualifier 12068 // is present, e has type cv A 12069 if (VDecl && isa<DecompositionDecl>(VDecl) && 12070 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 12071 DeduceInit->getType()->isConstantArrayType()) 12072 return Context.getQualifiedType(DeduceInit->getType(), 12073 Type.getQualifiers()); 12074 12075 QualType DeducedType; 12076 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 12077 if (!IsInitCapture) 12078 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 12079 else if (isa<InitListExpr>(Init)) 12080 Diag(Range.getBegin(), 12081 diag::err_init_capture_deduction_failure_from_init_list) 12082 << VN 12083 << (DeduceInit->getType().isNull() ? TSI->getType() 12084 : DeduceInit->getType()) 12085 << DeduceInit->getSourceRange(); 12086 else 12087 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 12088 << VN << TSI->getType() 12089 << (DeduceInit->getType().isNull() ? TSI->getType() 12090 : DeduceInit->getType()) 12091 << DeduceInit->getSourceRange(); 12092 } 12093 12094 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 12095 // 'id' instead of a specific object type prevents most of our usual 12096 // checks. 12097 // We only want to warn outside of template instantiations, though: 12098 // inside a template, the 'id' could have come from a parameter. 12099 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 12100 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 12101 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 12102 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 12103 } 12104 12105 return DeducedType; 12106 } 12107 12108 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 12109 Expr *Init) { 12110 assert(!Init || !Init->containsErrors()); 12111 QualType DeducedType = deduceVarTypeFromInitializer( 12112 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 12113 VDecl->getSourceRange(), DirectInit, Init); 12114 if (DeducedType.isNull()) { 12115 VDecl->setInvalidDecl(); 12116 return true; 12117 } 12118 12119 VDecl->setType(DeducedType); 12120 assert(VDecl->isLinkageValid()); 12121 12122 // In ARC, infer lifetime. 12123 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 12124 VDecl->setInvalidDecl(); 12125 12126 if (getLangOpts().OpenCL) 12127 deduceOpenCLAddressSpace(VDecl); 12128 12129 // If this is a redeclaration, check that the type we just deduced matches 12130 // the previously declared type. 12131 if (VarDecl *Old = VDecl->getPreviousDecl()) { 12132 // We never need to merge the type, because we cannot form an incomplete 12133 // array of auto, nor deduce such a type. 12134 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 12135 } 12136 12137 // Check the deduced type is valid for a variable declaration. 12138 CheckVariableDeclarationType(VDecl); 12139 return VDecl->isInvalidDecl(); 12140 } 12141 12142 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init, 12143 SourceLocation Loc) { 12144 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init)) 12145 Init = EWC->getSubExpr(); 12146 12147 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 12148 Init = CE->getSubExpr(); 12149 12150 QualType InitType = Init->getType(); 12151 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12152 InitType.hasNonTrivialToPrimitiveCopyCUnion()) && 12153 "shouldn't be called if type doesn't have a non-trivial C struct"); 12154 if (auto *ILE = dyn_cast<InitListExpr>(Init)) { 12155 for (auto I : ILE->inits()) { 12156 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() && 12157 !I->getType().hasNonTrivialToPrimitiveCopyCUnion()) 12158 continue; 12159 SourceLocation SL = I->getExprLoc(); 12160 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc); 12161 } 12162 return; 12163 } 12164 12165 if (isa<ImplicitValueInitExpr>(Init)) { 12166 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 12167 checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject, 12168 NTCUK_Init); 12169 } else { 12170 // Assume all other explicit initializers involving copying some existing 12171 // object. 12172 // TODO: ignore any explicit initializers where we can guarantee 12173 // copy-elision. 12174 if (InitType.hasNonTrivialToPrimitiveCopyCUnion()) 12175 checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy); 12176 } 12177 } 12178 12179 namespace { 12180 12181 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) { 12182 // Ignore unavailable fields. A field can be marked as unavailable explicitly 12183 // in the source code or implicitly by the compiler if it is in a union 12184 // defined in a system header and has non-trivial ObjC ownership 12185 // qualifications. We don't want those fields to participate in determining 12186 // whether the containing union is non-trivial. 12187 return FD->hasAttr<UnavailableAttr>(); 12188 } 12189 12190 struct DiagNonTrivalCUnionDefaultInitializeVisitor 12191 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 12192 void> { 12193 using Super = 12194 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 12195 void>; 12196 12197 DiagNonTrivalCUnionDefaultInitializeVisitor( 12198 QualType OrigTy, SourceLocation OrigLoc, 12199 Sema::NonTrivialCUnionContext UseContext, Sema &S) 12200 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 12201 12202 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT, 12203 const FieldDecl *FD, bool InNonTrivialUnion) { 12204 if (const auto *AT = S.Context.getAsArrayType(QT)) 12205 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 12206 InNonTrivialUnion); 12207 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion); 12208 } 12209 12210 void visitARCStrong(QualType QT, const FieldDecl *FD, 12211 bool InNonTrivialUnion) { 12212 if (InNonTrivialUnion) 12213 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12214 << 1 << 0 << QT << FD->getName(); 12215 } 12216 12217 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12218 if (InNonTrivialUnion) 12219 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12220 << 1 << 0 << QT << FD->getName(); 12221 } 12222 12223 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12224 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 12225 if (RD->isUnion()) { 12226 if (OrigLoc.isValid()) { 12227 bool IsUnion = false; 12228 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 12229 IsUnion = OrigRD->isUnion(); 12230 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 12231 << 0 << OrigTy << IsUnion << UseContext; 12232 // Reset OrigLoc so that this diagnostic is emitted only once. 12233 OrigLoc = SourceLocation(); 12234 } 12235 InNonTrivialUnion = true; 12236 } 12237 12238 if (InNonTrivialUnion) 12239 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 12240 << 0 << 0 << QT.getUnqualifiedType() << ""; 12241 12242 for (const FieldDecl *FD : RD->fields()) 12243 if (!shouldIgnoreForRecordTriviality(FD)) 12244 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 12245 } 12246 12247 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 12248 12249 // The non-trivial C union type or the struct/union type that contains a 12250 // non-trivial C union. 12251 QualType OrigTy; 12252 SourceLocation OrigLoc; 12253 Sema::NonTrivialCUnionContext UseContext; 12254 Sema &S; 12255 }; 12256 12257 struct DiagNonTrivalCUnionDestructedTypeVisitor 12258 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> { 12259 using Super = 12260 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>; 12261 12262 DiagNonTrivalCUnionDestructedTypeVisitor( 12263 QualType OrigTy, SourceLocation OrigLoc, 12264 Sema::NonTrivialCUnionContext UseContext, Sema &S) 12265 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 12266 12267 void visitWithKind(QualType::DestructionKind DK, QualType QT, 12268 const FieldDecl *FD, bool InNonTrivialUnion) { 12269 if (const auto *AT = S.Context.getAsArrayType(QT)) 12270 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 12271 InNonTrivialUnion); 12272 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion); 12273 } 12274 12275 void visitARCStrong(QualType QT, const FieldDecl *FD, 12276 bool InNonTrivialUnion) { 12277 if (InNonTrivialUnion) 12278 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12279 << 1 << 1 << QT << FD->getName(); 12280 } 12281 12282 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12283 if (InNonTrivialUnion) 12284 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12285 << 1 << 1 << QT << FD->getName(); 12286 } 12287 12288 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12289 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 12290 if (RD->isUnion()) { 12291 if (OrigLoc.isValid()) { 12292 bool IsUnion = false; 12293 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 12294 IsUnion = OrigRD->isUnion(); 12295 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 12296 << 1 << OrigTy << IsUnion << UseContext; 12297 // Reset OrigLoc so that this diagnostic is emitted only once. 12298 OrigLoc = SourceLocation(); 12299 } 12300 InNonTrivialUnion = true; 12301 } 12302 12303 if (InNonTrivialUnion) 12304 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 12305 << 0 << 1 << QT.getUnqualifiedType() << ""; 12306 12307 for (const FieldDecl *FD : RD->fields()) 12308 if (!shouldIgnoreForRecordTriviality(FD)) 12309 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 12310 } 12311 12312 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 12313 void visitCXXDestructor(QualType QT, const FieldDecl *FD, 12314 bool InNonTrivialUnion) {} 12315 12316 // The non-trivial C union type or the struct/union type that contains a 12317 // non-trivial C union. 12318 QualType OrigTy; 12319 SourceLocation OrigLoc; 12320 Sema::NonTrivialCUnionContext UseContext; 12321 Sema &S; 12322 }; 12323 12324 struct DiagNonTrivalCUnionCopyVisitor 12325 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> { 12326 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>; 12327 12328 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc, 12329 Sema::NonTrivialCUnionContext UseContext, 12330 Sema &S) 12331 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 12332 12333 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT, 12334 const FieldDecl *FD, bool InNonTrivialUnion) { 12335 if (const auto *AT = S.Context.getAsArrayType(QT)) 12336 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 12337 InNonTrivialUnion); 12338 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion); 12339 } 12340 12341 void visitARCStrong(QualType QT, const FieldDecl *FD, 12342 bool InNonTrivialUnion) { 12343 if (InNonTrivialUnion) 12344 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12345 << 1 << 2 << QT << FD->getName(); 12346 } 12347 12348 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12349 if (InNonTrivialUnion) 12350 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12351 << 1 << 2 << QT << FD->getName(); 12352 } 12353 12354 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12355 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 12356 if (RD->isUnion()) { 12357 if (OrigLoc.isValid()) { 12358 bool IsUnion = false; 12359 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 12360 IsUnion = OrigRD->isUnion(); 12361 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 12362 << 2 << OrigTy << IsUnion << UseContext; 12363 // Reset OrigLoc so that this diagnostic is emitted only once. 12364 OrigLoc = SourceLocation(); 12365 } 12366 InNonTrivialUnion = true; 12367 } 12368 12369 if (InNonTrivialUnion) 12370 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 12371 << 0 << 2 << QT.getUnqualifiedType() << ""; 12372 12373 for (const FieldDecl *FD : RD->fields()) 12374 if (!shouldIgnoreForRecordTriviality(FD)) 12375 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 12376 } 12377 12378 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT, 12379 const FieldDecl *FD, bool InNonTrivialUnion) {} 12380 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 12381 void visitVolatileTrivial(QualType QT, const FieldDecl *FD, 12382 bool InNonTrivialUnion) {} 12383 12384 // The non-trivial C union type or the struct/union type that contains a 12385 // non-trivial C union. 12386 QualType OrigTy; 12387 SourceLocation OrigLoc; 12388 Sema::NonTrivialCUnionContext UseContext; 12389 Sema &S; 12390 }; 12391 12392 } // namespace 12393 12394 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc, 12395 NonTrivialCUnionContext UseContext, 12396 unsigned NonTrivialKind) { 12397 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12398 QT.hasNonTrivialToPrimitiveDestructCUnion() || 12399 QT.hasNonTrivialToPrimitiveCopyCUnion()) && 12400 "shouldn't be called if type doesn't have a non-trivial C union"); 12401 12402 if ((NonTrivialKind & NTCUK_Init) && 12403 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 12404 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this) 12405 .visit(QT, nullptr, false); 12406 if ((NonTrivialKind & NTCUK_Destruct) && 12407 QT.hasNonTrivialToPrimitiveDestructCUnion()) 12408 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this) 12409 .visit(QT, nullptr, false); 12410 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion()) 12411 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this) 12412 .visit(QT, nullptr, false); 12413 } 12414 12415 /// AddInitializerToDecl - Adds the initializer Init to the 12416 /// declaration dcl. If DirectInit is true, this is C++ direct 12417 /// initialization rather than copy initialization. 12418 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 12419 // If there is no declaration, there was an error parsing it. Just ignore 12420 // the initializer. 12421 if (!RealDecl || RealDecl->isInvalidDecl()) { 12422 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 12423 return; 12424 } 12425 12426 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 12427 // Pure-specifiers are handled in ActOnPureSpecifier. 12428 Diag(Method->getLocation(), diag::err_member_function_initialization) 12429 << Method->getDeclName() << Init->getSourceRange(); 12430 Method->setInvalidDecl(); 12431 return; 12432 } 12433 12434 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 12435 if (!VDecl) { 12436 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 12437 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 12438 RealDecl->setInvalidDecl(); 12439 return; 12440 } 12441 12442 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 12443 if (VDecl->getType()->isUndeducedType()) { 12444 // Attempt typo correction early so that the type of the init expression can 12445 // be deduced based on the chosen correction if the original init contains a 12446 // TypoExpr. 12447 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 12448 if (!Res.isUsable()) { 12449 // There are unresolved typos in Init, just drop them. 12450 // FIXME: improve the recovery strategy to preserve the Init. 12451 RealDecl->setInvalidDecl(); 12452 return; 12453 } 12454 if (Res.get()->containsErrors()) { 12455 // Invalidate the decl as we don't know the type for recovery-expr yet. 12456 RealDecl->setInvalidDecl(); 12457 VDecl->setInit(Res.get()); 12458 return; 12459 } 12460 Init = Res.get(); 12461 12462 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 12463 return; 12464 } 12465 12466 // dllimport cannot be used on variable definitions. 12467 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 12468 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 12469 VDecl->setInvalidDecl(); 12470 return; 12471 } 12472 12473 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 12474 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 12475 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 12476 VDecl->setInvalidDecl(); 12477 return; 12478 } 12479 12480 if (!VDecl->getType()->isDependentType()) { 12481 // A definition must end up with a complete type, which means it must be 12482 // complete with the restriction that an array type might be completed by 12483 // the initializer; note that later code assumes this restriction. 12484 QualType BaseDeclType = VDecl->getType(); 12485 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 12486 BaseDeclType = Array->getElementType(); 12487 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 12488 diag::err_typecheck_decl_incomplete_type)) { 12489 RealDecl->setInvalidDecl(); 12490 return; 12491 } 12492 12493 // The variable can not have an abstract class type. 12494 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 12495 diag::err_abstract_type_in_decl, 12496 AbstractVariableType)) 12497 VDecl->setInvalidDecl(); 12498 } 12499 12500 // If adding the initializer will turn this declaration into a definition, 12501 // and we already have a definition for this variable, diagnose or otherwise 12502 // handle the situation. 12503 if (VarDecl *Def = VDecl->getDefinition()) 12504 if (Def != VDecl && 12505 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 12506 !VDecl->isThisDeclarationADemotedDefinition() && 12507 checkVarDeclRedefinition(Def, VDecl)) 12508 return; 12509 12510 if (getLangOpts().CPlusPlus) { 12511 // C++ [class.static.data]p4 12512 // If a static data member is of const integral or const 12513 // enumeration type, its declaration in the class definition can 12514 // specify a constant-initializer which shall be an integral 12515 // constant expression (5.19). In that case, the member can appear 12516 // in integral constant expressions. The member shall still be 12517 // defined in a namespace scope if it is used in the program and the 12518 // namespace scope definition shall not contain an initializer. 12519 // 12520 // We already performed a redefinition check above, but for static 12521 // data members we also need to check whether there was an in-class 12522 // declaration with an initializer. 12523 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 12524 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 12525 << VDecl->getDeclName(); 12526 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 12527 diag::note_previous_initializer) 12528 << 0; 12529 return; 12530 } 12531 12532 if (VDecl->hasLocalStorage()) 12533 setFunctionHasBranchProtectedScope(); 12534 12535 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 12536 VDecl->setInvalidDecl(); 12537 return; 12538 } 12539 } 12540 12541 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 12542 // a kernel function cannot be initialized." 12543 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 12544 Diag(VDecl->getLocation(), diag::err_local_cant_init); 12545 VDecl->setInvalidDecl(); 12546 return; 12547 } 12548 12549 // The LoaderUninitialized attribute acts as a definition (of undef). 12550 if (VDecl->hasAttr<LoaderUninitializedAttr>()) { 12551 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init); 12552 VDecl->setInvalidDecl(); 12553 return; 12554 } 12555 12556 // Get the decls type and save a reference for later, since 12557 // CheckInitializerTypes may change it. 12558 QualType DclT = VDecl->getType(), SavT = DclT; 12559 12560 // Expressions default to 'id' when we're in a debugger 12561 // and we are assigning it to a variable of Objective-C pointer type. 12562 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 12563 Init->getType() == Context.UnknownAnyTy) { 12564 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 12565 if (Result.isInvalid()) { 12566 VDecl->setInvalidDecl(); 12567 return; 12568 } 12569 Init = Result.get(); 12570 } 12571 12572 // Perform the initialization. 12573 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 12574 if (!VDecl->isInvalidDecl()) { 12575 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 12576 InitializationKind Kind = InitializationKind::CreateForInit( 12577 VDecl->getLocation(), DirectInit, Init); 12578 12579 MultiExprArg Args = Init; 12580 if (CXXDirectInit) 12581 Args = MultiExprArg(CXXDirectInit->getExprs(), 12582 CXXDirectInit->getNumExprs()); 12583 12584 // Try to correct any TypoExprs in the initialization arguments. 12585 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 12586 ExprResult Res = CorrectDelayedTyposInExpr( 12587 Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true, 12588 [this, Entity, Kind](Expr *E) { 12589 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 12590 return Init.Failed() ? ExprError() : E; 12591 }); 12592 if (Res.isInvalid()) { 12593 VDecl->setInvalidDecl(); 12594 } else if (Res.get() != Args[Idx]) { 12595 Args[Idx] = Res.get(); 12596 } 12597 } 12598 if (VDecl->isInvalidDecl()) 12599 return; 12600 12601 InitializationSequence InitSeq(*this, Entity, Kind, Args, 12602 /*TopLevelOfInitList=*/false, 12603 /*TreatUnavailableAsInvalid=*/false); 12604 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 12605 if (Result.isInvalid()) { 12606 // If the provided initializer fails to initialize the var decl, 12607 // we attach a recovery expr for better recovery. 12608 auto RecoveryExpr = 12609 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args); 12610 if (RecoveryExpr.get()) 12611 VDecl->setInit(RecoveryExpr.get()); 12612 return; 12613 } 12614 12615 Init = Result.getAs<Expr>(); 12616 } 12617 12618 // Check for self-references within variable initializers. 12619 // Variables declared within a function/method body (except for references) 12620 // are handled by a dataflow analysis. 12621 // This is undefined behavior in C++, but valid in C. 12622 if (getLangOpts().CPlusPlus) 12623 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 12624 VDecl->getType()->isReferenceType()) 12625 CheckSelfReference(*this, RealDecl, Init, DirectInit); 12626 12627 // If the type changed, it means we had an incomplete type that was 12628 // completed by the initializer. For example: 12629 // int ary[] = { 1, 3, 5 }; 12630 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 12631 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 12632 VDecl->setType(DclT); 12633 12634 if (!VDecl->isInvalidDecl()) { 12635 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 12636 12637 if (VDecl->hasAttr<BlocksAttr>()) 12638 checkRetainCycles(VDecl, Init); 12639 12640 // It is safe to assign a weak reference into a strong variable. 12641 // Although this code can still have problems: 12642 // id x = self.weakProp; 12643 // id y = self.weakProp; 12644 // we do not warn to warn spuriously when 'x' and 'y' are on separate 12645 // paths through the function. This should be revisited if 12646 // -Wrepeated-use-of-weak is made flow-sensitive. 12647 if (FunctionScopeInfo *FSI = getCurFunction()) 12648 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 12649 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 12650 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 12651 Init->getBeginLoc())) 12652 FSI->markSafeWeakUse(Init); 12653 } 12654 12655 // The initialization is usually a full-expression. 12656 // 12657 // FIXME: If this is a braced initialization of an aggregate, it is not 12658 // an expression, and each individual field initializer is a separate 12659 // full-expression. For instance, in: 12660 // 12661 // struct Temp { ~Temp(); }; 12662 // struct S { S(Temp); }; 12663 // struct T { S a, b; } t = { Temp(), Temp() } 12664 // 12665 // we should destroy the first Temp before constructing the second. 12666 ExprResult Result = 12667 ActOnFinishFullExpr(Init, VDecl->getLocation(), 12668 /*DiscardedValue*/ false, VDecl->isConstexpr()); 12669 if (Result.isInvalid()) { 12670 VDecl->setInvalidDecl(); 12671 return; 12672 } 12673 Init = Result.get(); 12674 12675 // Attach the initializer to the decl. 12676 VDecl->setInit(Init); 12677 12678 if (VDecl->isLocalVarDecl()) { 12679 // Don't check the initializer if the declaration is malformed. 12680 if (VDecl->isInvalidDecl()) { 12681 // do nothing 12682 12683 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 12684 // This is true even in C++ for OpenCL. 12685 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 12686 CheckForConstantInitializer(Init, DclT); 12687 12688 // Otherwise, C++ does not restrict the initializer. 12689 } else if (getLangOpts().CPlusPlus) { 12690 // do nothing 12691 12692 // C99 6.7.8p4: All the expressions in an initializer for an object that has 12693 // static storage duration shall be constant expressions or string literals. 12694 } else if (VDecl->getStorageClass() == SC_Static) { 12695 CheckForConstantInitializer(Init, DclT); 12696 12697 // C89 is stricter than C99 for aggregate initializers. 12698 // C89 6.5.7p3: All the expressions [...] in an initializer list 12699 // for an object that has aggregate or union type shall be 12700 // constant expressions. 12701 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 12702 isa<InitListExpr>(Init)) { 12703 const Expr *Culprit; 12704 if (!Init->isConstantInitializer(Context, false, &Culprit)) { 12705 Diag(Culprit->getExprLoc(), 12706 diag::ext_aggregate_init_not_constant) 12707 << Culprit->getSourceRange(); 12708 } 12709 } 12710 12711 if (auto *E = dyn_cast<ExprWithCleanups>(Init)) 12712 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens())) 12713 if (VDecl->hasLocalStorage()) 12714 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 12715 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 12716 VDecl->getLexicalDeclContext()->isRecord()) { 12717 // This is an in-class initialization for a static data member, e.g., 12718 // 12719 // struct S { 12720 // static const int value = 17; 12721 // }; 12722 12723 // C++ [class.mem]p4: 12724 // A member-declarator can contain a constant-initializer only 12725 // if it declares a static member (9.4) of const integral or 12726 // const enumeration type, see 9.4.2. 12727 // 12728 // C++11 [class.static.data]p3: 12729 // If a non-volatile non-inline const static data member is of integral 12730 // or enumeration type, its declaration in the class definition can 12731 // specify a brace-or-equal-initializer in which every initializer-clause 12732 // that is an assignment-expression is a constant expression. A static 12733 // data member of literal type can be declared in the class definition 12734 // with the constexpr specifier; if so, its declaration shall specify a 12735 // brace-or-equal-initializer in which every initializer-clause that is 12736 // an assignment-expression is a constant expression. 12737 12738 // Do nothing on dependent types. 12739 if (DclT->isDependentType()) { 12740 12741 // Allow any 'static constexpr' members, whether or not they are of literal 12742 // type. We separately check that every constexpr variable is of literal 12743 // type. 12744 } else if (VDecl->isConstexpr()) { 12745 12746 // Require constness. 12747 } else if (!DclT.isConstQualified()) { 12748 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 12749 << Init->getSourceRange(); 12750 VDecl->setInvalidDecl(); 12751 12752 // We allow integer constant expressions in all cases. 12753 } else if (DclT->isIntegralOrEnumerationType()) { 12754 // Check whether the expression is a constant expression. 12755 SourceLocation Loc; 12756 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 12757 // In C++11, a non-constexpr const static data member with an 12758 // in-class initializer cannot be volatile. 12759 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 12760 else if (Init->isValueDependent()) 12761 ; // Nothing to check. 12762 else if (Init->isIntegerConstantExpr(Context, &Loc)) 12763 ; // Ok, it's an ICE! 12764 else if (Init->getType()->isScopedEnumeralType() && 12765 Init->isCXX11ConstantExpr(Context)) 12766 ; // Ok, it is a scoped-enum constant expression. 12767 else if (Init->isEvaluatable(Context)) { 12768 // If we can constant fold the initializer through heroics, accept it, 12769 // but report this as a use of an extension for -pedantic. 12770 Diag(Loc, diag::ext_in_class_initializer_non_constant) 12771 << Init->getSourceRange(); 12772 } else { 12773 // Otherwise, this is some crazy unknown case. Report the issue at the 12774 // location provided by the isIntegerConstantExpr failed check. 12775 Diag(Loc, diag::err_in_class_initializer_non_constant) 12776 << Init->getSourceRange(); 12777 VDecl->setInvalidDecl(); 12778 } 12779 12780 // We allow foldable floating-point constants as an extension. 12781 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 12782 // In C++98, this is a GNU extension. In C++11, it is not, but we support 12783 // it anyway and provide a fixit to add the 'constexpr'. 12784 if (getLangOpts().CPlusPlus11) { 12785 Diag(VDecl->getLocation(), 12786 diag::ext_in_class_initializer_float_type_cxx11) 12787 << DclT << Init->getSourceRange(); 12788 Diag(VDecl->getBeginLoc(), 12789 diag::note_in_class_initializer_float_type_cxx11) 12790 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12791 } else { 12792 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 12793 << DclT << Init->getSourceRange(); 12794 12795 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 12796 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 12797 << Init->getSourceRange(); 12798 VDecl->setInvalidDecl(); 12799 } 12800 } 12801 12802 // Suggest adding 'constexpr' in C++11 for literal types. 12803 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 12804 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 12805 << DclT << Init->getSourceRange() 12806 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12807 VDecl->setConstexpr(true); 12808 12809 } else { 12810 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 12811 << DclT << Init->getSourceRange(); 12812 VDecl->setInvalidDecl(); 12813 } 12814 } else if (VDecl->isFileVarDecl()) { 12815 // In C, extern is typically used to avoid tentative definitions when 12816 // declaring variables in headers, but adding an intializer makes it a 12817 // definition. This is somewhat confusing, so GCC and Clang both warn on it. 12818 // In C++, extern is often used to give implictly static const variables 12819 // external linkage, so don't warn in that case. If selectany is present, 12820 // this might be header code intended for C and C++ inclusion, so apply the 12821 // C++ rules. 12822 if (VDecl->getStorageClass() == SC_Extern && 12823 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 12824 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 12825 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 12826 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 12827 Diag(VDecl->getLocation(), diag::warn_extern_init); 12828 12829 // In Microsoft C++ mode, a const variable defined in namespace scope has 12830 // external linkage by default if the variable is declared with 12831 // __declspec(dllexport). 12832 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 12833 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() && 12834 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition()) 12835 VDecl->setStorageClass(SC_Extern); 12836 12837 // C99 6.7.8p4. All file scoped initializers need to be constant. 12838 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 12839 CheckForConstantInitializer(Init, DclT); 12840 } 12841 12842 QualType InitType = Init->getType(); 12843 if (!InitType.isNull() && 12844 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12845 InitType.hasNonTrivialToPrimitiveCopyCUnion())) 12846 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc()); 12847 12848 // We will represent direct-initialization similarly to copy-initialization: 12849 // int x(1); -as-> int x = 1; 12850 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 12851 // 12852 // Clients that want to distinguish between the two forms, can check for 12853 // direct initializer using VarDecl::getInitStyle(). 12854 // A major benefit is that clients that don't particularly care about which 12855 // exactly form was it (like the CodeGen) can handle both cases without 12856 // special case code. 12857 12858 // C++ 8.5p11: 12859 // The form of initialization (using parentheses or '=') is generally 12860 // insignificant, but does matter when the entity being initialized has a 12861 // class type. 12862 if (CXXDirectInit) { 12863 assert(DirectInit && "Call-style initializer must be direct init."); 12864 VDecl->setInitStyle(VarDecl::CallInit); 12865 } else if (DirectInit) { 12866 // This must be list-initialization. No other way is direct-initialization. 12867 VDecl->setInitStyle(VarDecl::ListInit); 12868 } 12869 12870 if (LangOpts.OpenMP && 12871 (LangOpts.OpenMPIsDevice || !LangOpts.OMPTargetTriples.empty()) && 12872 VDecl->isFileVarDecl()) 12873 DeclsToCheckForDeferredDiags.insert(VDecl); 12874 CheckCompleteVariableDeclaration(VDecl); 12875 } 12876 12877 /// ActOnInitializerError - Given that there was an error parsing an 12878 /// initializer for the given declaration, try to at least re-establish 12879 /// invariants such as whether a variable's type is either dependent or 12880 /// complete. 12881 void Sema::ActOnInitializerError(Decl *D) { 12882 // Our main concern here is re-establishing invariants like "a 12883 // variable's type is either dependent or complete". 12884 if (!D || D->isInvalidDecl()) return; 12885 12886 VarDecl *VD = dyn_cast<VarDecl>(D); 12887 if (!VD) return; 12888 12889 // Bindings are not usable if we can't make sense of the initializer. 12890 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 12891 for (auto *BD : DD->bindings()) 12892 BD->setInvalidDecl(); 12893 12894 // Auto types are meaningless if we can't make sense of the initializer. 12895 if (VD->getType()->isUndeducedType()) { 12896 D->setInvalidDecl(); 12897 return; 12898 } 12899 12900 QualType Ty = VD->getType(); 12901 if (Ty->isDependentType()) return; 12902 12903 // Require a complete type. 12904 if (RequireCompleteType(VD->getLocation(), 12905 Context.getBaseElementType(Ty), 12906 diag::err_typecheck_decl_incomplete_type)) { 12907 VD->setInvalidDecl(); 12908 return; 12909 } 12910 12911 // Require a non-abstract type. 12912 if (RequireNonAbstractType(VD->getLocation(), Ty, 12913 diag::err_abstract_type_in_decl, 12914 AbstractVariableType)) { 12915 VD->setInvalidDecl(); 12916 return; 12917 } 12918 12919 // Don't bother complaining about constructors or destructors, 12920 // though. 12921 } 12922 12923 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 12924 // If there is no declaration, there was an error parsing it. Just ignore it. 12925 if (!RealDecl) 12926 return; 12927 12928 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 12929 QualType Type = Var->getType(); 12930 12931 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 12932 if (isa<DecompositionDecl>(RealDecl)) { 12933 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 12934 Var->setInvalidDecl(); 12935 return; 12936 } 12937 12938 if (Type->isUndeducedType() && 12939 DeduceVariableDeclarationType(Var, false, nullptr)) 12940 return; 12941 12942 // C++11 [class.static.data]p3: A static data member can be declared with 12943 // the constexpr specifier; if so, its declaration shall specify 12944 // a brace-or-equal-initializer. 12945 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 12946 // the definition of a variable [...] or the declaration of a static data 12947 // member. 12948 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 12949 !Var->isThisDeclarationADemotedDefinition()) { 12950 if (Var->isStaticDataMember()) { 12951 // C++1z removes the relevant rule; the in-class declaration is always 12952 // a definition there. 12953 if (!getLangOpts().CPlusPlus17 && 12954 !Context.getTargetInfo().getCXXABI().isMicrosoft()) { 12955 Diag(Var->getLocation(), 12956 diag::err_constexpr_static_mem_var_requires_init) 12957 << Var; 12958 Var->setInvalidDecl(); 12959 return; 12960 } 12961 } else { 12962 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 12963 Var->setInvalidDecl(); 12964 return; 12965 } 12966 } 12967 12968 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 12969 // be initialized. 12970 if (!Var->isInvalidDecl() && 12971 Var->getType().getAddressSpace() == LangAS::opencl_constant && 12972 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 12973 bool HasConstExprDefaultConstructor = false; 12974 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) { 12975 for (auto *Ctor : RD->ctors()) { 12976 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 && 12977 Ctor->getMethodQualifiers().getAddressSpace() == 12978 LangAS::opencl_constant) { 12979 HasConstExprDefaultConstructor = true; 12980 } 12981 } 12982 } 12983 if (!HasConstExprDefaultConstructor) { 12984 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 12985 Var->setInvalidDecl(); 12986 return; 12987 } 12988 } 12989 12990 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) { 12991 if (Var->getStorageClass() == SC_Extern) { 12992 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl) 12993 << Var; 12994 Var->setInvalidDecl(); 12995 return; 12996 } 12997 if (RequireCompleteType(Var->getLocation(), Var->getType(), 12998 diag::err_typecheck_decl_incomplete_type)) { 12999 Var->setInvalidDecl(); 13000 return; 13001 } 13002 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) { 13003 if (!RD->hasTrivialDefaultConstructor()) { 13004 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor); 13005 Var->setInvalidDecl(); 13006 return; 13007 } 13008 } 13009 // The declaration is unitialized, no need for further checks. 13010 return; 13011 } 13012 13013 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition(); 13014 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly && 13015 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 13016 checkNonTrivialCUnion(Var->getType(), Var->getLocation(), 13017 NTCUC_DefaultInitializedObject, NTCUK_Init); 13018 13019 13020 switch (DefKind) { 13021 case VarDecl::Definition: 13022 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 13023 break; 13024 13025 // We have an out-of-line definition of a static data member 13026 // that has an in-class initializer, so we type-check this like 13027 // a declaration. 13028 // 13029 LLVM_FALLTHROUGH; 13030 13031 case VarDecl::DeclarationOnly: 13032 // It's only a declaration. 13033 13034 // Block scope. C99 6.7p7: If an identifier for an object is 13035 // declared with no linkage (C99 6.2.2p6), the type for the 13036 // object shall be complete. 13037 if (!Type->isDependentType() && Var->isLocalVarDecl() && 13038 !Var->hasLinkage() && !Var->isInvalidDecl() && 13039 RequireCompleteType(Var->getLocation(), Type, 13040 diag::err_typecheck_decl_incomplete_type)) 13041 Var->setInvalidDecl(); 13042 13043 // Make sure that the type is not abstract. 13044 if (!Type->isDependentType() && !Var->isInvalidDecl() && 13045 RequireNonAbstractType(Var->getLocation(), Type, 13046 diag::err_abstract_type_in_decl, 13047 AbstractVariableType)) 13048 Var->setInvalidDecl(); 13049 if (!Type->isDependentType() && !Var->isInvalidDecl() && 13050 Var->getStorageClass() == SC_PrivateExtern) { 13051 Diag(Var->getLocation(), diag::warn_private_extern); 13052 Diag(Var->getLocation(), diag::note_private_extern); 13053 } 13054 13055 if (Context.getTargetInfo().allowDebugInfoForExternalRef() && 13056 !Var->isInvalidDecl() && !getLangOpts().CPlusPlus) 13057 ExternalDeclarations.push_back(Var); 13058 13059 return; 13060 13061 case VarDecl::TentativeDefinition: 13062 // File scope. C99 6.9.2p2: A declaration of an identifier for an 13063 // object that has file scope without an initializer, and without a 13064 // storage-class specifier or with the storage-class specifier "static", 13065 // constitutes a tentative definition. Note: A tentative definition with 13066 // external linkage is valid (C99 6.2.2p5). 13067 if (!Var->isInvalidDecl()) { 13068 if (const IncompleteArrayType *ArrayT 13069 = Context.getAsIncompleteArrayType(Type)) { 13070 if (RequireCompleteSizedType( 13071 Var->getLocation(), ArrayT->getElementType(), 13072 diag::err_array_incomplete_or_sizeless_type)) 13073 Var->setInvalidDecl(); 13074 } else if (Var->getStorageClass() == SC_Static) { 13075 // C99 6.9.2p3: If the declaration of an identifier for an object is 13076 // a tentative definition and has internal linkage (C99 6.2.2p3), the 13077 // declared type shall not be an incomplete type. 13078 // NOTE: code such as the following 13079 // static struct s; 13080 // struct s { int a; }; 13081 // is accepted by gcc. Hence here we issue a warning instead of 13082 // an error and we do not invalidate the static declaration. 13083 // NOTE: to avoid multiple warnings, only check the first declaration. 13084 if (Var->isFirstDecl()) 13085 RequireCompleteType(Var->getLocation(), Type, 13086 diag::ext_typecheck_decl_incomplete_type); 13087 } 13088 } 13089 13090 // Record the tentative definition; we're done. 13091 if (!Var->isInvalidDecl()) 13092 TentativeDefinitions.push_back(Var); 13093 return; 13094 } 13095 13096 // Provide a specific diagnostic for uninitialized variable 13097 // definitions with incomplete array type. 13098 if (Type->isIncompleteArrayType()) { 13099 Diag(Var->getLocation(), 13100 diag::err_typecheck_incomplete_array_needs_initializer); 13101 Var->setInvalidDecl(); 13102 return; 13103 } 13104 13105 // Provide a specific diagnostic for uninitialized variable 13106 // definitions with reference type. 13107 if (Type->isReferenceType()) { 13108 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 13109 << Var << SourceRange(Var->getLocation(), Var->getLocation()); 13110 Var->setInvalidDecl(); 13111 return; 13112 } 13113 13114 // Do not attempt to type-check the default initializer for a 13115 // variable with dependent type. 13116 if (Type->isDependentType()) 13117 return; 13118 13119 if (Var->isInvalidDecl()) 13120 return; 13121 13122 if (!Var->hasAttr<AliasAttr>()) { 13123 if (RequireCompleteType(Var->getLocation(), 13124 Context.getBaseElementType(Type), 13125 diag::err_typecheck_decl_incomplete_type)) { 13126 Var->setInvalidDecl(); 13127 return; 13128 } 13129 } else { 13130 return; 13131 } 13132 13133 // The variable can not have an abstract class type. 13134 if (RequireNonAbstractType(Var->getLocation(), Type, 13135 diag::err_abstract_type_in_decl, 13136 AbstractVariableType)) { 13137 Var->setInvalidDecl(); 13138 return; 13139 } 13140 13141 // Check for jumps past the implicit initializer. C++0x 13142 // clarifies that this applies to a "variable with automatic 13143 // storage duration", not a "local variable". 13144 // C++11 [stmt.dcl]p3 13145 // A program that jumps from a point where a variable with automatic 13146 // storage duration is not in scope to a point where it is in scope is 13147 // ill-formed unless the variable has scalar type, class type with a 13148 // trivial default constructor and a trivial destructor, a cv-qualified 13149 // version of one of these types, or an array of one of the preceding 13150 // types and is declared without an initializer. 13151 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 13152 if (const RecordType *Record 13153 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 13154 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 13155 // Mark the function (if we're in one) for further checking even if the 13156 // looser rules of C++11 do not require such checks, so that we can 13157 // diagnose incompatibilities with C++98. 13158 if (!CXXRecord->isPOD()) 13159 setFunctionHasBranchProtectedScope(); 13160 } 13161 } 13162 // In OpenCL, we can't initialize objects in the __local address space, 13163 // even implicitly, so don't synthesize an implicit initializer. 13164 if (getLangOpts().OpenCL && 13165 Var->getType().getAddressSpace() == LangAS::opencl_local) 13166 return; 13167 // C++03 [dcl.init]p9: 13168 // If no initializer is specified for an object, and the 13169 // object is of (possibly cv-qualified) non-POD class type (or 13170 // array thereof), the object shall be default-initialized; if 13171 // the object is of const-qualified type, the underlying class 13172 // type shall have a user-declared default 13173 // constructor. Otherwise, if no initializer is specified for 13174 // a non- static object, the object and its subobjects, if 13175 // any, have an indeterminate initial value); if the object 13176 // or any of its subobjects are of const-qualified type, the 13177 // program is ill-formed. 13178 // C++0x [dcl.init]p11: 13179 // If no initializer is specified for an object, the object is 13180 // default-initialized; [...]. 13181 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 13182 InitializationKind Kind 13183 = InitializationKind::CreateDefault(Var->getLocation()); 13184 13185 InitializationSequence InitSeq(*this, Entity, Kind, None); 13186 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 13187 13188 if (Init.get()) { 13189 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 13190 // This is important for template substitution. 13191 Var->setInitStyle(VarDecl::CallInit); 13192 } else if (Init.isInvalid()) { 13193 // If default-init fails, attach a recovery-expr initializer to track 13194 // that initialization was attempted and failed. 13195 auto RecoveryExpr = 13196 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {}); 13197 if (RecoveryExpr.get()) 13198 Var->setInit(RecoveryExpr.get()); 13199 } 13200 13201 CheckCompleteVariableDeclaration(Var); 13202 } 13203 } 13204 13205 void Sema::ActOnCXXForRangeDecl(Decl *D) { 13206 // If there is no declaration, there was an error parsing it. Ignore it. 13207 if (!D) 13208 return; 13209 13210 VarDecl *VD = dyn_cast<VarDecl>(D); 13211 if (!VD) { 13212 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 13213 D->setInvalidDecl(); 13214 return; 13215 } 13216 13217 VD->setCXXForRangeDecl(true); 13218 13219 // for-range-declaration cannot be given a storage class specifier. 13220 int Error = -1; 13221 switch (VD->getStorageClass()) { 13222 case SC_None: 13223 break; 13224 case SC_Extern: 13225 Error = 0; 13226 break; 13227 case SC_Static: 13228 Error = 1; 13229 break; 13230 case SC_PrivateExtern: 13231 Error = 2; 13232 break; 13233 case SC_Auto: 13234 Error = 3; 13235 break; 13236 case SC_Register: 13237 Error = 4; 13238 break; 13239 } 13240 13241 // for-range-declaration cannot be given a storage class specifier con't. 13242 switch (VD->getTSCSpec()) { 13243 case TSCS_thread_local: 13244 Error = 6; 13245 break; 13246 case TSCS___thread: 13247 case TSCS__Thread_local: 13248 case TSCS_unspecified: 13249 break; 13250 } 13251 13252 if (Error != -1) { 13253 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 13254 << VD << Error; 13255 D->setInvalidDecl(); 13256 } 13257 } 13258 13259 StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 13260 IdentifierInfo *Ident, 13261 ParsedAttributes &Attrs) { 13262 // C++1y [stmt.iter]p1: 13263 // A range-based for statement of the form 13264 // for ( for-range-identifier : for-range-initializer ) statement 13265 // is equivalent to 13266 // for ( auto&& for-range-identifier : for-range-initializer ) statement 13267 DeclSpec DS(Attrs.getPool().getFactory()); 13268 13269 const char *PrevSpec; 13270 unsigned DiagID; 13271 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 13272 getPrintingPolicy()); 13273 13274 Declarator D(DS, DeclaratorContext::ForInit); 13275 D.SetIdentifier(Ident, IdentLoc); 13276 D.takeAttributes(Attrs); 13277 13278 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false), 13279 IdentLoc); 13280 Decl *Var = ActOnDeclarator(S, D); 13281 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 13282 FinalizeDeclaration(Var); 13283 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 13284 Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd() 13285 : IdentLoc); 13286 } 13287 13288 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 13289 if (var->isInvalidDecl()) return; 13290 13291 MaybeAddCUDAConstantAttr(var); 13292 13293 if (getLangOpts().OpenCL) { 13294 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 13295 // initialiser 13296 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 13297 !var->hasInit()) { 13298 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 13299 << 1 /*Init*/; 13300 var->setInvalidDecl(); 13301 return; 13302 } 13303 } 13304 13305 // In Objective-C, don't allow jumps past the implicit initialization of a 13306 // local retaining variable. 13307 if (getLangOpts().ObjC && 13308 var->hasLocalStorage()) { 13309 switch (var->getType().getObjCLifetime()) { 13310 case Qualifiers::OCL_None: 13311 case Qualifiers::OCL_ExplicitNone: 13312 case Qualifiers::OCL_Autoreleasing: 13313 break; 13314 13315 case Qualifiers::OCL_Weak: 13316 case Qualifiers::OCL_Strong: 13317 setFunctionHasBranchProtectedScope(); 13318 break; 13319 } 13320 } 13321 13322 if (var->hasLocalStorage() && 13323 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 13324 setFunctionHasBranchProtectedScope(); 13325 13326 // Warn about externally-visible variables being defined without a 13327 // prior declaration. We only want to do this for global 13328 // declarations, but we also specifically need to avoid doing it for 13329 // class members because the linkage of an anonymous class can 13330 // change if it's later given a typedef name. 13331 if (var->isThisDeclarationADefinition() && 13332 var->getDeclContext()->getRedeclContext()->isFileContext() && 13333 var->isExternallyVisible() && var->hasLinkage() && 13334 !var->isInline() && !var->getDescribedVarTemplate() && 13335 !isa<VarTemplatePartialSpecializationDecl>(var) && 13336 !isTemplateInstantiation(var->getTemplateSpecializationKind()) && 13337 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 13338 var->getLocation())) { 13339 // Find a previous declaration that's not a definition. 13340 VarDecl *prev = var->getPreviousDecl(); 13341 while (prev && prev->isThisDeclarationADefinition()) 13342 prev = prev->getPreviousDecl(); 13343 13344 if (!prev) { 13345 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 13346 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 13347 << /* variable */ 0; 13348 } 13349 } 13350 13351 // Cache the result of checking for constant initialization. 13352 Optional<bool> CacheHasConstInit; 13353 const Expr *CacheCulprit = nullptr; 13354 auto checkConstInit = [&]() mutable { 13355 if (!CacheHasConstInit) 13356 CacheHasConstInit = var->getInit()->isConstantInitializer( 13357 Context, var->getType()->isReferenceType(), &CacheCulprit); 13358 return *CacheHasConstInit; 13359 }; 13360 13361 if (var->getTLSKind() == VarDecl::TLS_Static) { 13362 if (var->getType().isDestructedType()) { 13363 // GNU C++98 edits for __thread, [basic.start.term]p3: 13364 // The type of an object with thread storage duration shall not 13365 // have a non-trivial destructor. 13366 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 13367 if (getLangOpts().CPlusPlus11) 13368 Diag(var->getLocation(), diag::note_use_thread_local); 13369 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 13370 if (!checkConstInit()) { 13371 // GNU C++98 edits for __thread, [basic.start.init]p4: 13372 // An object of thread storage duration shall not require dynamic 13373 // initialization. 13374 // FIXME: Need strict checking here. 13375 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 13376 << CacheCulprit->getSourceRange(); 13377 if (getLangOpts().CPlusPlus11) 13378 Diag(var->getLocation(), diag::note_use_thread_local); 13379 } 13380 } 13381 } 13382 13383 13384 if (!var->getType()->isStructureType() && var->hasInit() && 13385 isa<InitListExpr>(var->getInit())) { 13386 const auto *ILE = cast<InitListExpr>(var->getInit()); 13387 unsigned NumInits = ILE->getNumInits(); 13388 if (NumInits > 2) 13389 for (unsigned I = 0; I < NumInits; ++I) { 13390 const auto *Init = ILE->getInit(I); 13391 if (!Init) 13392 break; 13393 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); 13394 if (!SL) 13395 break; 13396 13397 unsigned NumConcat = SL->getNumConcatenated(); 13398 // Diagnose missing comma in string array initialization. 13399 // Do not warn when all the elements in the initializer are concatenated 13400 // together. Do not warn for macros too. 13401 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) { 13402 bool OnlyOneMissingComma = true; 13403 for (unsigned J = I + 1; J < NumInits; ++J) { 13404 const auto *Init = ILE->getInit(J); 13405 if (!Init) 13406 break; 13407 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); 13408 if (!SLJ || SLJ->getNumConcatenated() > 1) { 13409 OnlyOneMissingComma = false; 13410 break; 13411 } 13412 } 13413 13414 if (OnlyOneMissingComma) { 13415 SmallVector<FixItHint, 1> Hints; 13416 for (unsigned i = 0; i < NumConcat - 1; ++i) 13417 Hints.push_back(FixItHint::CreateInsertion( 13418 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ",")); 13419 13420 Diag(SL->getStrTokenLoc(1), 13421 diag::warn_concatenated_literal_array_init) 13422 << Hints; 13423 Diag(SL->getBeginLoc(), 13424 diag::note_concatenated_string_literal_silence); 13425 } 13426 // In any case, stop now. 13427 break; 13428 } 13429 } 13430 } 13431 13432 13433 QualType type = var->getType(); 13434 13435 if (var->hasAttr<BlocksAttr>()) 13436 getCurFunction()->addByrefBlockVar(var); 13437 13438 Expr *Init = var->getInit(); 13439 bool GlobalStorage = var->hasGlobalStorage(); 13440 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 13441 QualType baseType = Context.getBaseElementType(type); 13442 bool HasConstInit = true; 13443 13444 // Check whether the initializer is sufficiently constant. 13445 if (getLangOpts().CPlusPlus && !type->isDependentType() && Init && 13446 !Init->isValueDependent() && 13447 (GlobalStorage || var->isConstexpr() || 13448 var->mightBeUsableInConstantExpressions(Context))) { 13449 // If this variable might have a constant initializer or might be usable in 13450 // constant expressions, check whether or not it actually is now. We can't 13451 // do this lazily, because the result might depend on things that change 13452 // later, such as which constexpr functions happen to be defined. 13453 SmallVector<PartialDiagnosticAt, 8> Notes; 13454 if (!getLangOpts().CPlusPlus11) { 13455 // Prior to C++11, in contexts where a constant initializer is required, 13456 // the set of valid constant initializers is described by syntactic rules 13457 // in [expr.const]p2-6. 13458 // FIXME: Stricter checking for these rules would be useful for constinit / 13459 // -Wglobal-constructors. 13460 HasConstInit = checkConstInit(); 13461 13462 // Compute and cache the constant value, and remember that we have a 13463 // constant initializer. 13464 if (HasConstInit) { 13465 (void)var->checkForConstantInitialization(Notes); 13466 Notes.clear(); 13467 } else if (CacheCulprit) { 13468 Notes.emplace_back(CacheCulprit->getExprLoc(), 13469 PDiag(diag::note_invalid_subexpr_in_const_expr)); 13470 Notes.back().second << CacheCulprit->getSourceRange(); 13471 } 13472 } else { 13473 // Evaluate the initializer to see if it's a constant initializer. 13474 HasConstInit = var->checkForConstantInitialization(Notes); 13475 } 13476 13477 if (HasConstInit) { 13478 // FIXME: Consider replacing the initializer with a ConstantExpr. 13479 } else if (var->isConstexpr()) { 13480 SourceLocation DiagLoc = var->getLocation(); 13481 // If the note doesn't add any useful information other than a source 13482 // location, fold it into the primary diagnostic. 13483 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 13484 diag::note_invalid_subexpr_in_const_expr) { 13485 DiagLoc = Notes[0].first; 13486 Notes.clear(); 13487 } 13488 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 13489 << var << Init->getSourceRange(); 13490 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 13491 Diag(Notes[I].first, Notes[I].second); 13492 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) { 13493 auto *Attr = var->getAttr<ConstInitAttr>(); 13494 Diag(var->getLocation(), diag::err_require_constant_init_failed) 13495 << Init->getSourceRange(); 13496 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here) 13497 << Attr->getRange() << Attr->isConstinit(); 13498 for (auto &it : Notes) 13499 Diag(it.first, it.second); 13500 } else if (IsGlobal && 13501 !getDiagnostics().isIgnored(diag::warn_global_constructor, 13502 var->getLocation())) { 13503 // Warn about globals which don't have a constant initializer. Don't 13504 // warn about globals with a non-trivial destructor because we already 13505 // warned about them. 13506 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 13507 if (!(RD && !RD->hasTrivialDestructor())) { 13508 // checkConstInit() here permits trivial default initialization even in 13509 // C++11 onwards, where such an initializer is not a constant initializer 13510 // but nonetheless doesn't require a global constructor. 13511 if (!checkConstInit()) 13512 Diag(var->getLocation(), diag::warn_global_constructor) 13513 << Init->getSourceRange(); 13514 } 13515 } 13516 } 13517 13518 // Apply section attributes and pragmas to global variables. 13519 if (GlobalStorage && var->isThisDeclarationADefinition() && 13520 !inTemplateInstantiation()) { 13521 PragmaStack<StringLiteral *> *Stack = nullptr; 13522 int SectionFlags = ASTContext::PSF_Read; 13523 if (var->getType().isConstQualified()) { 13524 if (HasConstInit) 13525 Stack = &ConstSegStack; 13526 else { 13527 Stack = &BSSSegStack; 13528 SectionFlags |= ASTContext::PSF_Write; 13529 } 13530 } else if (var->hasInit() && HasConstInit) { 13531 Stack = &DataSegStack; 13532 SectionFlags |= ASTContext::PSF_Write; 13533 } else { 13534 Stack = &BSSSegStack; 13535 SectionFlags |= ASTContext::PSF_Write; 13536 } 13537 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) { 13538 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec) 13539 SectionFlags |= ASTContext::PSF_Implicit; 13540 UnifySection(SA->getName(), SectionFlags, var); 13541 } else if (Stack->CurrentValue) { 13542 SectionFlags |= ASTContext::PSF_Implicit; 13543 auto SectionName = Stack->CurrentValue->getString(); 13544 var->addAttr(SectionAttr::CreateImplicit( 13545 Context, SectionName, Stack->CurrentPragmaLocation, 13546 AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate)); 13547 if (UnifySection(SectionName, SectionFlags, var)) 13548 var->dropAttr<SectionAttr>(); 13549 } 13550 13551 // Apply the init_seg attribute if this has an initializer. If the 13552 // initializer turns out to not be dynamic, we'll end up ignoring this 13553 // attribute. 13554 if (CurInitSeg && var->getInit()) 13555 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 13556 CurInitSegLoc, 13557 AttributeCommonInfo::AS_Pragma)); 13558 } 13559 13560 // All the following checks are C++ only. 13561 if (!getLangOpts().CPlusPlus) { 13562 // If this variable must be emitted, add it as an initializer for the 13563 // current module. 13564 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 13565 Context.addModuleInitializer(ModuleScopes.back().Module, var); 13566 return; 13567 } 13568 13569 // Require the destructor. 13570 if (!type->isDependentType()) 13571 if (const RecordType *recordType = baseType->getAs<RecordType>()) 13572 FinalizeVarWithDestructor(var, recordType); 13573 13574 // If this variable must be emitted, add it as an initializer for the current 13575 // module. 13576 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 13577 Context.addModuleInitializer(ModuleScopes.back().Module, var); 13578 13579 // Build the bindings if this is a structured binding declaration. 13580 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 13581 CheckCompleteDecompositionDeclaration(DD); 13582 } 13583 13584 /// Check if VD needs to be dllexport/dllimport due to being in a 13585 /// dllexport/import function. 13586 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) { 13587 assert(VD->isStaticLocal()); 13588 13589 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 13590 13591 // Find outermost function when VD is in lambda function. 13592 while (FD && !getDLLAttr(FD) && 13593 !FD->hasAttr<DLLExportStaticLocalAttr>() && 13594 !FD->hasAttr<DLLImportStaticLocalAttr>()) { 13595 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod()); 13596 } 13597 13598 if (!FD) 13599 return; 13600 13601 // Static locals inherit dll attributes from their function. 13602 if (Attr *A = getDLLAttr(FD)) { 13603 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 13604 NewAttr->setInherited(true); 13605 VD->addAttr(NewAttr); 13606 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) { 13607 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A); 13608 NewAttr->setInherited(true); 13609 VD->addAttr(NewAttr); 13610 13611 // Export this function to enforce exporting this static variable even 13612 // if it is not used in this compilation unit. 13613 if (!FD->hasAttr<DLLExportAttr>()) 13614 FD->addAttr(NewAttr); 13615 13616 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) { 13617 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A); 13618 NewAttr->setInherited(true); 13619 VD->addAttr(NewAttr); 13620 } 13621 } 13622 13623 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 13624 /// any semantic actions necessary after any initializer has been attached. 13625 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 13626 // Note that we are no longer parsing the initializer for this declaration. 13627 ParsingInitForAutoVars.erase(ThisDecl); 13628 13629 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 13630 if (!VD) 13631 return; 13632 13633 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active 13634 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && 13635 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { 13636 if (PragmaClangBSSSection.Valid) 13637 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit( 13638 Context, PragmaClangBSSSection.SectionName, 13639 PragmaClangBSSSection.PragmaLocation, 13640 AttributeCommonInfo::AS_Pragma)); 13641 if (PragmaClangDataSection.Valid) 13642 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit( 13643 Context, PragmaClangDataSection.SectionName, 13644 PragmaClangDataSection.PragmaLocation, 13645 AttributeCommonInfo::AS_Pragma)); 13646 if (PragmaClangRodataSection.Valid) 13647 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit( 13648 Context, PragmaClangRodataSection.SectionName, 13649 PragmaClangRodataSection.PragmaLocation, 13650 AttributeCommonInfo::AS_Pragma)); 13651 if (PragmaClangRelroSection.Valid) 13652 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit( 13653 Context, PragmaClangRelroSection.SectionName, 13654 PragmaClangRelroSection.PragmaLocation, 13655 AttributeCommonInfo::AS_Pragma)); 13656 } 13657 13658 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 13659 for (auto *BD : DD->bindings()) { 13660 FinalizeDeclaration(BD); 13661 } 13662 } 13663 13664 checkAttributesAfterMerging(*this, *VD); 13665 13666 // Perform TLS alignment check here after attributes attached to the variable 13667 // which may affect the alignment have been processed. Only perform the check 13668 // if the target has a maximum TLS alignment (zero means no constraints). 13669 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 13670 // Protect the check so that it's not performed on dependent types and 13671 // dependent alignments (we can't determine the alignment in that case). 13672 if (VD->getTLSKind() && !VD->hasDependentAlignment()) { 13673 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 13674 if (Context.getDeclAlign(VD) > MaxAlignChars) { 13675 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 13676 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 13677 << (unsigned)MaxAlignChars.getQuantity(); 13678 } 13679 } 13680 } 13681 13682 if (VD->isStaticLocal()) 13683 CheckStaticLocalForDllExport(VD); 13684 13685 // Perform check for initializers of device-side global variables. 13686 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 13687 // 7.5). We must also apply the same checks to all __shared__ 13688 // variables whether they are local or not. CUDA also allows 13689 // constant initializers for __constant__ and __device__ variables. 13690 if (getLangOpts().CUDA) 13691 checkAllowedCUDAInitializer(VD); 13692 13693 // Grab the dllimport or dllexport attribute off of the VarDecl. 13694 const InheritableAttr *DLLAttr = getDLLAttr(VD); 13695 13696 // Imported static data members cannot be defined out-of-line. 13697 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 13698 if (VD->isStaticDataMember() && VD->isOutOfLine() && 13699 VD->isThisDeclarationADefinition()) { 13700 // We allow definitions of dllimport class template static data members 13701 // with a warning. 13702 CXXRecordDecl *Context = 13703 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 13704 bool IsClassTemplateMember = 13705 isa<ClassTemplatePartialSpecializationDecl>(Context) || 13706 Context->getDescribedClassTemplate(); 13707 13708 Diag(VD->getLocation(), 13709 IsClassTemplateMember 13710 ? diag::warn_attribute_dllimport_static_field_definition 13711 : diag::err_attribute_dllimport_static_field_definition); 13712 Diag(IA->getLocation(), diag::note_attribute); 13713 if (!IsClassTemplateMember) 13714 VD->setInvalidDecl(); 13715 } 13716 } 13717 13718 // dllimport/dllexport variables cannot be thread local, their TLS index 13719 // isn't exported with the variable. 13720 if (DLLAttr && VD->getTLSKind()) { 13721 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 13722 if (F && getDLLAttr(F)) { 13723 assert(VD->isStaticLocal()); 13724 // But if this is a static local in a dlimport/dllexport function, the 13725 // function will never be inlined, which means the var would never be 13726 // imported, so having it marked import/export is safe. 13727 } else { 13728 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 13729 << DLLAttr; 13730 VD->setInvalidDecl(); 13731 } 13732 } 13733 13734 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 13735 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 13736 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition) 13737 << Attr; 13738 VD->dropAttr<UsedAttr>(); 13739 } 13740 } 13741 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) { 13742 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 13743 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition) 13744 << Attr; 13745 VD->dropAttr<RetainAttr>(); 13746 } 13747 } 13748 13749 const DeclContext *DC = VD->getDeclContext(); 13750 // If there's a #pragma GCC visibility in scope, and this isn't a class 13751 // member, set the visibility of this variable. 13752 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 13753 AddPushedVisibilityAttribute(VD); 13754 13755 // FIXME: Warn on unused var template partial specializations. 13756 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 13757 MarkUnusedFileScopedDecl(VD); 13758 13759 // Now we have parsed the initializer and can update the table of magic 13760 // tag values. 13761 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 13762 !VD->getType()->isIntegralOrEnumerationType()) 13763 return; 13764 13765 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 13766 const Expr *MagicValueExpr = VD->getInit(); 13767 if (!MagicValueExpr) { 13768 continue; 13769 } 13770 Optional<llvm::APSInt> MagicValueInt; 13771 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) { 13772 Diag(I->getRange().getBegin(), 13773 diag::err_type_tag_for_datatype_not_ice) 13774 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13775 continue; 13776 } 13777 if (MagicValueInt->getActiveBits() > 64) { 13778 Diag(I->getRange().getBegin(), 13779 diag::err_type_tag_for_datatype_too_large) 13780 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13781 continue; 13782 } 13783 uint64_t MagicValue = MagicValueInt->getZExtValue(); 13784 RegisterTypeTagForDatatype(I->getArgumentKind(), 13785 MagicValue, 13786 I->getMatchingCType(), 13787 I->getLayoutCompatible(), 13788 I->getMustBeNull()); 13789 } 13790 } 13791 13792 static bool hasDeducedAuto(DeclaratorDecl *DD) { 13793 auto *VD = dyn_cast<VarDecl>(DD); 13794 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 13795 } 13796 13797 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 13798 ArrayRef<Decl *> Group) { 13799 SmallVector<Decl*, 8> Decls; 13800 13801 if (DS.isTypeSpecOwned()) 13802 Decls.push_back(DS.getRepAsDecl()); 13803 13804 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 13805 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 13806 bool DiagnosedMultipleDecomps = false; 13807 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 13808 bool DiagnosedNonDeducedAuto = false; 13809 13810 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13811 if (Decl *D = Group[i]) { 13812 // For declarators, there are some additional syntactic-ish checks we need 13813 // to perform. 13814 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 13815 if (!FirstDeclaratorInGroup) 13816 FirstDeclaratorInGroup = DD; 13817 if (!FirstDecompDeclaratorInGroup) 13818 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 13819 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 13820 !hasDeducedAuto(DD)) 13821 FirstNonDeducedAutoInGroup = DD; 13822 13823 if (FirstDeclaratorInGroup != DD) { 13824 // A decomposition declaration cannot be combined with any other 13825 // declaration in the same group. 13826 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 13827 Diag(FirstDecompDeclaratorInGroup->getLocation(), 13828 diag::err_decomp_decl_not_alone) 13829 << FirstDeclaratorInGroup->getSourceRange() 13830 << DD->getSourceRange(); 13831 DiagnosedMultipleDecomps = true; 13832 } 13833 13834 // A declarator that uses 'auto' in any way other than to declare a 13835 // variable with a deduced type cannot be combined with any other 13836 // declarator in the same group. 13837 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 13838 Diag(FirstNonDeducedAutoInGroup->getLocation(), 13839 diag::err_auto_non_deduced_not_alone) 13840 << FirstNonDeducedAutoInGroup->getType() 13841 ->hasAutoForTrailingReturnType() 13842 << FirstDeclaratorInGroup->getSourceRange() 13843 << DD->getSourceRange(); 13844 DiagnosedNonDeducedAuto = true; 13845 } 13846 } 13847 } 13848 13849 Decls.push_back(D); 13850 } 13851 } 13852 13853 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 13854 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 13855 handleTagNumbering(Tag, S); 13856 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 13857 getLangOpts().CPlusPlus) 13858 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 13859 } 13860 } 13861 13862 return BuildDeclaratorGroup(Decls); 13863 } 13864 13865 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 13866 /// group, performing any necessary semantic checking. 13867 Sema::DeclGroupPtrTy 13868 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 13869 // C++14 [dcl.spec.auto]p7: (DR1347) 13870 // If the type that replaces the placeholder type is not the same in each 13871 // deduction, the program is ill-formed. 13872 if (Group.size() > 1) { 13873 QualType Deduced; 13874 VarDecl *DeducedDecl = nullptr; 13875 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13876 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 13877 if (!D || D->isInvalidDecl()) 13878 break; 13879 DeducedType *DT = D->getType()->getContainedDeducedType(); 13880 if (!DT || DT->getDeducedType().isNull()) 13881 continue; 13882 if (Deduced.isNull()) { 13883 Deduced = DT->getDeducedType(); 13884 DeducedDecl = D; 13885 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 13886 auto *AT = dyn_cast<AutoType>(DT); 13887 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 13888 diag::err_auto_different_deductions) 13889 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced 13890 << DeducedDecl->getDeclName() << DT->getDeducedType() 13891 << D->getDeclName(); 13892 if (DeducedDecl->hasInit()) 13893 Dia << DeducedDecl->getInit()->getSourceRange(); 13894 if (D->getInit()) 13895 Dia << D->getInit()->getSourceRange(); 13896 D->setInvalidDecl(); 13897 break; 13898 } 13899 } 13900 } 13901 13902 ActOnDocumentableDecls(Group); 13903 13904 return DeclGroupPtrTy::make( 13905 DeclGroupRef::Create(Context, Group.data(), Group.size())); 13906 } 13907 13908 void Sema::ActOnDocumentableDecl(Decl *D) { 13909 ActOnDocumentableDecls(D); 13910 } 13911 13912 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 13913 // Don't parse the comment if Doxygen diagnostics are ignored. 13914 if (Group.empty() || !Group[0]) 13915 return; 13916 13917 if (Diags.isIgnored(diag::warn_doc_param_not_found, 13918 Group[0]->getLocation()) && 13919 Diags.isIgnored(diag::warn_unknown_comment_command_name, 13920 Group[0]->getLocation())) 13921 return; 13922 13923 if (Group.size() >= 2) { 13924 // This is a decl group. Normally it will contain only declarations 13925 // produced from declarator list. But in case we have any definitions or 13926 // additional declaration references: 13927 // 'typedef struct S {} S;' 13928 // 'typedef struct S *S;' 13929 // 'struct S *pS;' 13930 // FinalizeDeclaratorGroup adds these as separate declarations. 13931 Decl *MaybeTagDecl = Group[0]; 13932 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 13933 Group = Group.slice(1); 13934 } 13935 } 13936 13937 // FIMXE: We assume every Decl in the group is in the same file. 13938 // This is false when preprocessor constructs the group from decls in 13939 // different files (e. g. macros or #include). 13940 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor()); 13941 } 13942 13943 /// Common checks for a parameter-declaration that should apply to both function 13944 /// parameters and non-type template parameters. 13945 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) { 13946 // Check that there are no default arguments inside the type of this 13947 // parameter. 13948 if (getLangOpts().CPlusPlus) 13949 CheckExtraCXXDefaultArguments(D); 13950 13951 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 13952 if (D.getCXXScopeSpec().isSet()) { 13953 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 13954 << D.getCXXScopeSpec().getRange(); 13955 } 13956 13957 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a 13958 // simple identifier except [...irrelevant cases...]. 13959 switch (D.getName().getKind()) { 13960 case UnqualifiedIdKind::IK_Identifier: 13961 break; 13962 13963 case UnqualifiedIdKind::IK_OperatorFunctionId: 13964 case UnqualifiedIdKind::IK_ConversionFunctionId: 13965 case UnqualifiedIdKind::IK_LiteralOperatorId: 13966 case UnqualifiedIdKind::IK_ConstructorName: 13967 case UnqualifiedIdKind::IK_DestructorName: 13968 case UnqualifiedIdKind::IK_ImplicitSelfParam: 13969 case UnqualifiedIdKind::IK_DeductionGuideName: 13970 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 13971 << GetNameForDeclarator(D).getName(); 13972 break; 13973 13974 case UnqualifiedIdKind::IK_TemplateId: 13975 case UnqualifiedIdKind::IK_ConstructorTemplateId: 13976 // GetNameForDeclarator would not produce a useful name in this case. 13977 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id); 13978 break; 13979 } 13980 } 13981 13982 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 13983 /// to introduce parameters into function prototype scope. 13984 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 13985 const DeclSpec &DS = D.getDeclSpec(); 13986 13987 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 13988 13989 // C++03 [dcl.stc]p2 also permits 'auto'. 13990 StorageClass SC = SC_None; 13991 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 13992 SC = SC_Register; 13993 // In C++11, the 'register' storage class specifier is deprecated. 13994 // In C++17, it is not allowed, but we tolerate it as an extension. 13995 if (getLangOpts().CPlusPlus11) { 13996 Diag(DS.getStorageClassSpecLoc(), 13997 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 13998 : diag::warn_deprecated_register) 13999 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 14000 } 14001 } else if (getLangOpts().CPlusPlus && 14002 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 14003 SC = SC_Auto; 14004 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 14005 Diag(DS.getStorageClassSpecLoc(), 14006 diag::err_invalid_storage_class_in_func_decl); 14007 D.getMutableDeclSpec().ClearStorageClassSpecs(); 14008 } 14009 14010 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 14011 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 14012 << DeclSpec::getSpecifierName(TSCS); 14013 if (DS.isInlineSpecified()) 14014 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 14015 << getLangOpts().CPlusPlus17; 14016 if (DS.hasConstexprSpecifier()) 14017 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 14018 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 14019 14020 DiagnoseFunctionSpecifiers(DS); 14021 14022 CheckFunctionOrTemplateParamDeclarator(S, D); 14023 14024 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 14025 QualType parmDeclType = TInfo->getType(); 14026 14027 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 14028 IdentifierInfo *II = D.getIdentifier(); 14029 if (II) { 14030 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 14031 ForVisibleRedeclaration); 14032 LookupName(R, S); 14033 if (R.isSingleResult()) { 14034 NamedDecl *PrevDecl = R.getFoundDecl(); 14035 if (PrevDecl->isTemplateParameter()) { 14036 // Maybe we will complain about the shadowed template parameter. 14037 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 14038 // Just pretend that we didn't see the previous declaration. 14039 PrevDecl = nullptr; 14040 } else if (S->isDeclScope(PrevDecl)) { 14041 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 14042 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 14043 14044 // Recover by removing the name 14045 II = nullptr; 14046 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 14047 D.setInvalidType(true); 14048 } 14049 } 14050 } 14051 14052 // Temporarily put parameter variables in the translation unit, not 14053 // the enclosing context. This prevents them from accidentally 14054 // looking like class members in C++. 14055 ParmVarDecl *New = 14056 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(), 14057 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC); 14058 14059 if (D.isInvalidType()) 14060 New->setInvalidDecl(); 14061 14062 assert(S->isFunctionPrototypeScope()); 14063 assert(S->getFunctionPrototypeDepth() >= 1); 14064 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 14065 S->getNextFunctionPrototypeIndex()); 14066 14067 // Add the parameter declaration into this scope. 14068 S->AddDecl(New); 14069 if (II) 14070 IdResolver.AddDecl(New); 14071 14072 ProcessDeclAttributes(S, New, D); 14073 14074 if (D.getDeclSpec().isModulePrivateSpecified()) 14075 Diag(New->getLocation(), diag::err_module_private_local) 14076 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 14077 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 14078 14079 if (New->hasAttr<BlocksAttr>()) { 14080 Diag(New->getLocation(), diag::err_block_on_nonlocal); 14081 } 14082 14083 if (getLangOpts().OpenCL) 14084 deduceOpenCLAddressSpace(New); 14085 14086 return New; 14087 } 14088 14089 /// Synthesizes a variable for a parameter arising from a 14090 /// typedef. 14091 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 14092 SourceLocation Loc, 14093 QualType T) { 14094 /* FIXME: setting StartLoc == Loc. 14095 Would it be worth to modify callers so as to provide proper source 14096 location for the unnamed parameters, embedding the parameter's type? */ 14097 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 14098 T, Context.getTrivialTypeSourceInfo(T, Loc), 14099 SC_None, nullptr); 14100 Param->setImplicit(); 14101 return Param; 14102 } 14103 14104 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 14105 // Don't diagnose unused-parameter errors in template instantiations; we 14106 // will already have done so in the template itself. 14107 if (inTemplateInstantiation()) 14108 return; 14109 14110 for (const ParmVarDecl *Parameter : Parameters) { 14111 if (!Parameter->isReferenced() && Parameter->getDeclName() && 14112 !Parameter->hasAttr<UnusedAttr>()) { 14113 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 14114 << Parameter->getDeclName(); 14115 } 14116 } 14117 } 14118 14119 void Sema::DiagnoseSizeOfParametersAndReturnValue( 14120 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 14121 if (LangOpts.NumLargeByValueCopy == 0) // No check. 14122 return; 14123 14124 // Warn if the return value is pass-by-value and larger than the specified 14125 // threshold. 14126 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 14127 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 14128 if (Size > LangOpts.NumLargeByValueCopy) 14129 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size; 14130 } 14131 14132 // Warn if any parameter is pass-by-value and larger than the specified 14133 // threshold. 14134 for (const ParmVarDecl *Parameter : Parameters) { 14135 QualType T = Parameter->getType(); 14136 if (T->isDependentType() || !T.isPODType(Context)) 14137 continue; 14138 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 14139 if (Size > LangOpts.NumLargeByValueCopy) 14140 Diag(Parameter->getLocation(), diag::warn_parameter_size) 14141 << Parameter << Size; 14142 } 14143 } 14144 14145 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 14146 SourceLocation NameLoc, IdentifierInfo *Name, 14147 QualType T, TypeSourceInfo *TSInfo, 14148 StorageClass SC) { 14149 // In ARC, infer a lifetime qualifier for appropriate parameter types. 14150 if (getLangOpts().ObjCAutoRefCount && 14151 T.getObjCLifetime() == Qualifiers::OCL_None && 14152 T->isObjCLifetimeType()) { 14153 14154 Qualifiers::ObjCLifetime lifetime; 14155 14156 // Special cases for arrays: 14157 // - if it's const, use __unsafe_unretained 14158 // - otherwise, it's an error 14159 if (T->isArrayType()) { 14160 if (!T.isConstQualified()) { 14161 if (DelayedDiagnostics.shouldDelayDiagnostics()) 14162 DelayedDiagnostics.add( 14163 sema::DelayedDiagnostic::makeForbiddenType( 14164 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 14165 else 14166 Diag(NameLoc, diag::err_arc_array_param_no_ownership) 14167 << TSInfo->getTypeLoc().getSourceRange(); 14168 } 14169 lifetime = Qualifiers::OCL_ExplicitNone; 14170 } else { 14171 lifetime = T->getObjCARCImplicitLifetime(); 14172 } 14173 T = Context.getLifetimeQualifiedType(T, lifetime); 14174 } 14175 14176 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 14177 Context.getAdjustedParameterType(T), 14178 TSInfo, SC, nullptr); 14179 14180 // Make a note if we created a new pack in the scope of a lambda, so that 14181 // we know that references to that pack must also be expanded within the 14182 // lambda scope. 14183 if (New->isParameterPack()) 14184 if (auto *LSI = getEnclosingLambda()) 14185 LSI->LocalPacks.push_back(New); 14186 14187 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() || 14188 New->getType().hasNonTrivialToPrimitiveCopyCUnion()) 14189 checkNonTrivialCUnion(New->getType(), New->getLocation(), 14190 NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy); 14191 14192 // Parameters can not be abstract class types. 14193 // For record types, this is done by the AbstractClassUsageDiagnoser once 14194 // the class has been completely parsed. 14195 if (!CurContext->isRecord() && 14196 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 14197 AbstractParamType)) 14198 New->setInvalidDecl(); 14199 14200 // Parameter declarators cannot be interface types. All ObjC objects are 14201 // passed by reference. 14202 if (T->isObjCObjectType()) { 14203 SourceLocation TypeEndLoc = 14204 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc()); 14205 Diag(NameLoc, 14206 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 14207 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 14208 T = Context.getObjCObjectPointerType(T); 14209 New->setType(T); 14210 } 14211 14212 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 14213 // duration shall not be qualified by an address-space qualifier." 14214 // Since all parameters have automatic store duration, they can not have 14215 // an address space. 14216 if (T.getAddressSpace() != LangAS::Default && 14217 // OpenCL allows function arguments declared to be an array of a type 14218 // to be qualified with an address space. 14219 !(getLangOpts().OpenCL && 14220 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) { 14221 Diag(NameLoc, diag::err_arg_with_address_space); 14222 New->setInvalidDecl(); 14223 } 14224 14225 // PPC MMA non-pointer types are not allowed as function argument types. 14226 if (Context.getTargetInfo().getTriple().isPPC64() && 14227 CheckPPCMMAType(New->getOriginalType(), New->getLocation())) { 14228 New->setInvalidDecl(); 14229 } 14230 14231 return New; 14232 } 14233 14234 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 14235 SourceLocation LocAfterDecls) { 14236 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 14237 14238 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 14239 // for a K&R function. 14240 if (!FTI.hasPrototype) { 14241 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 14242 --i; 14243 if (FTI.Params[i].Param == nullptr) { 14244 SmallString<256> Code; 14245 llvm::raw_svector_ostream(Code) 14246 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 14247 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 14248 << FTI.Params[i].Ident 14249 << FixItHint::CreateInsertion(LocAfterDecls, Code); 14250 14251 // Implicitly declare the argument as type 'int' for lack of a better 14252 // type. 14253 AttributeFactory attrs; 14254 DeclSpec DS(attrs); 14255 const char* PrevSpec; // unused 14256 unsigned DiagID; // unused 14257 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 14258 DiagID, Context.getPrintingPolicy()); 14259 // Use the identifier location for the type source range. 14260 DS.SetRangeStart(FTI.Params[i].IdentLoc); 14261 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 14262 Declarator ParamD(DS, DeclaratorContext::KNRTypeList); 14263 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 14264 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 14265 } 14266 } 14267 } 14268 } 14269 14270 Decl * 14271 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 14272 MultiTemplateParamsArg TemplateParameterLists, 14273 SkipBodyInfo *SkipBody) { 14274 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 14275 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 14276 Scope *ParentScope = FnBodyScope->getParent(); 14277 14278 // Check if we are in an `omp begin/end declare variant` scope. If we are, and 14279 // we define a non-templated function definition, we will create a declaration 14280 // instead (=BaseFD), and emit the definition with a mangled name afterwards. 14281 // The base function declaration will have the equivalent of an `omp declare 14282 // variant` annotation which specifies the mangled definition as a 14283 // specialization function under the OpenMP context defined as part of the 14284 // `omp begin declare variant`. 14285 SmallVector<FunctionDecl *, 4> Bases; 14286 if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope()) 14287 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( 14288 ParentScope, D, TemplateParameterLists, Bases); 14289 14290 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition); 14291 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 14292 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 14293 14294 if (!Bases.empty()) 14295 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases); 14296 14297 return Dcl; 14298 } 14299 14300 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 14301 Consumer.HandleInlineFunctionDefinition(D); 14302 } 14303 14304 static bool 14305 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 14306 const FunctionDecl *&PossiblePrototype) { 14307 // Don't warn about invalid declarations. 14308 if (FD->isInvalidDecl()) 14309 return false; 14310 14311 // Or declarations that aren't global. 14312 if (!FD->isGlobal()) 14313 return false; 14314 14315 // Don't warn about C++ member functions. 14316 if (isa<CXXMethodDecl>(FD)) 14317 return false; 14318 14319 // Don't warn about 'main'. 14320 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext())) 14321 if (IdentifierInfo *II = FD->getIdentifier()) 14322 if (II->isStr("main") || II->isStr("efi_main")) 14323 return false; 14324 14325 // Don't warn about inline functions. 14326 if (FD->isInlined()) 14327 return false; 14328 14329 // Don't warn about function templates. 14330 if (FD->getDescribedFunctionTemplate()) 14331 return false; 14332 14333 // Don't warn about function template specializations. 14334 if (FD->isFunctionTemplateSpecialization()) 14335 return false; 14336 14337 // Don't warn for OpenCL kernels. 14338 if (FD->hasAttr<OpenCLKernelAttr>()) 14339 return false; 14340 14341 // Don't warn on explicitly deleted functions. 14342 if (FD->isDeleted()) 14343 return false; 14344 14345 // Don't warn on implicitly local functions (such as having local-typed 14346 // parameters). 14347 if (!FD->isExternallyVisible()) 14348 return false; 14349 14350 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 14351 Prev; Prev = Prev->getPreviousDecl()) { 14352 // Ignore any declarations that occur in function or method 14353 // scope, because they aren't visible from the header. 14354 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 14355 continue; 14356 14357 PossiblePrototype = Prev; 14358 return Prev->getType()->isFunctionNoProtoType(); 14359 } 14360 14361 return true; 14362 } 14363 14364 void 14365 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 14366 const FunctionDecl *EffectiveDefinition, 14367 SkipBodyInfo *SkipBody) { 14368 const FunctionDecl *Definition = EffectiveDefinition; 14369 if (!Definition && 14370 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true)) 14371 return; 14372 14373 if (Definition->getFriendObjectKind() != Decl::FOK_None) { 14374 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) { 14375 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { 14376 // A merged copy of the same function, instantiated as a member of 14377 // the same class, is OK. 14378 if (declaresSameEntity(OrigFD, OrigDef) && 14379 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()), 14380 cast<Decl>(FD->getLexicalDeclContext()))) 14381 return; 14382 } 14383 } 14384 } 14385 14386 if (canRedefineFunction(Definition, getLangOpts())) 14387 return; 14388 14389 // Don't emit an error when this is redefinition of a typo-corrected 14390 // definition. 14391 if (TypoCorrectedFunctionDefinitions.count(Definition)) 14392 return; 14393 14394 // If we don't have a visible definition of the function, and it's inline or 14395 // a template, skip the new definition. 14396 if (SkipBody && !hasVisibleDefinition(Definition) && 14397 (Definition->getFormalLinkage() == InternalLinkage || 14398 Definition->isInlined() || 14399 Definition->getDescribedFunctionTemplate() || 14400 Definition->getNumTemplateParameterLists())) { 14401 SkipBody->ShouldSkip = true; 14402 SkipBody->Previous = const_cast<FunctionDecl*>(Definition); 14403 if (auto *TD = Definition->getDescribedFunctionTemplate()) 14404 makeMergedDefinitionVisible(TD); 14405 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 14406 return; 14407 } 14408 14409 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 14410 Definition->getStorageClass() == SC_Extern) 14411 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 14412 << FD << getLangOpts().CPlusPlus; 14413 else 14414 Diag(FD->getLocation(), diag::err_redefinition) << FD; 14415 14416 Diag(Definition->getLocation(), diag::note_previous_definition); 14417 FD->setInvalidDecl(); 14418 } 14419 14420 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 14421 Sema &S) { 14422 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 14423 14424 LambdaScopeInfo *LSI = S.PushLambdaScope(); 14425 LSI->CallOperator = CallOperator; 14426 LSI->Lambda = LambdaClass; 14427 LSI->ReturnType = CallOperator->getReturnType(); 14428 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 14429 14430 if (LCD == LCD_None) 14431 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 14432 else if (LCD == LCD_ByCopy) 14433 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 14434 else if (LCD == LCD_ByRef) 14435 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 14436 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 14437 14438 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 14439 LSI->Mutable = !CallOperator->isConst(); 14440 14441 // Add the captures to the LSI so they can be noted as already 14442 // captured within tryCaptureVar. 14443 auto I = LambdaClass->field_begin(); 14444 for (const auto &C : LambdaClass->captures()) { 14445 if (C.capturesVariable()) { 14446 VarDecl *VD = C.getCapturedVar(); 14447 if (VD->isInitCapture()) 14448 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 14449 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 14450 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 14451 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 14452 /*EllipsisLoc*/C.isPackExpansion() 14453 ? C.getEllipsisLoc() : SourceLocation(), 14454 I->getType(), /*Invalid*/false); 14455 14456 } else if (C.capturesThis()) { 14457 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(), 14458 C.getCaptureKind() == LCK_StarThis); 14459 } else { 14460 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(), 14461 I->getType()); 14462 } 14463 ++I; 14464 } 14465 } 14466 14467 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 14468 SkipBodyInfo *SkipBody) { 14469 if (!D) { 14470 // Parsing the function declaration failed in some way. Push on a fake scope 14471 // anyway so we can try to parse the function body. 14472 PushFunctionScope(); 14473 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 14474 return D; 14475 } 14476 14477 FunctionDecl *FD = nullptr; 14478 14479 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 14480 FD = FunTmpl->getTemplatedDecl(); 14481 else 14482 FD = cast<FunctionDecl>(D); 14483 14484 // Do not push if it is a lambda because one is already pushed when building 14485 // the lambda in ActOnStartOfLambdaDefinition(). 14486 if (!isLambdaCallOperator(FD)) 14487 PushExpressionEvaluationContext( 14488 FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated 14489 : ExprEvalContexts.back().Context); 14490 14491 // Check for defining attributes before the check for redefinition. 14492 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 14493 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 14494 FD->dropAttr<AliasAttr>(); 14495 FD->setInvalidDecl(); 14496 } 14497 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 14498 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 14499 FD->dropAttr<IFuncAttr>(); 14500 FD->setInvalidDecl(); 14501 } 14502 14503 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { 14504 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 14505 Ctor->isDefaultConstructor() && 14506 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 14507 // If this is an MS ABI dllexport default constructor, instantiate any 14508 // default arguments. 14509 InstantiateDefaultCtorDefaultArgs(Ctor); 14510 } 14511 } 14512 14513 // See if this is a redefinition. If 'will have body' (or similar) is already 14514 // set, then these checks were already performed when it was set. 14515 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() && 14516 !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) { 14517 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 14518 14519 // If we're skipping the body, we're done. Don't enter the scope. 14520 if (SkipBody && SkipBody->ShouldSkip) 14521 return D; 14522 } 14523 14524 // Mark this function as "will have a body eventually". This lets users to 14525 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 14526 // this function. 14527 FD->setWillHaveBody(); 14528 14529 // If we are instantiating a generic lambda call operator, push 14530 // a LambdaScopeInfo onto the function stack. But use the information 14531 // that's already been calculated (ActOnLambdaExpr) to prime the current 14532 // LambdaScopeInfo. 14533 // When the template operator is being specialized, the LambdaScopeInfo, 14534 // has to be properly restored so that tryCaptureVariable doesn't try 14535 // and capture any new variables. In addition when calculating potential 14536 // captures during transformation of nested lambdas, it is necessary to 14537 // have the LSI properly restored. 14538 if (isGenericLambdaCallOperatorSpecialization(FD)) { 14539 assert(inTemplateInstantiation() && 14540 "There should be an active template instantiation on the stack " 14541 "when instantiating a generic lambda!"); 14542 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 14543 } else { 14544 // Enter a new function scope 14545 PushFunctionScope(); 14546 } 14547 14548 // Builtin functions cannot be defined. 14549 if (unsigned BuiltinID = FD->getBuiltinID()) { 14550 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 14551 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 14552 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 14553 FD->setInvalidDecl(); 14554 } 14555 } 14556 14557 // The return type of a function definition must be complete 14558 // (C99 6.9.1p3, C++ [dcl.fct]p6). 14559 QualType ResultType = FD->getReturnType(); 14560 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 14561 !FD->isInvalidDecl() && 14562 RequireCompleteType(FD->getLocation(), ResultType, 14563 diag::err_func_def_incomplete_result)) 14564 FD->setInvalidDecl(); 14565 14566 if (FnBodyScope) 14567 PushDeclContext(FnBodyScope, FD); 14568 14569 // Check the validity of our function parameters 14570 CheckParmsForFunctionDef(FD->parameters(), 14571 /*CheckParameterNames=*/true); 14572 14573 // Add non-parameter declarations already in the function to the current 14574 // scope. 14575 if (FnBodyScope) { 14576 for (Decl *NPD : FD->decls()) { 14577 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 14578 if (!NonParmDecl) 14579 continue; 14580 assert(!isa<ParmVarDecl>(NonParmDecl) && 14581 "parameters should not be in newly created FD yet"); 14582 14583 // If the decl has a name, make it accessible in the current scope. 14584 if (NonParmDecl->getDeclName()) 14585 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 14586 14587 // Similarly, dive into enums and fish their constants out, making them 14588 // accessible in this scope. 14589 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 14590 for (auto *EI : ED->enumerators()) 14591 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 14592 } 14593 } 14594 } 14595 14596 // Introduce our parameters into the function scope 14597 for (auto Param : FD->parameters()) { 14598 Param->setOwningFunction(FD); 14599 14600 // If this has an identifier, add it to the scope stack. 14601 if (Param->getIdentifier() && FnBodyScope) { 14602 CheckShadow(FnBodyScope, Param); 14603 14604 PushOnScopeChains(Param, FnBodyScope); 14605 } 14606 } 14607 14608 // Ensure that the function's exception specification is instantiated. 14609 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 14610 ResolveExceptionSpec(D->getLocation(), FPT); 14611 14612 // dllimport cannot be applied to non-inline function definitions. 14613 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 14614 !FD->isTemplateInstantiation()) { 14615 assert(!FD->hasAttr<DLLExportAttr>()); 14616 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 14617 FD->setInvalidDecl(); 14618 return D; 14619 } 14620 // We want to attach documentation to original Decl (which might be 14621 // a function template). 14622 ActOnDocumentableDecl(D); 14623 if (getCurLexicalContext()->isObjCContainer() && 14624 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 14625 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 14626 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 14627 14628 return D; 14629 } 14630 14631 /// Given the set of return statements within a function body, 14632 /// compute the variables that are subject to the named return value 14633 /// optimization. 14634 /// 14635 /// Each of the variables that is subject to the named return value 14636 /// optimization will be marked as NRVO variables in the AST, and any 14637 /// return statement that has a marked NRVO variable as its NRVO candidate can 14638 /// use the named return value optimization. 14639 /// 14640 /// This function applies a very simplistic algorithm for NRVO: if every return 14641 /// statement in the scope of a variable has the same NRVO candidate, that 14642 /// candidate is an NRVO variable. 14643 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 14644 ReturnStmt **Returns = Scope->Returns.data(); 14645 14646 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 14647 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 14648 if (!NRVOCandidate->isNRVOVariable()) 14649 Returns[I]->setNRVOCandidate(nullptr); 14650 } 14651 } 14652 } 14653 14654 bool Sema::canDelayFunctionBody(const Declarator &D) { 14655 // We can't delay parsing the body of a constexpr function template (yet). 14656 if (D.getDeclSpec().hasConstexprSpecifier()) 14657 return false; 14658 14659 // We can't delay parsing the body of a function template with a deduced 14660 // return type (yet). 14661 if (D.getDeclSpec().hasAutoTypeSpec()) { 14662 // If the placeholder introduces a non-deduced trailing return type, 14663 // we can still delay parsing it. 14664 if (D.getNumTypeObjects()) { 14665 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 14666 if (Outer.Kind == DeclaratorChunk::Function && 14667 Outer.Fun.hasTrailingReturnType()) { 14668 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 14669 return Ty.isNull() || !Ty->isUndeducedType(); 14670 } 14671 } 14672 return false; 14673 } 14674 14675 return true; 14676 } 14677 14678 bool Sema::canSkipFunctionBody(Decl *D) { 14679 // We cannot skip the body of a function (or function template) which is 14680 // constexpr, since we may need to evaluate its body in order to parse the 14681 // rest of the file. 14682 // We cannot skip the body of a function with an undeduced return type, 14683 // because any callers of that function need to know the type. 14684 if (const FunctionDecl *FD = D->getAsFunction()) { 14685 if (FD->isConstexpr()) 14686 return false; 14687 // We can't simply call Type::isUndeducedType here, because inside template 14688 // auto can be deduced to a dependent type, which is not considered 14689 // "undeduced". 14690 if (FD->getReturnType()->getContainedDeducedType()) 14691 return false; 14692 } 14693 return Consumer.shouldSkipFunctionBody(D); 14694 } 14695 14696 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 14697 if (!Decl) 14698 return nullptr; 14699 if (FunctionDecl *FD = Decl->getAsFunction()) 14700 FD->setHasSkippedBody(); 14701 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) 14702 MD->setHasSkippedBody(); 14703 return Decl; 14704 } 14705 14706 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 14707 return ActOnFinishFunctionBody(D, BodyArg, false); 14708 } 14709 14710 /// RAII object that pops an ExpressionEvaluationContext when exiting a function 14711 /// body. 14712 class ExitFunctionBodyRAII { 14713 public: 14714 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {} 14715 ~ExitFunctionBodyRAII() { 14716 if (!IsLambda) 14717 S.PopExpressionEvaluationContext(); 14718 } 14719 14720 private: 14721 Sema &S; 14722 bool IsLambda = false; 14723 }; 14724 14725 static void diagnoseImplicitlyRetainedSelf(Sema &S) { 14726 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo; 14727 14728 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) { 14729 if (EscapeInfo.count(BD)) 14730 return EscapeInfo[BD]; 14731 14732 bool R = false; 14733 const BlockDecl *CurBD = BD; 14734 14735 do { 14736 R = !CurBD->doesNotEscape(); 14737 if (R) 14738 break; 14739 CurBD = CurBD->getParent()->getInnermostBlockDecl(); 14740 } while (CurBD); 14741 14742 return EscapeInfo[BD] = R; 14743 }; 14744 14745 // If the location where 'self' is implicitly retained is inside a escaping 14746 // block, emit a diagnostic. 14747 for (const std::pair<SourceLocation, const BlockDecl *> &P : 14748 S.ImplicitlyRetainedSelfLocs) 14749 if (IsOrNestedInEscapingBlock(P.second)) 14750 S.Diag(P.first, diag::warn_implicitly_retains_self) 14751 << FixItHint::CreateInsertion(P.first, "self->"); 14752 } 14753 14754 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 14755 bool IsInstantiation) { 14756 FunctionScopeInfo *FSI = getCurFunction(); 14757 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 14758 14759 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>()) 14760 FD->addAttr(StrictFPAttr::CreateImplicit(Context)); 14761 14762 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 14763 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 14764 14765 if (getLangOpts().Coroutines && FSI->isCoroutine()) 14766 CheckCompletedCoroutineBody(FD, Body); 14767 14768 { 14769 // Do not call PopExpressionEvaluationContext() if it is a lambda because 14770 // one is already popped when finishing the lambda in BuildLambdaExpr(). 14771 // This is meant to pop the context added in ActOnStartOfFunctionDef(). 14772 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD)); 14773 14774 if (FD) { 14775 FD->setBody(Body); 14776 FD->setWillHaveBody(false); 14777 14778 if (getLangOpts().CPlusPlus14) { 14779 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 14780 FD->getReturnType()->isUndeducedType()) { 14781 // For a function with a deduced result type to return void, 14782 // the result type as written must be 'auto' or 'decltype(auto)', 14783 // possibly cv-qualified or constrained, but not ref-qualified. 14784 if (!FD->getReturnType()->getAs<AutoType>()) { 14785 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 14786 << FD->getReturnType(); 14787 FD->setInvalidDecl(); 14788 } else { 14789 // Falling off the end of the function is the same as 'return;'. 14790 Expr *Dummy = nullptr; 14791 if (DeduceFunctionTypeFromReturnExpr( 14792 FD, dcl->getLocation(), Dummy, 14793 FD->getReturnType()->getAs<AutoType>())) 14794 FD->setInvalidDecl(); 14795 } 14796 } 14797 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 14798 // In C++11, we don't use 'auto' deduction rules for lambda call 14799 // operators because we don't support return type deduction. 14800 auto *LSI = getCurLambda(); 14801 if (LSI->HasImplicitReturnType) { 14802 deduceClosureReturnType(*LSI); 14803 14804 // C++11 [expr.prim.lambda]p4: 14805 // [...] if there are no return statements in the compound-statement 14806 // [the deduced type is] the type void 14807 QualType RetType = 14808 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 14809 14810 // Update the return type to the deduced type. 14811 const auto *Proto = FD->getType()->castAs<FunctionProtoType>(); 14812 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 14813 Proto->getExtProtoInfo())); 14814 } 14815 } 14816 14817 // If the function implicitly returns zero (like 'main') or is naked, 14818 // don't complain about missing return statements. 14819 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 14820 WP.disableCheckFallThrough(); 14821 14822 // MSVC permits the use of pure specifier (=0) on function definition, 14823 // defined at class scope, warn about this non-standard construct. 14824 if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine()) 14825 Diag(FD->getLocation(), diag::ext_pure_function_definition); 14826 14827 if (!FD->isInvalidDecl()) { 14828 // Don't diagnose unused parameters of defaulted, deleted or naked 14829 // functions. 14830 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() && 14831 !FD->hasAttr<NakedAttr>()) 14832 DiagnoseUnusedParameters(FD->parameters()); 14833 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 14834 FD->getReturnType(), FD); 14835 14836 // If this is a structor, we need a vtable. 14837 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 14838 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 14839 else if (CXXDestructorDecl *Destructor = 14840 dyn_cast<CXXDestructorDecl>(FD)) 14841 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 14842 14843 // Try to apply the named return value optimization. We have to check 14844 // if we can do this here because lambdas keep return statements around 14845 // to deduce an implicit return type. 14846 if (FD->getReturnType()->isRecordType() && 14847 (!getLangOpts().CPlusPlus || !FD->isDependentContext())) 14848 computeNRVO(Body, FSI); 14849 } 14850 14851 // GNU warning -Wmissing-prototypes: 14852 // Warn if a global function is defined without a previous 14853 // prototype declaration. This warning is issued even if the 14854 // definition itself provides a prototype. The aim is to detect 14855 // global functions that fail to be declared in header files. 14856 const FunctionDecl *PossiblePrototype = nullptr; 14857 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) { 14858 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 14859 14860 if (PossiblePrototype) { 14861 // We found a declaration that is not a prototype, 14862 // but that could be a zero-parameter prototype 14863 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) { 14864 TypeLoc TL = TI->getTypeLoc(); 14865 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 14866 Diag(PossiblePrototype->getLocation(), 14867 diag::note_declaration_not_a_prototype) 14868 << (FD->getNumParams() != 0) 14869 << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion( 14870 FTL.getRParenLoc(), "void") 14871 : FixItHint{}); 14872 } 14873 } else { 14874 // Returns true if the token beginning at this Loc is `const`. 14875 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM, 14876 const LangOptions &LangOpts) { 14877 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); 14878 if (LocInfo.first.isInvalid()) 14879 return false; 14880 14881 bool Invalid = false; 14882 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid); 14883 if (Invalid) 14884 return false; 14885 14886 if (LocInfo.second > Buffer.size()) 14887 return false; 14888 14889 const char *LexStart = Buffer.data() + LocInfo.second; 14890 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second); 14891 14892 return StartTok.consume_front("const") && 14893 (StartTok.empty() || isWhitespace(StartTok[0]) || 14894 StartTok.startswith("/*") || StartTok.startswith("//")); 14895 }; 14896 14897 auto findBeginLoc = [&]() { 14898 // If the return type has `const` qualifier, we want to insert 14899 // `static` before `const` (and not before the typename). 14900 if ((FD->getReturnType()->isAnyPointerType() && 14901 FD->getReturnType()->getPointeeType().isConstQualified()) || 14902 FD->getReturnType().isConstQualified()) { 14903 // But only do this if we can determine where the `const` is. 14904 14905 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(), 14906 getLangOpts())) 14907 14908 return FD->getBeginLoc(); 14909 } 14910 return FD->getTypeSpecStartLoc(); 14911 }; 14912 Diag(FD->getTypeSpecStartLoc(), 14913 diag::note_static_for_internal_linkage) 14914 << /* function */ 1 14915 << (FD->getStorageClass() == SC_None 14916 ? FixItHint::CreateInsertion(findBeginLoc(), "static ") 14917 : FixItHint{}); 14918 } 14919 } 14920 14921 // If the function being defined does not have a prototype, then we may 14922 // need to diagnose it as changing behavior in C2x because we now know 14923 // whether the function accepts arguments or not. This only handles the 14924 // case where the definition has no prototype but does have parameters 14925 // and either there is no previous potential prototype, or the previous 14926 // potential prototype also has no actual prototype. This handles cases 14927 // like: 14928 // void f(); void f(a) int a; {} 14929 // void g(a) int a; {} 14930 // See MergeFunctionDecl() for other cases of the behavior change 14931 // diagnostic. See GetFullTypeForDeclarator() for handling of a function 14932 // type without a prototype. 14933 if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 && 14934 (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() && 14935 !PossiblePrototype->isImplicit()))) { 14936 // The function definition has parameters, so this will change behavior 14937 // in C2x. If there is a possible prototype, it comes before the 14938 // function definition. 14939 // FIXME: The declaration may have already been diagnosed as being 14940 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but 14941 // there's no way to test for the "changes behavior" condition in 14942 // SemaType.cpp when forming the declaration's function type. So, we do 14943 // this awkward dance instead. 14944 // 14945 // If we have a possible prototype and it declares a function with a 14946 // prototype, we don't want to diagnose it; if we have a possible 14947 // prototype and it has no prototype, it may have already been 14948 // diagnosed in SemaType.cpp as deprecated depending on whether 14949 // -Wstrict-prototypes is enabled. If we already warned about it being 14950 // deprecated, add a note that it also changes behavior. If we didn't 14951 // warn about it being deprecated (because the diagnostic is not 14952 // enabled), warn now that it is deprecated and changes behavior. 14953 bool AddNote = false; 14954 if (PossiblePrototype) { 14955 if (Diags.isIgnored(diag::warn_strict_prototypes, 14956 PossiblePrototype->getLocation())) { 14957 14958 PartialDiagnostic PD = 14959 PDiag(diag::warn_non_prototype_changes_behavior); 14960 if (TypeSourceInfo *TSI = PossiblePrototype->getTypeSourceInfo()) { 14961 if (auto FTL = TSI->getTypeLoc().getAs<FunctionNoProtoTypeLoc>()) 14962 PD << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); 14963 } 14964 Diag(PossiblePrototype->getLocation(), PD); 14965 } else { 14966 AddNote = true; 14967 } 14968 } 14969 14970 // Because this function definition has no prototype and it has 14971 // parameters, it will definitely change behavior in C2x. 14972 Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior); 14973 if (AddNote) 14974 Diag(PossiblePrototype->getLocation(), 14975 diag::note_func_decl_changes_behavior); 14976 } 14977 14978 // Warn on CPUDispatch with an actual body. 14979 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body) 14980 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body)) 14981 if (!CmpndBody->body_empty()) 14982 Diag(CmpndBody->body_front()->getBeginLoc(), 14983 diag::warn_dispatch_body_ignored); 14984 14985 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 14986 const CXXMethodDecl *KeyFunction; 14987 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 14988 MD->isVirtual() && 14989 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 14990 MD == KeyFunction->getCanonicalDecl()) { 14991 // Update the key-function state if necessary for this ABI. 14992 if (FD->isInlined() && 14993 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 14994 Context.setNonKeyFunction(MD); 14995 14996 // If the newly-chosen key function is already defined, then we 14997 // need to mark the vtable as used retroactively. 14998 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 14999 const FunctionDecl *Definition; 15000 if (KeyFunction && KeyFunction->isDefined(Definition)) 15001 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 15002 } else { 15003 // We just defined they key function; mark the vtable as used. 15004 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 15005 } 15006 } 15007 } 15008 15009 assert( 15010 (FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 15011 "Function parsing confused"); 15012 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 15013 assert(MD == getCurMethodDecl() && "Method parsing confused"); 15014 MD->setBody(Body); 15015 if (!MD->isInvalidDecl()) { 15016 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 15017 MD->getReturnType(), MD); 15018 15019 if (Body) 15020 computeNRVO(Body, FSI); 15021 } 15022 if (FSI->ObjCShouldCallSuper) { 15023 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call) 15024 << MD->getSelector().getAsString(); 15025 FSI->ObjCShouldCallSuper = false; 15026 } 15027 if (FSI->ObjCWarnForNoDesignatedInitChain) { 15028 const ObjCMethodDecl *InitMethod = nullptr; 15029 bool isDesignated = 15030 MD->isDesignatedInitializerForTheInterface(&InitMethod); 15031 assert(isDesignated && InitMethod); 15032 (void)isDesignated; 15033 15034 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 15035 auto IFace = MD->getClassInterface(); 15036 if (!IFace) 15037 return false; 15038 auto SuperD = IFace->getSuperClass(); 15039 if (!SuperD) 15040 return false; 15041 return SuperD->getIdentifier() == 15042 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 15043 }; 15044 // Don't issue this warning for unavailable inits or direct subclasses 15045 // of NSObject. 15046 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 15047 Diag(MD->getLocation(), 15048 diag::warn_objc_designated_init_missing_super_call); 15049 Diag(InitMethod->getLocation(), 15050 diag::note_objc_designated_init_marked_here); 15051 } 15052 FSI->ObjCWarnForNoDesignatedInitChain = false; 15053 } 15054 if (FSI->ObjCWarnForNoInitDelegation) { 15055 // Don't issue this warning for unavaialable inits. 15056 if (!MD->isUnavailable()) 15057 Diag(MD->getLocation(), 15058 diag::warn_objc_secondary_init_missing_init_call); 15059 FSI->ObjCWarnForNoInitDelegation = false; 15060 } 15061 15062 diagnoseImplicitlyRetainedSelf(*this); 15063 } else { 15064 // Parsing the function declaration failed in some way. Pop the fake scope 15065 // we pushed on. 15066 PopFunctionScopeInfo(ActivePolicy, dcl); 15067 return nullptr; 15068 } 15069 15070 if (Body && FSI->HasPotentialAvailabilityViolations) 15071 DiagnoseUnguardedAvailabilityViolations(dcl); 15072 15073 assert(!FSI->ObjCShouldCallSuper && 15074 "This should only be set for ObjC methods, which should have been " 15075 "handled in the block above."); 15076 15077 // Verify and clean out per-function state. 15078 if (Body && (!FD || !FD->isDefaulted())) { 15079 // C++ constructors that have function-try-blocks can't have return 15080 // statements in the handlers of that block. (C++ [except.handle]p14) 15081 // Verify this. 15082 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 15083 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 15084 15085 // Verify that gotos and switch cases don't jump into scopes illegally. 15086 if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled()) 15087 DiagnoseInvalidJumps(Body); 15088 15089 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 15090 if (!Destructor->getParent()->isDependentType()) 15091 CheckDestructor(Destructor); 15092 15093 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 15094 Destructor->getParent()); 15095 } 15096 15097 // If any errors have occurred, clear out any temporaries that may have 15098 // been leftover. This ensures that these temporaries won't be picked up 15099 // for deletion in some later function. 15100 if (hasUncompilableErrorOccurred() || 15101 getDiagnostics().getSuppressAllDiagnostics()) { 15102 DiscardCleanupsInEvaluationContext(); 15103 } 15104 if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) { 15105 // Since the body is valid, issue any analysis-based warnings that are 15106 // enabled. 15107 ActivePolicy = &WP; 15108 } 15109 15110 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 15111 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose)) 15112 FD->setInvalidDecl(); 15113 15114 if (FD && FD->hasAttr<NakedAttr>()) { 15115 for (const Stmt *S : Body->children()) { 15116 // Allow local register variables without initializer as they don't 15117 // require prologue. 15118 bool RegisterVariables = false; 15119 if (auto *DS = dyn_cast<DeclStmt>(S)) { 15120 for (const auto *Decl : DS->decls()) { 15121 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 15122 RegisterVariables = 15123 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 15124 if (!RegisterVariables) 15125 break; 15126 } 15127 } 15128 } 15129 if (RegisterVariables) 15130 continue; 15131 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 15132 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function); 15133 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 15134 FD->setInvalidDecl(); 15135 break; 15136 } 15137 } 15138 } 15139 15140 assert(ExprCleanupObjects.size() == 15141 ExprEvalContexts.back().NumCleanupObjects && 15142 "Leftover temporaries in function"); 15143 assert(!Cleanup.exprNeedsCleanups() && 15144 "Unaccounted cleanups in function"); 15145 assert(MaybeODRUseExprs.empty() && 15146 "Leftover expressions for odr-use checking"); 15147 } 15148 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop 15149 // the declaration context below. Otherwise, we're unable to transform 15150 // 'this' expressions when transforming immediate context functions. 15151 15152 if (!IsInstantiation) 15153 PopDeclContext(); 15154 15155 PopFunctionScopeInfo(ActivePolicy, dcl); 15156 // If any errors have occurred, clear out any temporaries that may have 15157 // been leftover. This ensures that these temporaries won't be picked up for 15158 // deletion in some later function. 15159 if (hasUncompilableErrorOccurred()) { 15160 DiscardCleanupsInEvaluationContext(); 15161 } 15162 15163 if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsDevice || 15164 !LangOpts.OMPTargetTriples.empty())) || 15165 LangOpts.CUDA || LangOpts.SYCLIsDevice)) { 15166 auto ES = getEmissionStatus(FD); 15167 if (ES == Sema::FunctionEmissionStatus::Emitted || 15168 ES == Sema::FunctionEmissionStatus::Unknown) 15169 DeclsToCheckForDeferredDiags.insert(FD); 15170 } 15171 15172 if (FD && !FD->isDeleted()) 15173 checkTypeSupport(FD->getType(), FD->getLocation(), FD); 15174 15175 return dcl; 15176 } 15177 15178 /// When we finish delayed parsing of an attribute, we must attach it to the 15179 /// relevant Decl. 15180 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 15181 ParsedAttributes &Attrs) { 15182 // Always attach attributes to the underlying decl. 15183 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 15184 D = TD->getTemplatedDecl(); 15185 ProcessDeclAttributeList(S, D, Attrs); 15186 15187 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 15188 if (Method->isStatic()) 15189 checkThisInStaticMemberFunctionAttributes(Method); 15190 } 15191 15192 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 15193 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 15194 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 15195 IdentifierInfo &II, Scope *S) { 15196 // Find the scope in which the identifier is injected and the corresponding 15197 // DeclContext. 15198 // FIXME: C89 does not say what happens if there is no enclosing block scope. 15199 // In that case, we inject the declaration into the translation unit scope 15200 // instead. 15201 Scope *BlockScope = S; 15202 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) 15203 BlockScope = BlockScope->getParent(); 15204 15205 Scope *ContextScope = BlockScope; 15206 while (!ContextScope->getEntity()) 15207 ContextScope = ContextScope->getParent(); 15208 ContextRAII SavedContext(*this, ContextScope->getEntity()); 15209 15210 // Before we produce a declaration for an implicitly defined 15211 // function, see whether there was a locally-scoped declaration of 15212 // this name as a function or variable. If so, use that 15213 // (non-visible) declaration, and complain about it. 15214 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); 15215 if (ExternCPrev) { 15216 // We still need to inject the function into the enclosing block scope so 15217 // that later (non-call) uses can see it. 15218 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); 15219 15220 // C89 footnote 38: 15221 // If in fact it is not defined as having type "function returning int", 15222 // the behavior is undefined. 15223 if (!isa<FunctionDecl>(ExternCPrev) || 15224 !Context.typesAreCompatible( 15225 cast<FunctionDecl>(ExternCPrev)->getType(), 15226 Context.getFunctionNoProtoType(Context.IntTy))) { 15227 Diag(Loc, diag::ext_use_out_of_scope_declaration) 15228 << ExternCPrev << !getLangOpts().C99; 15229 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 15230 return ExternCPrev; 15231 } 15232 } 15233 15234 // Extension in C99. Legal in C90, but warn about it. 15235 unsigned diag_id; 15236 if (II.getName().startswith("__builtin_")) 15237 diag_id = diag::warn_builtin_unknown; 15238 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. 15239 else if (getLangOpts().OpenCL) 15240 diag_id = diag::err_opencl_implicit_function_decl; 15241 else if (getLangOpts().C99) 15242 diag_id = diag::ext_implicit_function_decl; 15243 else 15244 diag_id = diag::warn_implicit_function_decl; 15245 15246 TypoCorrection Corrected; 15247 // Because typo correction is expensive, only do it if the implicit 15248 // function declaration is going to be treated as an error. 15249 // 15250 // Perform the corection before issuing the main diagnostic, as some consumers 15251 // use typo-correction callbacks to enhance the main diagnostic. 15252 if (S && !ExternCPrev && 15253 (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) { 15254 DeclFilterCCC<FunctionDecl> CCC{}; 15255 Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName, 15256 S, nullptr, CCC, CTK_NonError); 15257 } 15258 15259 Diag(Loc, diag_id) << &II; 15260 if (Corrected) 15261 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 15262 /*ErrorRecovery*/ false); 15263 15264 // If we found a prior declaration of this function, don't bother building 15265 // another one. We've already pushed that one into scope, so there's nothing 15266 // more to do. 15267 if (ExternCPrev) 15268 return ExternCPrev; 15269 15270 // Set a Declarator for the implicit definition: int foo(); 15271 const char *Dummy; 15272 AttributeFactory attrFactory; 15273 DeclSpec DS(attrFactory); 15274 unsigned DiagID; 15275 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 15276 Context.getPrintingPolicy()); 15277 (void)Error; // Silence warning. 15278 assert(!Error && "Error setting up implicit decl!"); 15279 SourceLocation NoLoc; 15280 Declarator D(DS, DeclaratorContext::Block); 15281 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 15282 /*IsAmbiguous=*/false, 15283 /*LParenLoc=*/NoLoc, 15284 /*Params=*/nullptr, 15285 /*NumParams=*/0, 15286 /*EllipsisLoc=*/NoLoc, 15287 /*RParenLoc=*/NoLoc, 15288 /*RefQualifierIsLvalueRef=*/true, 15289 /*RefQualifierLoc=*/NoLoc, 15290 /*MutableLoc=*/NoLoc, EST_None, 15291 /*ESpecRange=*/SourceRange(), 15292 /*Exceptions=*/nullptr, 15293 /*ExceptionRanges=*/nullptr, 15294 /*NumExceptions=*/0, 15295 /*NoexceptExpr=*/nullptr, 15296 /*ExceptionSpecTokens=*/nullptr, 15297 /*DeclsInPrototype=*/None, Loc, 15298 Loc, D), 15299 std::move(DS.getAttributes()), SourceLocation()); 15300 D.SetIdentifier(&II, Loc); 15301 15302 // Insert this function into the enclosing block scope. 15303 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); 15304 FD->setImplicit(); 15305 15306 AddKnownFunctionAttributes(FD); 15307 15308 return FD; 15309 } 15310 15311 /// If this function is a C++ replaceable global allocation function 15312 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]), 15313 /// adds any function attributes that we know a priori based on the standard. 15314 /// 15315 /// We need to check for duplicate attributes both here and where user-written 15316 /// attributes are applied to declarations. 15317 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction( 15318 FunctionDecl *FD) { 15319 if (FD->isInvalidDecl()) 15320 return; 15321 15322 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New && 15323 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New) 15324 return; 15325 15326 Optional<unsigned> AlignmentParam; 15327 bool IsNothrow = false; 15328 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow)) 15329 return; 15330 15331 // C++2a [basic.stc.dynamic.allocation]p4: 15332 // An allocation function that has a non-throwing exception specification 15333 // indicates failure by returning a null pointer value. Any other allocation 15334 // function never returns a null pointer value and indicates failure only by 15335 // throwing an exception [...] 15336 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>()) 15337 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation())); 15338 15339 // C++2a [basic.stc.dynamic.allocation]p2: 15340 // An allocation function attempts to allocate the requested amount of 15341 // storage. [...] If the request succeeds, the value returned by a 15342 // replaceable allocation function is a [...] pointer value p0 different 15343 // from any previously returned value p1 [...] 15344 // 15345 // However, this particular information is being added in codegen, 15346 // because there is an opt-out switch for it (-fno-assume-sane-operator-new) 15347 15348 // C++2a [basic.stc.dynamic.allocation]p2: 15349 // An allocation function attempts to allocate the requested amount of 15350 // storage. If it is successful, it returns the address of the start of a 15351 // block of storage whose length in bytes is at least as large as the 15352 // requested size. 15353 if (!FD->hasAttr<AllocSizeAttr>()) { 15354 FD->addAttr(AllocSizeAttr::CreateImplicit( 15355 Context, /*ElemSizeParam=*/ParamIdx(1, FD), 15356 /*NumElemsParam=*/ParamIdx(), FD->getLocation())); 15357 } 15358 15359 // C++2a [basic.stc.dynamic.allocation]p3: 15360 // For an allocation function [...], the pointer returned on a successful 15361 // call shall represent the address of storage that is aligned as follows: 15362 // (3.1) If the allocation function takes an argument of type 15363 // std::align_val_t, the storage will have the alignment 15364 // specified by the value of this argument. 15365 if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) { 15366 FD->addAttr(AllocAlignAttr::CreateImplicit( 15367 Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation())); 15368 } 15369 15370 // FIXME: 15371 // C++2a [basic.stc.dynamic.allocation]p3: 15372 // For an allocation function [...], the pointer returned on a successful 15373 // call shall represent the address of storage that is aligned as follows: 15374 // (3.2) Otherwise, if the allocation function is named operator new[], 15375 // the storage is aligned for any object that does not have 15376 // new-extended alignment ([basic.align]) and is no larger than the 15377 // requested size. 15378 // (3.3) Otherwise, the storage is aligned for any object that does not 15379 // have new-extended alignment and is of the requested size. 15380 } 15381 15382 /// Adds any function attributes that we know a priori based on 15383 /// the declaration of this function. 15384 /// 15385 /// These attributes can apply both to implicitly-declared builtins 15386 /// (like __builtin___printf_chk) or to library-declared functions 15387 /// like NSLog or printf. 15388 /// 15389 /// We need to check for duplicate attributes both here and where user-written 15390 /// attributes are applied to declarations. 15391 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 15392 if (FD->isInvalidDecl()) 15393 return; 15394 15395 // If this is a built-in function, map its builtin attributes to 15396 // actual attributes. 15397 if (unsigned BuiltinID = FD->getBuiltinID()) { 15398 // Handle printf-formatting attributes. 15399 unsigned FormatIdx; 15400 bool HasVAListArg; 15401 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 15402 if (!FD->hasAttr<FormatAttr>()) { 15403 const char *fmt = "printf"; 15404 unsigned int NumParams = FD->getNumParams(); 15405 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 15406 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 15407 fmt = "NSString"; 15408 FD->addAttr(FormatAttr::CreateImplicit(Context, 15409 &Context.Idents.get(fmt), 15410 FormatIdx+1, 15411 HasVAListArg ? 0 : FormatIdx+2, 15412 FD->getLocation())); 15413 } 15414 } 15415 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 15416 HasVAListArg)) { 15417 if (!FD->hasAttr<FormatAttr>()) 15418 FD->addAttr(FormatAttr::CreateImplicit(Context, 15419 &Context.Idents.get("scanf"), 15420 FormatIdx+1, 15421 HasVAListArg ? 0 : FormatIdx+2, 15422 FD->getLocation())); 15423 } 15424 15425 // Handle automatically recognized callbacks. 15426 SmallVector<int, 4> Encoding; 15427 if (!FD->hasAttr<CallbackAttr>() && 15428 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding)) 15429 FD->addAttr(CallbackAttr::CreateImplicit( 15430 Context, Encoding.data(), Encoding.size(), FD->getLocation())); 15431 15432 // Mark const if we don't care about errno and that is the only thing 15433 // preventing the function from being const. This allows IRgen to use LLVM 15434 // intrinsics for such functions. 15435 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() && 15436 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) 15437 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 15438 15439 // We make "fma" on GNU or Windows const because we know it does not set 15440 // errno in those environments even though it could set errno based on the 15441 // C standard. 15442 const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); 15443 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) && 15444 !FD->hasAttr<ConstAttr>()) { 15445 switch (BuiltinID) { 15446 case Builtin::BI__builtin_fma: 15447 case Builtin::BI__builtin_fmaf: 15448 case Builtin::BI__builtin_fmal: 15449 case Builtin::BIfma: 15450 case Builtin::BIfmaf: 15451 case Builtin::BIfmal: 15452 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 15453 break; 15454 default: 15455 break; 15456 } 15457 } 15458 15459 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 15460 !FD->hasAttr<ReturnsTwiceAttr>()) 15461 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 15462 FD->getLocation())); 15463 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 15464 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 15465 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 15466 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 15467 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 15468 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 15469 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 15470 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 15471 // Add the appropriate attribute, depending on the CUDA compilation mode 15472 // and which target the builtin belongs to. For example, during host 15473 // compilation, aux builtins are __device__, while the rest are __host__. 15474 if (getLangOpts().CUDAIsDevice != 15475 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 15476 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 15477 else 15478 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 15479 } 15480 15481 // Add known guaranteed alignment for allocation functions. 15482 switch (BuiltinID) { 15483 case Builtin::BImemalign: 15484 case Builtin::BIaligned_alloc: 15485 if (!FD->hasAttr<AllocAlignAttr>()) 15486 FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD), 15487 FD->getLocation())); 15488 break; 15489 default: 15490 break; 15491 } 15492 15493 // Add allocsize attribute for allocation functions. 15494 switch (BuiltinID) { 15495 case Builtin::BIcalloc: 15496 FD->addAttr(AllocSizeAttr::CreateImplicit( 15497 Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation())); 15498 break; 15499 case Builtin::BImemalign: 15500 case Builtin::BIaligned_alloc: 15501 case Builtin::BIrealloc: 15502 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD), 15503 ParamIdx(), FD->getLocation())); 15504 break; 15505 case Builtin::BImalloc: 15506 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD), 15507 ParamIdx(), FD->getLocation())); 15508 break; 15509 default: 15510 break; 15511 } 15512 } 15513 15514 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD); 15515 15516 // If C++ exceptions are enabled but we are told extern "C" functions cannot 15517 // throw, add an implicit nothrow attribute to any extern "C" function we come 15518 // across. 15519 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 15520 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 15521 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 15522 if (!FPT || FPT->getExceptionSpecType() == EST_None) 15523 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 15524 } 15525 15526 IdentifierInfo *Name = FD->getIdentifier(); 15527 if (!Name) 15528 return; 15529 if ((!getLangOpts().CPlusPlus && 15530 FD->getDeclContext()->isTranslationUnit()) || 15531 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 15532 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 15533 LinkageSpecDecl::lang_c)) { 15534 // Okay: this could be a libc/libm/Objective-C function we know 15535 // about. 15536 } else 15537 return; 15538 15539 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 15540 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 15541 // target-specific builtins, perhaps? 15542 if (!FD->hasAttr<FormatAttr>()) 15543 FD->addAttr(FormatAttr::CreateImplicit(Context, 15544 &Context.Idents.get("printf"), 2, 15545 Name->isStr("vasprintf") ? 0 : 3, 15546 FD->getLocation())); 15547 } 15548 15549 if (Name->isStr("__CFStringMakeConstantString")) { 15550 // We already have a __builtin___CFStringMakeConstantString, 15551 // but builds that use -fno-constant-cfstrings don't go through that. 15552 if (!FD->hasAttr<FormatArgAttr>()) 15553 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), 15554 FD->getLocation())); 15555 } 15556 } 15557 15558 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 15559 TypeSourceInfo *TInfo) { 15560 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 15561 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 15562 15563 if (!TInfo) { 15564 assert(D.isInvalidType() && "no declarator info for valid type"); 15565 TInfo = Context.getTrivialTypeSourceInfo(T); 15566 } 15567 15568 // Scope manipulation handled by caller. 15569 TypedefDecl *NewTD = 15570 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(), 15571 D.getIdentifierLoc(), D.getIdentifier(), TInfo); 15572 15573 // Bail out immediately if we have an invalid declaration. 15574 if (D.isInvalidType()) { 15575 NewTD->setInvalidDecl(); 15576 return NewTD; 15577 } 15578 15579 if (D.getDeclSpec().isModulePrivateSpecified()) { 15580 if (CurContext->isFunctionOrMethod()) 15581 Diag(NewTD->getLocation(), diag::err_module_private_local) 15582 << 2 << NewTD 15583 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 15584 << FixItHint::CreateRemoval( 15585 D.getDeclSpec().getModulePrivateSpecLoc()); 15586 else 15587 NewTD->setModulePrivate(); 15588 } 15589 15590 // C++ [dcl.typedef]p8: 15591 // If the typedef declaration defines an unnamed class (or 15592 // enum), the first typedef-name declared by the declaration 15593 // to be that class type (or enum type) is used to denote the 15594 // class type (or enum type) for linkage purposes only. 15595 // We need to check whether the type was declared in the declaration. 15596 switch (D.getDeclSpec().getTypeSpecType()) { 15597 case TST_enum: 15598 case TST_struct: 15599 case TST_interface: 15600 case TST_union: 15601 case TST_class: { 15602 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 15603 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 15604 break; 15605 } 15606 15607 default: 15608 break; 15609 } 15610 15611 return NewTD; 15612 } 15613 15614 /// Check that this is a valid underlying type for an enum declaration. 15615 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 15616 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 15617 QualType T = TI->getType(); 15618 15619 if (T->isDependentType()) 15620 return false; 15621 15622 // This doesn't use 'isIntegralType' despite the error message mentioning 15623 // integral type because isIntegralType would also allow enum types in C. 15624 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 15625 if (BT->isInteger()) 15626 return false; 15627 15628 if (T->isBitIntType()) 15629 return false; 15630 15631 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 15632 } 15633 15634 /// Check whether this is a valid redeclaration of a previous enumeration. 15635 /// \return true if the redeclaration was invalid. 15636 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 15637 QualType EnumUnderlyingTy, bool IsFixed, 15638 const EnumDecl *Prev) { 15639 if (IsScoped != Prev->isScoped()) { 15640 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 15641 << Prev->isScoped(); 15642 Diag(Prev->getLocation(), diag::note_previous_declaration); 15643 return true; 15644 } 15645 15646 if (IsFixed && Prev->isFixed()) { 15647 if (!EnumUnderlyingTy->isDependentType() && 15648 !Prev->getIntegerType()->isDependentType() && 15649 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 15650 Prev->getIntegerType())) { 15651 // TODO: Highlight the underlying type of the redeclaration. 15652 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 15653 << EnumUnderlyingTy << Prev->getIntegerType(); 15654 Diag(Prev->getLocation(), diag::note_previous_declaration) 15655 << Prev->getIntegerTypeRange(); 15656 return true; 15657 } 15658 } else if (IsFixed != Prev->isFixed()) { 15659 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 15660 << Prev->isFixed(); 15661 Diag(Prev->getLocation(), diag::note_previous_declaration); 15662 return true; 15663 } 15664 15665 return false; 15666 } 15667 15668 /// Get diagnostic %select index for tag kind for 15669 /// redeclaration diagnostic message. 15670 /// WARNING: Indexes apply to particular diagnostics only! 15671 /// 15672 /// \returns diagnostic %select index. 15673 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 15674 switch (Tag) { 15675 case TTK_Struct: return 0; 15676 case TTK_Interface: return 1; 15677 case TTK_Class: return 2; 15678 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 15679 } 15680 } 15681 15682 /// Determine if tag kind is a class-key compatible with 15683 /// class for redeclaration (class, struct, or __interface). 15684 /// 15685 /// \returns true iff the tag kind is compatible. 15686 static bool isClassCompatTagKind(TagTypeKind Tag) 15687 { 15688 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 15689 } 15690 15691 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 15692 TagTypeKind TTK) { 15693 if (isa<TypedefDecl>(PrevDecl)) 15694 return NTK_Typedef; 15695 else if (isa<TypeAliasDecl>(PrevDecl)) 15696 return NTK_TypeAlias; 15697 else if (isa<ClassTemplateDecl>(PrevDecl)) 15698 return NTK_Template; 15699 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 15700 return NTK_TypeAliasTemplate; 15701 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 15702 return NTK_TemplateTemplateArgument; 15703 switch (TTK) { 15704 case TTK_Struct: 15705 case TTK_Interface: 15706 case TTK_Class: 15707 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 15708 case TTK_Union: 15709 return NTK_NonUnion; 15710 case TTK_Enum: 15711 return NTK_NonEnum; 15712 } 15713 llvm_unreachable("invalid TTK"); 15714 } 15715 15716 /// Determine whether a tag with a given kind is acceptable 15717 /// as a redeclaration of the given tag declaration. 15718 /// 15719 /// \returns true if the new tag kind is acceptable, false otherwise. 15720 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 15721 TagTypeKind NewTag, bool isDefinition, 15722 SourceLocation NewTagLoc, 15723 const IdentifierInfo *Name) { 15724 // C++ [dcl.type.elab]p3: 15725 // The class-key or enum keyword present in the 15726 // elaborated-type-specifier shall agree in kind with the 15727 // declaration to which the name in the elaborated-type-specifier 15728 // refers. This rule also applies to the form of 15729 // elaborated-type-specifier that declares a class-name or 15730 // friend class since it can be construed as referring to the 15731 // definition of the class. Thus, in any 15732 // elaborated-type-specifier, the enum keyword shall be used to 15733 // refer to an enumeration (7.2), the union class-key shall be 15734 // used to refer to a union (clause 9), and either the class or 15735 // struct class-key shall be used to refer to a class (clause 9) 15736 // declared using the class or struct class-key. 15737 TagTypeKind OldTag = Previous->getTagKind(); 15738 if (OldTag != NewTag && 15739 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag))) 15740 return false; 15741 15742 // Tags are compatible, but we might still want to warn on mismatched tags. 15743 // Non-class tags can't be mismatched at this point. 15744 if (!isClassCompatTagKind(NewTag)) 15745 return true; 15746 15747 // Declarations for which -Wmismatched-tags is disabled are entirely ignored 15748 // by our warning analysis. We don't want to warn about mismatches with (eg) 15749 // declarations in system headers that are designed to be specialized, but if 15750 // a user asks us to warn, we should warn if their code contains mismatched 15751 // declarations. 15752 auto IsIgnoredLoc = [&](SourceLocation Loc) { 15753 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch, 15754 Loc); 15755 }; 15756 if (IsIgnoredLoc(NewTagLoc)) 15757 return true; 15758 15759 auto IsIgnored = [&](const TagDecl *Tag) { 15760 return IsIgnoredLoc(Tag->getLocation()); 15761 }; 15762 while (IsIgnored(Previous)) { 15763 Previous = Previous->getPreviousDecl(); 15764 if (!Previous) 15765 return true; 15766 OldTag = Previous->getTagKind(); 15767 } 15768 15769 bool isTemplate = false; 15770 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 15771 isTemplate = Record->getDescribedClassTemplate(); 15772 15773 if (inTemplateInstantiation()) { 15774 if (OldTag != NewTag) { 15775 // In a template instantiation, do not offer fix-its for tag mismatches 15776 // since they usually mess up the template instead of fixing the problem. 15777 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15778 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15779 << getRedeclDiagFromTagKind(OldTag); 15780 // FIXME: Note previous location? 15781 } 15782 return true; 15783 } 15784 15785 if (isDefinition) { 15786 // On definitions, check all previous tags and issue a fix-it for each 15787 // one that doesn't match the current tag. 15788 if (Previous->getDefinition()) { 15789 // Don't suggest fix-its for redefinitions. 15790 return true; 15791 } 15792 15793 bool previousMismatch = false; 15794 for (const TagDecl *I : Previous->redecls()) { 15795 if (I->getTagKind() != NewTag) { 15796 // Ignore previous declarations for which the warning was disabled. 15797 if (IsIgnored(I)) 15798 continue; 15799 15800 if (!previousMismatch) { 15801 previousMismatch = true; 15802 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 15803 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15804 << getRedeclDiagFromTagKind(I->getTagKind()); 15805 } 15806 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 15807 << getRedeclDiagFromTagKind(NewTag) 15808 << FixItHint::CreateReplacement(I->getInnerLocStart(), 15809 TypeWithKeyword::getTagTypeKindName(NewTag)); 15810 } 15811 } 15812 return true; 15813 } 15814 15815 // Identify the prevailing tag kind: this is the kind of the definition (if 15816 // there is a non-ignored definition), or otherwise the kind of the prior 15817 // (non-ignored) declaration. 15818 const TagDecl *PrevDef = Previous->getDefinition(); 15819 if (PrevDef && IsIgnored(PrevDef)) 15820 PrevDef = nullptr; 15821 const TagDecl *Redecl = PrevDef ? PrevDef : Previous; 15822 if (Redecl->getTagKind() != NewTag) { 15823 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15824 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15825 << getRedeclDiagFromTagKind(OldTag); 15826 Diag(Redecl->getLocation(), diag::note_previous_use); 15827 15828 // If there is a previous definition, suggest a fix-it. 15829 if (PrevDef) { 15830 Diag(NewTagLoc, diag::note_struct_class_suggestion) 15831 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 15832 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 15833 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 15834 } 15835 } 15836 15837 return true; 15838 } 15839 15840 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 15841 /// from an outer enclosing namespace or file scope inside a friend declaration. 15842 /// This should provide the commented out code in the following snippet: 15843 /// namespace N { 15844 /// struct X; 15845 /// namespace M { 15846 /// struct Y { friend struct /*N::*/ X; }; 15847 /// } 15848 /// } 15849 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 15850 SourceLocation NameLoc) { 15851 // While the decl is in a namespace, do repeated lookup of that name and see 15852 // if we get the same namespace back. If we do not, continue until 15853 // translation unit scope, at which point we have a fully qualified NNS. 15854 SmallVector<IdentifierInfo *, 4> Namespaces; 15855 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15856 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 15857 // This tag should be declared in a namespace, which can only be enclosed by 15858 // other namespaces. Bail if there's an anonymous namespace in the chain. 15859 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 15860 if (!Namespace || Namespace->isAnonymousNamespace()) 15861 return FixItHint(); 15862 IdentifierInfo *II = Namespace->getIdentifier(); 15863 Namespaces.push_back(II); 15864 NamedDecl *Lookup = SemaRef.LookupSingleName( 15865 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 15866 if (Lookup == Namespace) 15867 break; 15868 } 15869 15870 // Once we have all the namespaces, reverse them to go outermost first, and 15871 // build an NNS. 15872 SmallString<64> Insertion; 15873 llvm::raw_svector_ostream OS(Insertion); 15874 if (DC->isTranslationUnit()) 15875 OS << "::"; 15876 std::reverse(Namespaces.begin(), Namespaces.end()); 15877 for (auto *II : Namespaces) 15878 OS << II->getName() << "::"; 15879 return FixItHint::CreateInsertion(NameLoc, Insertion); 15880 } 15881 15882 /// Determine whether a tag originally declared in context \p OldDC can 15883 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup 15884 /// found a declaration in \p OldDC as a previous decl, perhaps through a 15885 /// using-declaration). 15886 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 15887 DeclContext *NewDC) { 15888 OldDC = OldDC->getRedeclContext(); 15889 NewDC = NewDC->getRedeclContext(); 15890 15891 if (OldDC->Equals(NewDC)) 15892 return true; 15893 15894 // In MSVC mode, we allow a redeclaration if the contexts are related (either 15895 // encloses the other). 15896 if (S.getLangOpts().MSVCCompat && 15897 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 15898 return true; 15899 15900 return false; 15901 } 15902 15903 /// This is invoked when we see 'struct foo' or 'struct {'. In the 15904 /// former case, Name will be non-null. In the later case, Name will be null. 15905 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 15906 /// reference/declaration/definition of a tag. 15907 /// 15908 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 15909 /// trailing-type-specifier) other than one in an alias-declaration. 15910 /// 15911 /// \param SkipBody If non-null, will be set to indicate if the caller should 15912 /// skip the definition of this tag and treat it as if it were a declaration. 15913 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 15914 SourceLocation KWLoc, CXXScopeSpec &SS, 15915 IdentifierInfo *Name, SourceLocation NameLoc, 15916 const ParsedAttributesView &Attrs, AccessSpecifier AS, 15917 SourceLocation ModulePrivateLoc, 15918 MultiTemplateParamsArg TemplateParameterLists, 15919 bool &OwnedDecl, bool &IsDependent, 15920 SourceLocation ScopedEnumKWLoc, 15921 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, 15922 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 15923 SkipBodyInfo *SkipBody) { 15924 // If this is not a definition, it must have a name. 15925 IdentifierInfo *OrigName = Name; 15926 assert((Name != nullptr || TUK == TUK_Definition) && 15927 "Nameless record must be a definition!"); 15928 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 15929 15930 OwnedDecl = false; 15931 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 15932 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 15933 15934 // FIXME: Check member specializations more carefully. 15935 bool isMemberSpecialization = false; 15936 bool Invalid = false; 15937 15938 // We only need to do this matching if we have template parameters 15939 // or a scope specifier, which also conveniently avoids this work 15940 // for non-C++ cases. 15941 if (TemplateParameterLists.size() > 0 || 15942 (SS.isNotEmpty() && TUK != TUK_Reference)) { 15943 if (TemplateParameterList *TemplateParams = 15944 MatchTemplateParametersToScopeSpecifier( 15945 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 15946 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 15947 if (Kind == TTK_Enum) { 15948 Diag(KWLoc, diag::err_enum_template); 15949 return nullptr; 15950 } 15951 15952 if (TemplateParams->size() > 0) { 15953 // This is a declaration or definition of a class template (which may 15954 // be a member of another template). 15955 15956 if (Invalid) 15957 return nullptr; 15958 15959 OwnedDecl = false; 15960 DeclResult Result = CheckClassTemplate( 15961 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams, 15962 AS, ModulePrivateLoc, 15963 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1, 15964 TemplateParameterLists.data(), SkipBody); 15965 return Result.get(); 15966 } else { 15967 // The "template<>" header is extraneous. 15968 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 15969 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 15970 isMemberSpecialization = true; 15971 } 15972 } 15973 15974 if (!TemplateParameterLists.empty() && isMemberSpecialization && 15975 CheckTemplateDeclScope(S, TemplateParameterLists.back())) 15976 return nullptr; 15977 } 15978 15979 // Figure out the underlying type if this a enum declaration. We need to do 15980 // this early, because it's needed to detect if this is an incompatible 15981 // redeclaration. 15982 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 15983 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; 15984 15985 if (Kind == TTK_Enum) { 15986 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { 15987 // No underlying type explicitly specified, or we failed to parse the 15988 // type, default to int. 15989 EnumUnderlying = Context.IntTy.getTypePtr(); 15990 } else if (UnderlyingType.get()) { 15991 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 15992 // integral type; any cv-qualification is ignored. 15993 TypeSourceInfo *TI = nullptr; 15994 GetTypeFromParser(UnderlyingType.get(), &TI); 15995 EnumUnderlying = TI; 15996 15997 if (CheckEnumUnderlyingType(TI)) 15998 // Recover by falling back to int. 15999 EnumUnderlying = Context.IntTy.getTypePtr(); 16000 16001 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 16002 UPPC_FixedUnderlyingType)) 16003 EnumUnderlying = Context.IntTy.getTypePtr(); 16004 16005 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) { 16006 // For MSVC ABI compatibility, unfixed enums must use an underlying type 16007 // of 'int'. However, if this is an unfixed forward declaration, don't set 16008 // the underlying type unless the user enables -fms-compatibility. This 16009 // makes unfixed forward declared enums incomplete and is more conforming. 16010 if (TUK == TUK_Definition || getLangOpts().MSVCCompat) 16011 EnumUnderlying = Context.IntTy.getTypePtr(); 16012 } 16013 } 16014 16015 DeclContext *SearchDC = CurContext; 16016 DeclContext *DC = CurContext; 16017 bool isStdBadAlloc = false; 16018 bool isStdAlignValT = false; 16019 16020 RedeclarationKind Redecl = forRedeclarationInCurContext(); 16021 if (TUK == TUK_Friend || TUK == TUK_Reference) 16022 Redecl = NotForRedeclaration; 16023 16024 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C 16025 /// implemented asks for structural equivalence checking, the returned decl 16026 /// here is passed back to the parser, allowing the tag body to be parsed. 16027 auto createTagFromNewDecl = [&]() -> TagDecl * { 16028 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage"); 16029 // If there is an identifier, use the location of the identifier as the 16030 // location of the decl, otherwise use the location of the struct/union 16031 // keyword. 16032 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 16033 TagDecl *New = nullptr; 16034 16035 if (Kind == TTK_Enum) { 16036 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, 16037 ScopedEnum, ScopedEnumUsesClassTag, IsFixed); 16038 // If this is an undefined enum, bail. 16039 if (TUK != TUK_Definition && !Invalid) 16040 return nullptr; 16041 if (EnumUnderlying) { 16042 EnumDecl *ED = cast<EnumDecl>(New); 16043 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) 16044 ED->setIntegerTypeSourceInfo(TI); 16045 else 16046 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); 16047 ED->setPromotionType(ED->getIntegerType()); 16048 } 16049 } else { // struct/union 16050 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 16051 nullptr); 16052 } 16053 16054 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 16055 // Add alignment attributes if necessary; these attributes are checked 16056 // when the ASTContext lays out the structure. 16057 // 16058 // It is important for implementing the correct semantics that this 16059 // happen here (in ActOnTag). The #pragma pack stack is 16060 // maintained as a result of parser callbacks which can occur at 16061 // many points during the parsing of a struct declaration (because 16062 // the #pragma tokens are effectively skipped over during the 16063 // parsing of the struct). 16064 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 16065 AddAlignmentAttributesForRecord(RD); 16066 AddMsStructLayoutForRecord(RD); 16067 } 16068 } 16069 New->setLexicalDeclContext(CurContext); 16070 return New; 16071 }; 16072 16073 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 16074 if (Name && SS.isNotEmpty()) { 16075 // We have a nested-name tag ('struct foo::bar'). 16076 16077 // Check for invalid 'foo::'. 16078 if (SS.isInvalid()) { 16079 Name = nullptr; 16080 goto CreateNewDecl; 16081 } 16082 16083 // If this is a friend or a reference to a class in a dependent 16084 // context, don't try to make a decl for it. 16085 if (TUK == TUK_Friend || TUK == TUK_Reference) { 16086 DC = computeDeclContext(SS, false); 16087 if (!DC) { 16088 IsDependent = true; 16089 return nullptr; 16090 } 16091 } else { 16092 DC = computeDeclContext(SS, true); 16093 if (!DC) { 16094 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 16095 << SS.getRange(); 16096 return nullptr; 16097 } 16098 } 16099 16100 if (RequireCompleteDeclContext(SS, DC)) 16101 return nullptr; 16102 16103 SearchDC = DC; 16104 // Look-up name inside 'foo::'. 16105 LookupQualifiedName(Previous, DC); 16106 16107 if (Previous.isAmbiguous()) 16108 return nullptr; 16109 16110 if (Previous.empty()) { 16111 // Name lookup did not find anything. However, if the 16112 // nested-name-specifier refers to the current instantiation, 16113 // and that current instantiation has any dependent base 16114 // classes, we might find something at instantiation time: treat 16115 // this as a dependent elaborated-type-specifier. 16116 // But this only makes any sense for reference-like lookups. 16117 if (Previous.wasNotFoundInCurrentInstantiation() && 16118 (TUK == TUK_Reference || TUK == TUK_Friend)) { 16119 IsDependent = true; 16120 return nullptr; 16121 } 16122 16123 // A tag 'foo::bar' must already exist. 16124 Diag(NameLoc, diag::err_not_tag_in_scope) 16125 << Kind << Name << DC << SS.getRange(); 16126 Name = nullptr; 16127 Invalid = true; 16128 goto CreateNewDecl; 16129 } 16130 } else if (Name) { 16131 // C++14 [class.mem]p14: 16132 // If T is the name of a class, then each of the following shall have a 16133 // name different from T: 16134 // -- every member of class T that is itself a type 16135 if (TUK != TUK_Reference && TUK != TUK_Friend && 16136 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 16137 return nullptr; 16138 16139 // If this is a named struct, check to see if there was a previous forward 16140 // declaration or definition. 16141 // FIXME: We're looking into outer scopes here, even when we 16142 // shouldn't be. Doing so can result in ambiguities that we 16143 // shouldn't be diagnosing. 16144 LookupName(Previous, S); 16145 16146 // When declaring or defining a tag, ignore ambiguities introduced 16147 // by types using'ed into this scope. 16148 if (Previous.isAmbiguous() && 16149 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 16150 LookupResult::Filter F = Previous.makeFilter(); 16151 while (F.hasNext()) { 16152 NamedDecl *ND = F.next(); 16153 if (!ND->getDeclContext()->getRedeclContext()->Equals( 16154 SearchDC->getRedeclContext())) 16155 F.erase(); 16156 } 16157 F.done(); 16158 } 16159 16160 // C++11 [namespace.memdef]p3: 16161 // If the name in a friend declaration is neither qualified nor 16162 // a template-id and the declaration is a function or an 16163 // elaborated-type-specifier, the lookup to determine whether 16164 // the entity has been previously declared shall not consider 16165 // any scopes outside the innermost enclosing namespace. 16166 // 16167 // MSVC doesn't implement the above rule for types, so a friend tag 16168 // declaration may be a redeclaration of a type declared in an enclosing 16169 // scope. They do implement this rule for friend functions. 16170 // 16171 // Does it matter that this should be by scope instead of by 16172 // semantic context? 16173 if (!Previous.empty() && TUK == TUK_Friend) { 16174 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 16175 LookupResult::Filter F = Previous.makeFilter(); 16176 bool FriendSawTagOutsideEnclosingNamespace = false; 16177 while (F.hasNext()) { 16178 NamedDecl *ND = F.next(); 16179 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 16180 if (DC->isFileContext() && 16181 !EnclosingNS->Encloses(ND->getDeclContext())) { 16182 if (getLangOpts().MSVCCompat) 16183 FriendSawTagOutsideEnclosingNamespace = true; 16184 else 16185 F.erase(); 16186 } 16187 } 16188 F.done(); 16189 16190 // Diagnose this MSVC extension in the easy case where lookup would have 16191 // unambiguously found something outside the enclosing namespace. 16192 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 16193 NamedDecl *ND = Previous.getFoundDecl(); 16194 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 16195 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 16196 } 16197 } 16198 16199 // Note: there used to be some attempt at recovery here. 16200 if (Previous.isAmbiguous()) 16201 return nullptr; 16202 16203 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 16204 // FIXME: This makes sure that we ignore the contexts associated 16205 // with C structs, unions, and enums when looking for a matching 16206 // tag declaration or definition. See the similar lookup tweak 16207 // in Sema::LookupName; is there a better way to deal with this? 16208 while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(SearchDC)) 16209 SearchDC = SearchDC->getParent(); 16210 } else if (getLangOpts().CPlusPlus) { 16211 // Inside ObjCContainer want to keep it as a lexical decl context but go 16212 // past it (most often to TranslationUnit) to find the semantic decl 16213 // context. 16214 while (isa<ObjCContainerDecl>(SearchDC)) 16215 SearchDC = SearchDC->getParent(); 16216 } 16217 } else if (getLangOpts().CPlusPlus) { 16218 // Don't use ObjCContainerDecl as the semantic decl context for anonymous 16219 // TagDecl the same way as we skip it for named TagDecl. 16220 while (isa<ObjCContainerDecl>(SearchDC)) 16221 SearchDC = SearchDC->getParent(); 16222 } 16223 16224 if (Previous.isSingleResult() && 16225 Previous.getFoundDecl()->isTemplateParameter()) { 16226 // Maybe we will complain about the shadowed template parameter. 16227 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 16228 // Just pretend that we didn't see the previous declaration. 16229 Previous.clear(); 16230 } 16231 16232 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 16233 DC->Equals(getStdNamespace())) { 16234 if (Name->isStr("bad_alloc")) { 16235 // This is a declaration of or a reference to "std::bad_alloc". 16236 isStdBadAlloc = true; 16237 16238 // If std::bad_alloc has been implicitly declared (but made invisible to 16239 // name lookup), fill in this implicit declaration as the previous 16240 // declaration, so that the declarations get chained appropriately. 16241 if (Previous.empty() && StdBadAlloc) 16242 Previous.addDecl(getStdBadAlloc()); 16243 } else if (Name->isStr("align_val_t")) { 16244 isStdAlignValT = true; 16245 if (Previous.empty() && StdAlignValT) 16246 Previous.addDecl(getStdAlignValT()); 16247 } 16248 } 16249 16250 // If we didn't find a previous declaration, and this is a reference 16251 // (or friend reference), move to the correct scope. In C++, we 16252 // also need to do a redeclaration lookup there, just in case 16253 // there's a shadow friend decl. 16254 if (Name && Previous.empty() && 16255 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { 16256 if (Invalid) goto CreateNewDecl; 16257 assert(SS.isEmpty()); 16258 16259 if (TUK == TUK_Reference || IsTemplateParamOrArg) { 16260 // C++ [basic.scope.pdecl]p5: 16261 // -- for an elaborated-type-specifier of the form 16262 // 16263 // class-key identifier 16264 // 16265 // if the elaborated-type-specifier is used in the 16266 // decl-specifier-seq or parameter-declaration-clause of a 16267 // function defined in namespace scope, the identifier is 16268 // declared as a class-name in the namespace that contains 16269 // the declaration; otherwise, except as a friend 16270 // declaration, the identifier is declared in the smallest 16271 // non-class, non-function-prototype scope that contains the 16272 // declaration. 16273 // 16274 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 16275 // C structs and unions. 16276 // 16277 // It is an error in C++ to declare (rather than define) an enum 16278 // type, including via an elaborated type specifier. We'll 16279 // diagnose that later; for now, declare the enum in the same 16280 // scope as we would have picked for any other tag type. 16281 // 16282 // GNU C also supports this behavior as part of its incomplete 16283 // enum types extension, while GNU C++ does not. 16284 // 16285 // Find the context where we'll be declaring the tag. 16286 // FIXME: We would like to maintain the current DeclContext as the 16287 // lexical context, 16288 SearchDC = getTagInjectionContext(SearchDC); 16289 16290 // Find the scope where we'll be declaring the tag. 16291 S = getTagInjectionScope(S, getLangOpts()); 16292 } else { 16293 assert(TUK == TUK_Friend); 16294 // C++ [namespace.memdef]p3: 16295 // If a friend declaration in a non-local class first declares a 16296 // class or function, the friend class or function is a member of 16297 // the innermost enclosing namespace. 16298 SearchDC = SearchDC->getEnclosingNamespaceContext(); 16299 } 16300 16301 // In C++, we need to do a redeclaration lookup to properly 16302 // diagnose some problems. 16303 // FIXME: redeclaration lookup is also used (with and without C++) to find a 16304 // hidden declaration so that we don't get ambiguity errors when using a 16305 // type declared by an elaborated-type-specifier. In C that is not correct 16306 // and we should instead merge compatible types found by lookup. 16307 if (getLangOpts().CPlusPlus) { 16308 // FIXME: This can perform qualified lookups into function contexts, 16309 // which are meaningless. 16310 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 16311 LookupQualifiedName(Previous, SearchDC); 16312 } else { 16313 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 16314 LookupName(Previous, S); 16315 } 16316 } 16317 16318 // If we have a known previous declaration to use, then use it. 16319 if (Previous.empty() && SkipBody && SkipBody->Previous) 16320 Previous.addDecl(SkipBody->Previous); 16321 16322 if (!Previous.empty()) { 16323 NamedDecl *PrevDecl = Previous.getFoundDecl(); 16324 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 16325 16326 // It's okay to have a tag decl in the same scope as a typedef 16327 // which hides a tag decl in the same scope. Finding this 16328 // with a redeclaration lookup can only actually happen in C++. 16329 // 16330 // This is also okay for elaborated-type-specifiers, which is 16331 // technically forbidden by the current standard but which is 16332 // okay according to the likely resolution of an open issue; 16333 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 16334 if (getLangOpts().CPlusPlus) { 16335 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 16336 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 16337 TagDecl *Tag = TT->getDecl(); 16338 if (Tag->getDeclName() == Name && 16339 Tag->getDeclContext()->getRedeclContext() 16340 ->Equals(TD->getDeclContext()->getRedeclContext())) { 16341 PrevDecl = Tag; 16342 Previous.clear(); 16343 Previous.addDecl(Tag); 16344 Previous.resolveKind(); 16345 } 16346 } 16347 } 16348 } 16349 16350 // If this is a redeclaration of a using shadow declaration, it must 16351 // declare a tag in the same context. In MSVC mode, we allow a 16352 // redefinition if either context is within the other. 16353 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 16354 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 16355 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 16356 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 16357 !(OldTag && isAcceptableTagRedeclContext( 16358 *this, OldTag->getDeclContext(), SearchDC))) { 16359 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 16360 Diag(Shadow->getTargetDecl()->getLocation(), 16361 diag::note_using_decl_target); 16362 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) 16363 << 0; 16364 // Recover by ignoring the old declaration. 16365 Previous.clear(); 16366 goto CreateNewDecl; 16367 } 16368 } 16369 16370 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 16371 // If this is a use of a previous tag, or if the tag is already declared 16372 // in the same scope (so that the definition/declaration completes or 16373 // rementions the tag), reuse the decl. 16374 if (TUK == TUK_Reference || TUK == TUK_Friend || 16375 isDeclInScope(DirectPrevDecl, SearchDC, S, 16376 SS.isNotEmpty() || isMemberSpecialization)) { 16377 // Make sure that this wasn't declared as an enum and now used as a 16378 // struct or something similar. 16379 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 16380 TUK == TUK_Definition, KWLoc, 16381 Name)) { 16382 bool SafeToContinue 16383 = (PrevTagDecl->getTagKind() != TTK_Enum && 16384 Kind != TTK_Enum); 16385 if (SafeToContinue) 16386 Diag(KWLoc, diag::err_use_with_wrong_tag) 16387 << Name 16388 << FixItHint::CreateReplacement(SourceRange(KWLoc), 16389 PrevTagDecl->getKindName()); 16390 else 16391 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 16392 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 16393 16394 if (SafeToContinue) 16395 Kind = PrevTagDecl->getTagKind(); 16396 else { 16397 // Recover by making this an anonymous redefinition. 16398 Name = nullptr; 16399 Previous.clear(); 16400 Invalid = true; 16401 } 16402 } 16403 16404 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 16405 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 16406 if (TUK == TUK_Reference || TUK == TUK_Friend) 16407 return PrevTagDecl; 16408 16409 QualType EnumUnderlyingTy; 16410 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 16411 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 16412 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 16413 EnumUnderlyingTy = QualType(T, 0); 16414 16415 // All conflicts with previous declarations are recovered by 16416 // returning the previous declaration, unless this is a definition, 16417 // in which case we want the caller to bail out. 16418 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 16419 ScopedEnum, EnumUnderlyingTy, 16420 IsFixed, PrevEnum)) 16421 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 16422 } 16423 16424 // C++11 [class.mem]p1: 16425 // A member shall not be declared twice in the member-specification, 16426 // except that a nested class or member class template can be declared 16427 // and then later defined. 16428 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 16429 S->isDeclScope(PrevDecl)) { 16430 Diag(NameLoc, diag::ext_member_redeclared); 16431 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 16432 } 16433 16434 if (!Invalid) { 16435 // If this is a use, just return the declaration we found, unless 16436 // we have attributes. 16437 if (TUK == TUK_Reference || TUK == TUK_Friend) { 16438 if (!Attrs.empty()) { 16439 // FIXME: Diagnose these attributes. For now, we create a new 16440 // declaration to hold them. 16441 } else if (TUK == TUK_Reference && 16442 (PrevTagDecl->getFriendObjectKind() == 16443 Decl::FOK_Undeclared || 16444 PrevDecl->getOwningModule() != getCurrentModule()) && 16445 SS.isEmpty()) { 16446 // This declaration is a reference to an existing entity, but 16447 // has different visibility from that entity: it either makes 16448 // a friend visible or it makes a type visible in a new module. 16449 // In either case, create a new declaration. We only do this if 16450 // the declaration would have meant the same thing if no prior 16451 // declaration were found, that is, if it was found in the same 16452 // scope where we would have injected a declaration. 16453 if (!getTagInjectionContext(CurContext)->getRedeclContext() 16454 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 16455 return PrevTagDecl; 16456 // This is in the injected scope, create a new declaration in 16457 // that scope. 16458 S = getTagInjectionScope(S, getLangOpts()); 16459 } else { 16460 return PrevTagDecl; 16461 } 16462 } 16463 16464 // Diagnose attempts to redefine a tag. 16465 if (TUK == TUK_Definition) { 16466 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 16467 // If we're defining a specialization and the previous definition 16468 // is from an implicit instantiation, don't emit an error 16469 // here; we'll catch this in the general case below. 16470 bool IsExplicitSpecializationAfterInstantiation = false; 16471 if (isMemberSpecialization) { 16472 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 16473 IsExplicitSpecializationAfterInstantiation = 16474 RD->getTemplateSpecializationKind() != 16475 TSK_ExplicitSpecialization; 16476 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 16477 IsExplicitSpecializationAfterInstantiation = 16478 ED->getTemplateSpecializationKind() != 16479 TSK_ExplicitSpecialization; 16480 } 16481 16482 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do 16483 // not keep more that one definition around (merge them). However, 16484 // ensure the decl passes the structural compatibility check in 16485 // C11 6.2.7/1 (or 6.1.2.6/1 in C89). 16486 NamedDecl *Hidden = nullptr; 16487 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 16488 // There is a definition of this tag, but it is not visible. We 16489 // explicitly make use of C++'s one definition rule here, and 16490 // assume that this definition is identical to the hidden one 16491 // we already have. Make the existing definition visible and 16492 // use it in place of this one. 16493 if (!getLangOpts().CPlusPlus) { 16494 // Postpone making the old definition visible until after we 16495 // complete parsing the new one and do the structural 16496 // comparison. 16497 SkipBody->CheckSameAsPrevious = true; 16498 SkipBody->New = createTagFromNewDecl(); 16499 SkipBody->Previous = Def; 16500 return Def; 16501 } else { 16502 SkipBody->ShouldSkip = true; 16503 SkipBody->Previous = Def; 16504 makeMergedDefinitionVisible(Hidden); 16505 // Carry on and handle it like a normal definition. We'll 16506 // skip starting the definitiion later. 16507 } 16508 } else if (!IsExplicitSpecializationAfterInstantiation) { 16509 // A redeclaration in function prototype scope in C isn't 16510 // visible elsewhere, so merely issue a warning. 16511 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 16512 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 16513 else 16514 Diag(NameLoc, diag::err_redefinition) << Name; 16515 notePreviousDefinition(Def, 16516 NameLoc.isValid() ? NameLoc : KWLoc); 16517 // If this is a redefinition, recover by making this 16518 // struct be anonymous, which will make any later 16519 // references get the previous definition. 16520 Name = nullptr; 16521 Previous.clear(); 16522 Invalid = true; 16523 } 16524 } else { 16525 // If the type is currently being defined, complain 16526 // about a nested redefinition. 16527 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 16528 if (TD->isBeingDefined()) { 16529 Diag(NameLoc, diag::err_nested_redefinition) << Name; 16530 Diag(PrevTagDecl->getLocation(), 16531 diag::note_previous_definition); 16532 Name = nullptr; 16533 Previous.clear(); 16534 Invalid = true; 16535 } 16536 } 16537 16538 // Okay, this is definition of a previously declared or referenced 16539 // tag. We're going to create a new Decl for it. 16540 } 16541 16542 // Okay, we're going to make a redeclaration. If this is some kind 16543 // of reference, make sure we build the redeclaration in the same DC 16544 // as the original, and ignore the current access specifier. 16545 if (TUK == TUK_Friend || TUK == TUK_Reference) { 16546 SearchDC = PrevTagDecl->getDeclContext(); 16547 AS = AS_none; 16548 } 16549 } 16550 // If we get here we have (another) forward declaration or we 16551 // have a definition. Just create a new decl. 16552 16553 } else { 16554 // If we get here, this is a definition of a new tag type in a nested 16555 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 16556 // new decl/type. We set PrevDecl to NULL so that the entities 16557 // have distinct types. 16558 Previous.clear(); 16559 } 16560 // If we get here, we're going to create a new Decl. If PrevDecl 16561 // is non-NULL, it's a definition of the tag declared by 16562 // PrevDecl. If it's NULL, we have a new definition. 16563 16564 // Otherwise, PrevDecl is not a tag, but was found with tag 16565 // lookup. This is only actually possible in C++, where a few 16566 // things like templates still live in the tag namespace. 16567 } else { 16568 // Use a better diagnostic if an elaborated-type-specifier 16569 // found the wrong kind of type on the first 16570 // (non-redeclaration) lookup. 16571 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 16572 !Previous.isForRedeclaration()) { 16573 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 16574 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 16575 << Kind; 16576 Diag(PrevDecl->getLocation(), diag::note_declared_at); 16577 Invalid = true; 16578 16579 // Otherwise, only diagnose if the declaration is in scope. 16580 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 16581 SS.isNotEmpty() || isMemberSpecialization)) { 16582 // do nothing 16583 16584 // Diagnose implicit declarations introduced by elaborated types. 16585 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 16586 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 16587 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 16588 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 16589 Invalid = true; 16590 16591 // Otherwise it's a declaration. Call out a particularly common 16592 // case here. 16593 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 16594 unsigned Kind = 0; 16595 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 16596 Diag(NameLoc, diag::err_tag_definition_of_typedef) 16597 << Name << Kind << TND->getUnderlyingType(); 16598 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 16599 Invalid = true; 16600 16601 // Otherwise, diagnose. 16602 } else { 16603 // The tag name clashes with something else in the target scope, 16604 // issue an error and recover by making this tag be anonymous. 16605 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 16606 notePreviousDefinition(PrevDecl, NameLoc); 16607 Name = nullptr; 16608 Invalid = true; 16609 } 16610 16611 // The existing declaration isn't relevant to us; we're in a 16612 // new scope, so clear out the previous declaration. 16613 Previous.clear(); 16614 } 16615 } 16616 16617 CreateNewDecl: 16618 16619 TagDecl *PrevDecl = nullptr; 16620 if (Previous.isSingleResult()) 16621 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 16622 16623 // If there is an identifier, use the location of the identifier as the 16624 // location of the decl, otherwise use the location of the struct/union 16625 // keyword. 16626 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 16627 16628 // Otherwise, create a new declaration. If there is a previous 16629 // declaration of the same entity, the two will be linked via 16630 // PrevDecl. 16631 TagDecl *New; 16632 16633 if (Kind == TTK_Enum) { 16634 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 16635 // enum X { A, B, C } D; D should chain to X. 16636 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 16637 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 16638 ScopedEnumUsesClassTag, IsFixed); 16639 16640 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 16641 StdAlignValT = cast<EnumDecl>(New); 16642 16643 // If this is an undefined enum, warn. 16644 if (TUK != TUK_Definition && !Invalid) { 16645 TagDecl *Def; 16646 if (IsFixed && cast<EnumDecl>(New)->isFixed()) { 16647 // C++0x: 7.2p2: opaque-enum-declaration. 16648 // Conflicts are diagnosed above. Do nothing. 16649 } 16650 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 16651 Diag(Loc, diag::ext_forward_ref_enum_def) 16652 << New; 16653 Diag(Def->getLocation(), diag::note_previous_definition); 16654 } else { 16655 unsigned DiagID = diag::ext_forward_ref_enum; 16656 if (getLangOpts().MSVCCompat) 16657 DiagID = diag::ext_ms_forward_ref_enum; 16658 else if (getLangOpts().CPlusPlus) 16659 DiagID = diag::err_forward_ref_enum; 16660 Diag(Loc, DiagID); 16661 } 16662 } 16663 16664 if (EnumUnderlying) { 16665 EnumDecl *ED = cast<EnumDecl>(New); 16666 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 16667 ED->setIntegerTypeSourceInfo(TI); 16668 else 16669 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 16670 ED->setPromotionType(ED->getIntegerType()); 16671 assert(ED->isComplete() && "enum with type should be complete"); 16672 } 16673 } else { 16674 // struct/union/class 16675 16676 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 16677 // struct X { int A; } D; D should chain to X. 16678 if (getLangOpts().CPlusPlus) { 16679 // FIXME: Look for a way to use RecordDecl for simple structs. 16680 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 16681 cast_or_null<CXXRecordDecl>(PrevDecl)); 16682 16683 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 16684 StdBadAlloc = cast<CXXRecordDecl>(New); 16685 } else 16686 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 16687 cast_or_null<RecordDecl>(PrevDecl)); 16688 } 16689 16690 // C++11 [dcl.type]p3: 16691 // A type-specifier-seq shall not define a class or enumeration [...]. 16692 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && 16693 TUK == TUK_Definition) { 16694 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 16695 << Context.getTagDeclType(New); 16696 Invalid = true; 16697 } 16698 16699 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && 16700 DC->getDeclKind() == Decl::Enum) { 16701 Diag(New->getLocation(), diag::err_type_defined_in_enum) 16702 << Context.getTagDeclType(New); 16703 Invalid = true; 16704 } 16705 16706 // Maybe add qualifier info. 16707 if (SS.isNotEmpty()) { 16708 if (SS.isSet()) { 16709 // If this is either a declaration or a definition, check the 16710 // nested-name-specifier against the current context. 16711 if ((TUK == TUK_Definition || TUK == TUK_Declaration) && 16712 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, 16713 isMemberSpecialization)) 16714 Invalid = true; 16715 16716 New->setQualifierInfo(SS.getWithLocInContext(Context)); 16717 if (TemplateParameterLists.size() > 0) { 16718 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 16719 } 16720 } 16721 else 16722 Invalid = true; 16723 } 16724 16725 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 16726 // Add alignment attributes if necessary; these attributes are checked when 16727 // the ASTContext lays out the structure. 16728 // 16729 // It is important for implementing the correct semantics that this 16730 // happen here (in ActOnTag). The #pragma pack stack is 16731 // maintained as a result of parser callbacks which can occur at 16732 // many points during the parsing of a struct declaration (because 16733 // the #pragma tokens are effectively skipped over during the 16734 // parsing of the struct). 16735 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 16736 AddAlignmentAttributesForRecord(RD); 16737 AddMsStructLayoutForRecord(RD); 16738 } 16739 } 16740 16741 if (ModulePrivateLoc.isValid()) { 16742 if (isMemberSpecialization) 16743 Diag(New->getLocation(), diag::err_module_private_specialization) 16744 << 2 16745 << FixItHint::CreateRemoval(ModulePrivateLoc); 16746 // __module_private__ does not apply to local classes. However, we only 16747 // diagnose this as an error when the declaration specifiers are 16748 // freestanding. Here, we just ignore the __module_private__. 16749 else if (!SearchDC->isFunctionOrMethod()) 16750 New->setModulePrivate(); 16751 } 16752 16753 // If this is a specialization of a member class (of a class template), 16754 // check the specialization. 16755 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 16756 Invalid = true; 16757 16758 // If we're declaring or defining a tag in function prototype scope in C, 16759 // note that this type can only be used within the function and add it to 16760 // the list of decls to inject into the function definition scope. 16761 if ((Name || Kind == TTK_Enum) && 16762 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 16763 if (getLangOpts().CPlusPlus) { 16764 // C++ [dcl.fct]p6: 16765 // Types shall not be defined in return or parameter types. 16766 if (TUK == TUK_Definition && !IsTypeSpecifier) { 16767 Diag(Loc, diag::err_type_defined_in_param_type) 16768 << Name; 16769 Invalid = true; 16770 } 16771 } else if (!PrevDecl) { 16772 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 16773 } 16774 } 16775 16776 if (Invalid) 16777 New->setInvalidDecl(); 16778 16779 // Set the lexical context. If the tag has a C++ scope specifier, the 16780 // lexical context will be different from the semantic context. 16781 New->setLexicalDeclContext(CurContext); 16782 16783 // Mark this as a friend decl if applicable. 16784 // In Microsoft mode, a friend declaration also acts as a forward 16785 // declaration so we always pass true to setObjectOfFriendDecl to make 16786 // the tag name visible. 16787 if (TUK == TUK_Friend) 16788 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 16789 16790 // Set the access specifier. 16791 if (!Invalid && SearchDC->isRecord()) 16792 SetMemberAccessSpecifier(New, PrevDecl, AS); 16793 16794 if (PrevDecl) 16795 CheckRedeclarationInModule(New, PrevDecl); 16796 16797 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) 16798 New->startDefinition(); 16799 16800 ProcessDeclAttributeList(S, New, Attrs); 16801 AddPragmaAttributes(S, New); 16802 16803 // If this has an identifier, add it to the scope stack. 16804 if (TUK == TUK_Friend) { 16805 // We might be replacing an existing declaration in the lookup tables; 16806 // if so, borrow its access specifier. 16807 if (PrevDecl) 16808 New->setAccess(PrevDecl->getAccess()); 16809 16810 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 16811 DC->makeDeclVisibleInContext(New); 16812 if (Name) // can be null along some error paths 16813 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 16814 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 16815 } else if (Name) { 16816 S = getNonFieldDeclScope(S); 16817 PushOnScopeChains(New, S, true); 16818 } else { 16819 CurContext->addDecl(New); 16820 } 16821 16822 // If this is the C FILE type, notify the AST context. 16823 if (IdentifierInfo *II = New->getIdentifier()) 16824 if (!New->isInvalidDecl() && 16825 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 16826 II->isStr("FILE")) 16827 Context.setFILEDecl(New); 16828 16829 if (PrevDecl) 16830 mergeDeclAttributes(New, PrevDecl); 16831 16832 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) 16833 inferGslOwnerPointerAttribute(CXXRD); 16834 16835 // If there's a #pragma GCC visibility in scope, set the visibility of this 16836 // record. 16837 AddPushedVisibilityAttribute(New); 16838 16839 if (isMemberSpecialization && !New->isInvalidDecl()) 16840 CompleteMemberSpecialization(New, Previous); 16841 16842 OwnedDecl = true; 16843 // In C++, don't return an invalid declaration. We can't recover well from 16844 // the cases where we make the type anonymous. 16845 if (Invalid && getLangOpts().CPlusPlus) { 16846 if (New->isBeingDefined()) 16847 if (auto RD = dyn_cast<RecordDecl>(New)) 16848 RD->completeDefinition(); 16849 return nullptr; 16850 } else if (SkipBody && SkipBody->ShouldSkip) { 16851 return SkipBody->Previous; 16852 } else { 16853 return New; 16854 } 16855 } 16856 16857 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 16858 AdjustDeclIfTemplate(TagD); 16859 TagDecl *Tag = cast<TagDecl>(TagD); 16860 16861 // Enter the tag context. 16862 PushDeclContext(S, Tag); 16863 16864 ActOnDocumentableDecl(TagD); 16865 16866 // If there's a #pragma GCC visibility in scope, set the visibility of this 16867 // record. 16868 AddPushedVisibilityAttribute(Tag); 16869 } 16870 16871 bool Sema::ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody) { 16872 if (!hasStructuralCompatLayout(Prev, SkipBody.New)) 16873 return false; 16874 16875 // Make the previous decl visible. 16876 makeMergedDefinitionVisible(SkipBody.Previous); 16877 return true; 16878 } 16879 16880 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 16881 assert(isa<ObjCContainerDecl>(IDecl) && 16882 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 16883 DeclContext *OCD = cast<DeclContext>(IDecl); 16884 assert(OCD->getLexicalParent() == CurContext && 16885 "The next DeclContext should be lexically contained in the current one."); 16886 CurContext = OCD; 16887 return IDecl; 16888 } 16889 16890 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 16891 SourceLocation FinalLoc, 16892 bool IsFinalSpelledSealed, 16893 bool IsAbstract, 16894 SourceLocation LBraceLoc) { 16895 AdjustDeclIfTemplate(TagD); 16896 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 16897 16898 FieldCollector->StartClass(); 16899 16900 if (!Record->getIdentifier()) 16901 return; 16902 16903 if (IsAbstract) 16904 Record->markAbstract(); 16905 16906 if (FinalLoc.isValid()) { 16907 Record->addAttr(FinalAttr::Create( 16908 Context, FinalLoc, AttributeCommonInfo::AS_Keyword, 16909 static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed))); 16910 } 16911 // C++ [class]p2: 16912 // [...] The class-name is also inserted into the scope of the 16913 // class itself; this is known as the injected-class-name. For 16914 // purposes of access checking, the injected-class-name is treated 16915 // as if it were a public member name. 16916 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create( 16917 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(), 16918 Record->getLocation(), Record->getIdentifier(), 16919 /*PrevDecl=*/nullptr, 16920 /*DelayTypeCreation=*/true); 16921 Context.getTypeDeclType(InjectedClassName, Record); 16922 InjectedClassName->setImplicit(); 16923 InjectedClassName->setAccess(AS_public); 16924 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 16925 InjectedClassName->setDescribedClassTemplate(Template); 16926 PushOnScopeChains(InjectedClassName, S); 16927 assert(InjectedClassName->isInjectedClassName() && 16928 "Broken injected-class-name"); 16929 } 16930 16931 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 16932 SourceRange BraceRange) { 16933 AdjustDeclIfTemplate(TagD); 16934 TagDecl *Tag = cast<TagDecl>(TagD); 16935 Tag->setBraceRange(BraceRange); 16936 16937 // Make sure we "complete" the definition even it is invalid. 16938 if (Tag->isBeingDefined()) { 16939 assert(Tag->isInvalidDecl() && "We should already have completed it"); 16940 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16941 RD->completeDefinition(); 16942 } 16943 16944 if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) { 16945 FieldCollector->FinishClass(); 16946 if (RD->hasAttr<SYCLSpecialClassAttr>()) { 16947 auto *Def = RD->getDefinition(); 16948 assert(Def && "The record is expected to have a completed definition"); 16949 unsigned NumInitMethods = 0; 16950 for (auto *Method : Def->methods()) { 16951 if (!Method->getIdentifier()) 16952 continue; 16953 if (Method->getName() == "__init") 16954 NumInitMethods++; 16955 } 16956 if (NumInitMethods > 1 || !Def->hasInitMethod()) 16957 Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method); 16958 } 16959 } 16960 16961 // Exit this scope of this tag's definition. 16962 PopDeclContext(); 16963 16964 if (getCurLexicalContext()->isObjCContainer() && 16965 Tag->getDeclContext()->isFileContext()) 16966 Tag->setTopLevelDeclInObjCContainer(); 16967 16968 // Notify the consumer that we've defined a tag. 16969 if (!Tag->isInvalidDecl()) 16970 Consumer.HandleTagDeclDefinition(Tag); 16971 16972 // Clangs implementation of #pragma align(packed) differs in bitfield layout 16973 // from XLs and instead matches the XL #pragma pack(1) behavior. 16974 if (Context.getTargetInfo().getTriple().isOSAIX() && 16975 AlignPackStack.hasValue()) { 16976 AlignPackInfo APInfo = AlignPackStack.CurrentValue; 16977 // Only diagnose #pragma align(packed). 16978 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed) 16979 return; 16980 const RecordDecl *RD = dyn_cast<RecordDecl>(Tag); 16981 if (!RD) 16982 return; 16983 // Only warn if there is at least 1 bitfield member. 16984 if (llvm::any_of(RD->fields(), 16985 [](const FieldDecl *FD) { return FD->isBitField(); })) 16986 Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible); 16987 } 16988 } 16989 16990 void Sema::ActOnObjCContainerFinishDefinition() { 16991 // Exit this scope of this interface definition. 16992 PopDeclContext(); 16993 } 16994 16995 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 16996 assert(DC == CurContext && "Mismatch of container contexts"); 16997 OriginalLexicalContext = DC; 16998 ActOnObjCContainerFinishDefinition(); 16999 } 17000 17001 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 17002 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 17003 OriginalLexicalContext = nullptr; 17004 } 17005 17006 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 17007 AdjustDeclIfTemplate(TagD); 17008 TagDecl *Tag = cast<TagDecl>(TagD); 17009 Tag->setInvalidDecl(); 17010 17011 // Make sure we "complete" the definition even it is invalid. 17012 if (Tag->isBeingDefined()) { 17013 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 17014 RD->completeDefinition(); 17015 } 17016 17017 // We're undoing ActOnTagStartDefinition here, not 17018 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 17019 // the FieldCollector. 17020 17021 PopDeclContext(); 17022 } 17023 17024 // Note that FieldName may be null for anonymous bitfields. 17025 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 17026 IdentifierInfo *FieldName, 17027 QualType FieldTy, bool IsMsStruct, 17028 Expr *BitWidth, bool *ZeroWidth) { 17029 assert(BitWidth); 17030 if (BitWidth->containsErrors()) 17031 return ExprError(); 17032 17033 // Default to true; that shouldn't confuse checks for emptiness 17034 if (ZeroWidth) 17035 *ZeroWidth = true; 17036 17037 // C99 6.7.2.1p4 - verify the field type. 17038 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 17039 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 17040 // Handle incomplete and sizeless types with a specific error. 17041 if (RequireCompleteSizedType(FieldLoc, FieldTy, 17042 diag::err_field_incomplete_or_sizeless)) 17043 return ExprError(); 17044 if (FieldName) 17045 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 17046 << FieldName << FieldTy << BitWidth->getSourceRange(); 17047 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 17048 << FieldTy << BitWidth->getSourceRange(); 17049 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 17050 UPPC_BitFieldWidth)) 17051 return ExprError(); 17052 17053 // If the bit-width is type- or value-dependent, don't try to check 17054 // it now. 17055 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 17056 return BitWidth; 17057 17058 llvm::APSInt Value; 17059 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold); 17060 if (ICE.isInvalid()) 17061 return ICE; 17062 BitWidth = ICE.get(); 17063 17064 if (Value != 0 && ZeroWidth) 17065 *ZeroWidth = false; 17066 17067 // Zero-width bitfield is ok for anonymous field. 17068 if (Value == 0 && FieldName) 17069 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 17070 17071 if (Value.isSigned() && Value.isNegative()) { 17072 if (FieldName) 17073 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 17074 << FieldName << toString(Value, 10); 17075 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 17076 << toString(Value, 10); 17077 } 17078 17079 // The size of the bit-field must not exceed our maximum permitted object 17080 // size. 17081 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) { 17082 return Diag(FieldLoc, diag::err_bitfield_too_wide) 17083 << !FieldName << FieldName << toString(Value, 10); 17084 } 17085 17086 if (!FieldTy->isDependentType()) { 17087 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 17088 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 17089 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 17090 17091 // Over-wide bitfields are an error in C or when using the MSVC bitfield 17092 // ABI. 17093 bool CStdConstraintViolation = 17094 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 17095 bool MSBitfieldViolation = 17096 Value.ugt(TypeStorageSize) && 17097 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 17098 if (CStdConstraintViolation || MSBitfieldViolation) { 17099 unsigned DiagWidth = 17100 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 17101 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 17102 << (bool)FieldName << FieldName << toString(Value, 10) 17103 << !CStdConstraintViolation << DiagWidth; 17104 } 17105 17106 // Warn on types where the user might conceivably expect to get all 17107 // specified bits as value bits: that's all integral types other than 17108 // 'bool'. 17109 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) { 17110 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 17111 << FieldName << toString(Value, 10) 17112 << (unsigned)TypeWidth; 17113 } 17114 } 17115 17116 return BitWidth; 17117 } 17118 17119 /// ActOnField - Each field of a C struct/union is passed into this in order 17120 /// to create a FieldDecl object for it. 17121 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 17122 Declarator &D, Expr *BitfieldWidth) { 17123 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 17124 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 17125 /*InitStyle=*/ICIS_NoInit, AS_public); 17126 return Res; 17127 } 17128 17129 /// HandleField - Analyze a field of a C struct or a C++ data member. 17130 /// 17131 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 17132 SourceLocation DeclStart, 17133 Declarator &D, Expr *BitWidth, 17134 InClassInitStyle InitStyle, 17135 AccessSpecifier AS) { 17136 if (D.isDecompositionDeclarator()) { 17137 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 17138 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 17139 << Decomp.getSourceRange(); 17140 return nullptr; 17141 } 17142 17143 IdentifierInfo *II = D.getIdentifier(); 17144 SourceLocation Loc = DeclStart; 17145 if (II) Loc = D.getIdentifierLoc(); 17146 17147 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 17148 QualType T = TInfo->getType(); 17149 if (getLangOpts().CPlusPlus) { 17150 CheckExtraCXXDefaultArguments(D); 17151 17152 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 17153 UPPC_DataMemberType)) { 17154 D.setInvalidType(); 17155 T = Context.IntTy; 17156 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 17157 } 17158 } 17159 17160 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 17161 17162 if (D.getDeclSpec().isInlineSpecified()) 17163 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 17164 << getLangOpts().CPlusPlus17; 17165 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 17166 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 17167 diag::err_invalid_thread) 17168 << DeclSpec::getSpecifierName(TSCS); 17169 17170 // Check to see if this name was declared as a member previously 17171 NamedDecl *PrevDecl = nullptr; 17172 LookupResult Previous(*this, II, Loc, LookupMemberName, 17173 ForVisibleRedeclaration); 17174 LookupName(Previous, S); 17175 switch (Previous.getResultKind()) { 17176 case LookupResult::Found: 17177 case LookupResult::FoundUnresolvedValue: 17178 PrevDecl = Previous.getAsSingle<NamedDecl>(); 17179 break; 17180 17181 case LookupResult::FoundOverloaded: 17182 PrevDecl = Previous.getRepresentativeDecl(); 17183 break; 17184 17185 case LookupResult::NotFound: 17186 case LookupResult::NotFoundInCurrentInstantiation: 17187 case LookupResult::Ambiguous: 17188 break; 17189 } 17190 Previous.suppressDiagnostics(); 17191 17192 if (PrevDecl && PrevDecl->isTemplateParameter()) { 17193 // Maybe we will complain about the shadowed template parameter. 17194 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 17195 // Just pretend that we didn't see the previous declaration. 17196 PrevDecl = nullptr; 17197 } 17198 17199 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 17200 PrevDecl = nullptr; 17201 17202 bool Mutable 17203 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 17204 SourceLocation TSSL = D.getBeginLoc(); 17205 FieldDecl *NewFD 17206 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 17207 TSSL, AS, PrevDecl, &D); 17208 17209 if (NewFD->isInvalidDecl()) 17210 Record->setInvalidDecl(); 17211 17212 if (D.getDeclSpec().isModulePrivateSpecified()) 17213 NewFD->setModulePrivate(); 17214 17215 if (NewFD->isInvalidDecl() && PrevDecl) { 17216 // Don't introduce NewFD into scope; there's already something 17217 // with the same name in the same scope. 17218 } else if (II) { 17219 PushOnScopeChains(NewFD, S); 17220 } else 17221 Record->addDecl(NewFD); 17222 17223 return NewFD; 17224 } 17225 17226 /// Build a new FieldDecl and check its well-formedness. 17227 /// 17228 /// This routine builds a new FieldDecl given the fields name, type, 17229 /// record, etc. \p PrevDecl should refer to any previous declaration 17230 /// with the same name and in the same scope as the field to be 17231 /// created. 17232 /// 17233 /// \returns a new FieldDecl. 17234 /// 17235 /// \todo The Declarator argument is a hack. It will be removed once 17236 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 17237 TypeSourceInfo *TInfo, 17238 RecordDecl *Record, SourceLocation Loc, 17239 bool Mutable, Expr *BitWidth, 17240 InClassInitStyle InitStyle, 17241 SourceLocation TSSL, 17242 AccessSpecifier AS, NamedDecl *PrevDecl, 17243 Declarator *D) { 17244 IdentifierInfo *II = Name.getAsIdentifierInfo(); 17245 bool InvalidDecl = false; 17246 if (D) InvalidDecl = D->isInvalidType(); 17247 17248 // If we receive a broken type, recover by assuming 'int' and 17249 // marking this declaration as invalid. 17250 if (T.isNull() || T->containsErrors()) { 17251 InvalidDecl = true; 17252 T = Context.IntTy; 17253 } 17254 17255 QualType EltTy = Context.getBaseElementType(T); 17256 if (!EltTy->isDependentType() && !EltTy->containsErrors()) { 17257 if (RequireCompleteSizedType(Loc, EltTy, 17258 diag::err_field_incomplete_or_sizeless)) { 17259 // Fields of incomplete type force their record to be invalid. 17260 Record->setInvalidDecl(); 17261 InvalidDecl = true; 17262 } else { 17263 NamedDecl *Def; 17264 EltTy->isIncompleteType(&Def); 17265 if (Def && Def->isInvalidDecl()) { 17266 Record->setInvalidDecl(); 17267 InvalidDecl = true; 17268 } 17269 } 17270 } 17271 17272 // TR 18037 does not allow fields to be declared with address space 17273 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() || 17274 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { 17275 Diag(Loc, diag::err_field_with_address_space); 17276 Record->setInvalidDecl(); 17277 InvalidDecl = true; 17278 } 17279 17280 if (LangOpts.OpenCL) { 17281 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 17282 // used as structure or union field: image, sampler, event or block types. 17283 if (T->isEventT() || T->isImageType() || T->isSamplerT() || 17284 T->isBlockPointerType()) { 17285 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 17286 Record->setInvalidDecl(); 17287 InvalidDecl = true; 17288 } 17289 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension 17290 // is enabled. 17291 if (BitWidth && !getOpenCLOptions().isAvailableOption( 17292 "__cl_clang_bitfields", LangOpts)) { 17293 Diag(Loc, diag::err_opencl_bitfields); 17294 InvalidDecl = true; 17295 } 17296 } 17297 17298 // Anonymous bit-fields cannot be cv-qualified (CWG 2229). 17299 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && 17300 T.hasQualifiers()) { 17301 InvalidDecl = true; 17302 Diag(Loc, diag::err_anon_bitfield_qualifiers); 17303 } 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 if (!InvalidDecl && T->isVariablyModifiedType()) { 17308 if (!tryToFixVariablyModifiedVarType( 17309 TInfo, T, Loc, diag::err_typecheck_field_variable_size)) 17310 InvalidDecl = true; 17311 } 17312 17313 // Fields can not have abstract class types 17314 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 17315 diag::err_abstract_type_in_decl, 17316 AbstractFieldType)) 17317 InvalidDecl = true; 17318 17319 bool ZeroWidth = false; 17320 if (InvalidDecl) 17321 BitWidth = nullptr; 17322 // If this is declared as a bit-field, check the bit-field. 17323 if (BitWidth) { 17324 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 17325 &ZeroWidth).get(); 17326 if (!BitWidth) { 17327 InvalidDecl = true; 17328 BitWidth = nullptr; 17329 ZeroWidth = false; 17330 } 17331 } 17332 17333 // Check that 'mutable' is consistent with the type of the declaration. 17334 if (!InvalidDecl && Mutable) { 17335 unsigned DiagID = 0; 17336 if (T->isReferenceType()) 17337 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 17338 : diag::err_mutable_reference; 17339 else if (T.isConstQualified()) 17340 DiagID = diag::err_mutable_const; 17341 17342 if (DiagID) { 17343 SourceLocation ErrLoc = Loc; 17344 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 17345 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 17346 Diag(ErrLoc, DiagID); 17347 if (DiagID != diag::ext_mutable_reference) { 17348 Mutable = false; 17349 InvalidDecl = true; 17350 } 17351 } 17352 } 17353 17354 // C++11 [class.union]p8 (DR1460): 17355 // At most one variant member of a union may have a 17356 // brace-or-equal-initializer. 17357 if (InitStyle != ICIS_NoInit) 17358 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 17359 17360 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 17361 BitWidth, Mutable, InitStyle); 17362 if (InvalidDecl) 17363 NewFD->setInvalidDecl(); 17364 17365 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 17366 Diag(Loc, diag::err_duplicate_member) << II; 17367 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 17368 NewFD->setInvalidDecl(); 17369 } 17370 17371 if (!InvalidDecl && getLangOpts().CPlusPlus) { 17372 if (Record->isUnion()) { 17373 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 17374 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 17375 if (RDecl->getDefinition()) { 17376 // C++ [class.union]p1: An object of a class with a non-trivial 17377 // constructor, a non-trivial copy constructor, a non-trivial 17378 // destructor, or a non-trivial copy assignment operator 17379 // cannot be a member of a union, nor can an array of such 17380 // objects. 17381 if (CheckNontrivialField(NewFD)) 17382 NewFD->setInvalidDecl(); 17383 } 17384 } 17385 17386 // C++ [class.union]p1: If a union contains a member of reference type, 17387 // the program is ill-formed, except when compiling with MSVC extensions 17388 // enabled. 17389 if (EltTy->isReferenceType()) { 17390 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 17391 diag::ext_union_member_of_reference_type : 17392 diag::err_union_member_of_reference_type) 17393 << NewFD->getDeclName() << EltTy; 17394 if (!getLangOpts().MicrosoftExt) 17395 NewFD->setInvalidDecl(); 17396 } 17397 } 17398 } 17399 17400 // FIXME: We need to pass in the attributes given an AST 17401 // representation, not a parser representation. 17402 if (D) { 17403 // FIXME: The current scope is almost... but not entirely... correct here. 17404 ProcessDeclAttributes(getCurScope(), NewFD, *D); 17405 17406 if (NewFD->hasAttrs()) 17407 CheckAlignasUnderalignment(NewFD); 17408 } 17409 17410 // In auto-retain/release, infer strong retension for fields of 17411 // retainable type. 17412 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 17413 NewFD->setInvalidDecl(); 17414 17415 if (T.isObjCGCWeak()) 17416 Diag(Loc, diag::warn_attribute_weak_on_field); 17417 17418 // PPC MMA non-pointer types are not allowed as field types. 17419 if (Context.getTargetInfo().getTriple().isPPC64() && 17420 CheckPPCMMAType(T, NewFD->getLocation())) 17421 NewFD->setInvalidDecl(); 17422 17423 NewFD->setAccess(AS); 17424 return NewFD; 17425 } 17426 17427 bool Sema::CheckNontrivialField(FieldDecl *FD) { 17428 assert(FD); 17429 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 17430 17431 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 17432 return false; 17433 17434 QualType EltTy = Context.getBaseElementType(FD->getType()); 17435 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 17436 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 17437 if (RDecl->getDefinition()) { 17438 // We check for copy constructors before constructors 17439 // because otherwise we'll never get complaints about 17440 // copy constructors. 17441 17442 CXXSpecialMember member = CXXInvalid; 17443 // We're required to check for any non-trivial constructors. Since the 17444 // implicit default constructor is suppressed if there are any 17445 // user-declared constructors, we just need to check that there is a 17446 // trivial default constructor and a trivial copy constructor. (We don't 17447 // worry about move constructors here, since this is a C++98 check.) 17448 if (RDecl->hasNonTrivialCopyConstructor()) 17449 member = CXXCopyConstructor; 17450 else if (!RDecl->hasTrivialDefaultConstructor()) 17451 member = CXXDefaultConstructor; 17452 else if (RDecl->hasNonTrivialCopyAssignment()) 17453 member = CXXCopyAssignment; 17454 else if (RDecl->hasNonTrivialDestructor()) 17455 member = CXXDestructor; 17456 17457 if (member != CXXInvalid) { 17458 if (!getLangOpts().CPlusPlus11 && 17459 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 17460 // Objective-C++ ARC: it is an error to have a non-trivial field of 17461 // a union. However, system headers in Objective-C programs 17462 // occasionally have Objective-C lifetime objects within unions, 17463 // and rather than cause the program to fail, we make those 17464 // members unavailable. 17465 SourceLocation Loc = FD->getLocation(); 17466 if (getSourceManager().isInSystemHeader(Loc)) { 17467 if (!FD->hasAttr<UnavailableAttr>()) 17468 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 17469 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 17470 return false; 17471 } 17472 } 17473 17474 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 17475 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 17476 diag::err_illegal_union_or_anon_struct_member) 17477 << FD->getParent()->isUnion() << FD->getDeclName() << member; 17478 DiagnoseNontrivial(RDecl, member); 17479 return !getLangOpts().CPlusPlus11; 17480 } 17481 } 17482 } 17483 17484 return false; 17485 } 17486 17487 /// TranslateIvarVisibility - Translate visibility from a token ID to an 17488 /// AST enum value. 17489 static ObjCIvarDecl::AccessControl 17490 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 17491 switch (ivarVisibility) { 17492 default: llvm_unreachable("Unknown visitibility kind"); 17493 case tok::objc_private: return ObjCIvarDecl::Private; 17494 case tok::objc_public: return ObjCIvarDecl::Public; 17495 case tok::objc_protected: return ObjCIvarDecl::Protected; 17496 case tok::objc_package: return ObjCIvarDecl::Package; 17497 } 17498 } 17499 17500 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 17501 /// in order to create an IvarDecl object for it. 17502 Decl *Sema::ActOnIvar(Scope *S, 17503 SourceLocation DeclStart, 17504 Declarator &D, Expr *BitfieldWidth, 17505 tok::ObjCKeywordKind Visibility) { 17506 17507 IdentifierInfo *II = D.getIdentifier(); 17508 Expr *BitWidth = (Expr*)BitfieldWidth; 17509 SourceLocation Loc = DeclStart; 17510 if (II) Loc = D.getIdentifierLoc(); 17511 17512 // FIXME: Unnamed fields can be handled in various different ways, for 17513 // example, unnamed unions inject all members into the struct namespace! 17514 17515 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 17516 QualType T = TInfo->getType(); 17517 17518 if (BitWidth) { 17519 // 6.7.2.1p3, 6.7.2.1p4 17520 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 17521 if (!BitWidth) 17522 D.setInvalidType(); 17523 } else { 17524 // Not a bitfield. 17525 17526 // validate II. 17527 17528 } 17529 if (T->isReferenceType()) { 17530 Diag(Loc, diag::err_ivar_reference_type); 17531 D.setInvalidType(); 17532 } 17533 // C99 6.7.2.1p8: A member of a structure or union may have any type other 17534 // than a variably modified type. 17535 else if (T->isVariablyModifiedType()) { 17536 if (!tryToFixVariablyModifiedVarType( 17537 TInfo, T, Loc, diag::err_typecheck_ivar_variable_size)) 17538 D.setInvalidType(); 17539 } 17540 17541 // Get the visibility (access control) for this ivar. 17542 ObjCIvarDecl::AccessControl ac = 17543 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 17544 : ObjCIvarDecl::None; 17545 // Must set ivar's DeclContext to its enclosing interface. 17546 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 17547 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 17548 return nullptr; 17549 ObjCContainerDecl *EnclosingContext; 17550 if (ObjCImplementationDecl *IMPDecl = 17551 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 17552 if (LangOpts.ObjCRuntime.isFragile()) { 17553 // Case of ivar declared in an implementation. Context is that of its class. 17554 EnclosingContext = IMPDecl->getClassInterface(); 17555 assert(EnclosingContext && "Implementation has no class interface!"); 17556 } 17557 else 17558 EnclosingContext = EnclosingDecl; 17559 } else { 17560 if (ObjCCategoryDecl *CDecl = 17561 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 17562 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 17563 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 17564 return nullptr; 17565 } 17566 } 17567 EnclosingContext = EnclosingDecl; 17568 } 17569 17570 // Construct the decl. 17571 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 17572 DeclStart, Loc, II, T, 17573 TInfo, ac, (Expr *)BitfieldWidth); 17574 17575 if (II) { 17576 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 17577 ForVisibleRedeclaration); 17578 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 17579 && !isa<TagDecl>(PrevDecl)) { 17580 Diag(Loc, diag::err_duplicate_member) << II; 17581 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 17582 NewID->setInvalidDecl(); 17583 } 17584 } 17585 17586 // Process attributes attached to the ivar. 17587 ProcessDeclAttributes(S, NewID, D); 17588 17589 if (D.isInvalidType()) 17590 NewID->setInvalidDecl(); 17591 17592 // In ARC, infer 'retaining' for ivars of retainable type. 17593 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 17594 NewID->setInvalidDecl(); 17595 17596 if (D.getDeclSpec().isModulePrivateSpecified()) 17597 NewID->setModulePrivate(); 17598 17599 if (II) { 17600 // FIXME: When interfaces are DeclContexts, we'll need to add 17601 // these to the interface. 17602 S->AddDecl(NewID); 17603 IdResolver.AddDecl(NewID); 17604 } 17605 17606 if (LangOpts.ObjCRuntime.isNonFragile() && 17607 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 17608 Diag(Loc, diag::warn_ivars_in_interface); 17609 17610 return NewID; 17611 } 17612 17613 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 17614 /// class and class extensions. For every class \@interface and class 17615 /// extension \@interface, if the last ivar is a bitfield of any type, 17616 /// then add an implicit `char :0` ivar to the end of that interface. 17617 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 17618 SmallVectorImpl<Decl *> &AllIvarDecls) { 17619 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 17620 return; 17621 17622 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 17623 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 17624 17625 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) 17626 return; 17627 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 17628 if (!ID) { 17629 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 17630 if (!CD->IsClassExtension()) 17631 return; 17632 } 17633 // No need to add this to end of @implementation. 17634 else 17635 return; 17636 } 17637 // All conditions are met. Add a new bitfield to the tail end of ivars. 17638 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 17639 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 17640 17641 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 17642 DeclLoc, DeclLoc, nullptr, 17643 Context.CharTy, 17644 Context.getTrivialTypeSourceInfo(Context.CharTy, 17645 DeclLoc), 17646 ObjCIvarDecl::Private, BW, 17647 true); 17648 AllIvarDecls.push_back(Ivar); 17649 } 17650 17651 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 17652 ArrayRef<Decl *> Fields, SourceLocation LBrac, 17653 SourceLocation RBrac, 17654 const ParsedAttributesView &Attrs) { 17655 assert(EnclosingDecl && "missing record or interface decl"); 17656 17657 // If this is an Objective-C @implementation or category and we have 17658 // new fields here we should reset the layout of the interface since 17659 // it will now change. 17660 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 17661 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 17662 switch (DC->getKind()) { 17663 default: break; 17664 case Decl::ObjCCategory: 17665 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 17666 break; 17667 case Decl::ObjCImplementation: 17668 Context. 17669 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 17670 break; 17671 } 17672 } 17673 17674 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 17675 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl); 17676 17677 // Start counting up the number of named members; make sure to include 17678 // members of anonymous structs and unions in the total. 17679 unsigned NumNamedMembers = 0; 17680 if (Record) { 17681 for (const auto *I : Record->decls()) { 17682 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 17683 if (IFD->getDeclName()) 17684 ++NumNamedMembers; 17685 } 17686 } 17687 17688 // Verify that all the fields are okay. 17689 SmallVector<FieldDecl*, 32> RecFields; 17690 17691 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 17692 i != end; ++i) { 17693 FieldDecl *FD = cast<FieldDecl>(*i); 17694 17695 // Get the type for the field. 17696 const Type *FDTy = FD->getType().getTypePtr(); 17697 17698 if (!FD->isAnonymousStructOrUnion()) { 17699 // Remember all fields written by the user. 17700 RecFields.push_back(FD); 17701 } 17702 17703 // If the field is already invalid for some reason, don't emit more 17704 // diagnostics about it. 17705 if (FD->isInvalidDecl()) { 17706 EnclosingDecl->setInvalidDecl(); 17707 continue; 17708 } 17709 17710 // C99 6.7.2.1p2: 17711 // A structure or union shall not contain a member with 17712 // incomplete or function type (hence, a structure shall not 17713 // contain an instance of itself, but may contain a pointer to 17714 // an instance of itself), except that the last member of a 17715 // structure with more than one named member may have incomplete 17716 // array type; such a structure (and any union containing, 17717 // possibly recursively, a member that is such a structure) 17718 // shall not be a member of a structure or an element of an 17719 // array. 17720 bool IsLastField = (i + 1 == Fields.end()); 17721 if (FDTy->isFunctionType()) { 17722 // Field declared as a function. 17723 Diag(FD->getLocation(), diag::err_field_declared_as_function) 17724 << FD->getDeclName(); 17725 FD->setInvalidDecl(); 17726 EnclosingDecl->setInvalidDecl(); 17727 continue; 17728 } else if (FDTy->isIncompleteArrayType() && 17729 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { 17730 if (Record) { 17731 // Flexible array member. 17732 // Microsoft and g++ is more permissive regarding flexible array. 17733 // It will accept flexible array in union and also 17734 // as the sole element of a struct/class. 17735 unsigned DiagID = 0; 17736 if (!Record->isUnion() && !IsLastField) { 17737 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) 17738 << FD->getDeclName() << FD->getType() << Record->getTagKind(); 17739 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); 17740 FD->setInvalidDecl(); 17741 EnclosingDecl->setInvalidDecl(); 17742 continue; 17743 } else if (Record->isUnion()) 17744 DiagID = getLangOpts().MicrosoftExt 17745 ? diag::ext_flexible_array_union_ms 17746 : getLangOpts().CPlusPlus 17747 ? diag::ext_flexible_array_union_gnu 17748 : diag::err_flexible_array_union; 17749 else if (NumNamedMembers < 1) 17750 DiagID = getLangOpts().MicrosoftExt 17751 ? diag::ext_flexible_array_empty_aggregate_ms 17752 : getLangOpts().CPlusPlus 17753 ? diag::ext_flexible_array_empty_aggregate_gnu 17754 : diag::err_flexible_array_empty_aggregate; 17755 17756 if (DiagID) 17757 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 17758 << Record->getTagKind(); 17759 // While the layout of types that contain virtual bases is not specified 17760 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 17761 // virtual bases after the derived members. This would make a flexible 17762 // array member declared at the end of an object not adjacent to the end 17763 // of the type. 17764 if (CXXRecord && CXXRecord->getNumVBases() != 0) 17765 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 17766 << FD->getDeclName() << Record->getTagKind(); 17767 if (!getLangOpts().C99) 17768 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 17769 << FD->getDeclName() << Record->getTagKind(); 17770 17771 // If the element type has a non-trivial destructor, we would not 17772 // implicitly destroy the elements, so disallow it for now. 17773 // 17774 // FIXME: GCC allows this. We should probably either implicitly delete 17775 // the destructor of the containing class, or just allow this. 17776 QualType BaseElem = Context.getBaseElementType(FD->getType()); 17777 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 17778 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 17779 << FD->getDeclName() << FD->getType(); 17780 FD->setInvalidDecl(); 17781 EnclosingDecl->setInvalidDecl(); 17782 continue; 17783 } 17784 // Okay, we have a legal flexible array member at the end of the struct. 17785 Record->setHasFlexibleArrayMember(true); 17786 } else { 17787 // In ObjCContainerDecl ivars with incomplete array type are accepted, 17788 // unless they are followed by another ivar. That check is done 17789 // elsewhere, after synthesized ivars are known. 17790 } 17791 } else if (!FDTy->isDependentType() && 17792 RequireCompleteSizedType( 17793 FD->getLocation(), FD->getType(), 17794 diag::err_field_incomplete_or_sizeless)) { 17795 // Incomplete type 17796 FD->setInvalidDecl(); 17797 EnclosingDecl->setInvalidDecl(); 17798 continue; 17799 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 17800 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 17801 // A type which contains a flexible array member is considered to be a 17802 // flexible array member. 17803 Record->setHasFlexibleArrayMember(true); 17804 if (!Record->isUnion()) { 17805 // If this is a struct/class and this is not the last element, reject 17806 // it. Note that GCC supports variable sized arrays in the middle of 17807 // structures. 17808 if (!IsLastField) 17809 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 17810 << FD->getDeclName() << FD->getType(); 17811 else { 17812 // We support flexible arrays at the end of structs in 17813 // other structs as an extension. 17814 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 17815 << FD->getDeclName(); 17816 } 17817 } 17818 } 17819 if (isa<ObjCContainerDecl>(EnclosingDecl) && 17820 RequireNonAbstractType(FD->getLocation(), FD->getType(), 17821 diag::err_abstract_type_in_decl, 17822 AbstractIvarType)) { 17823 // Ivars can not have abstract class types 17824 FD->setInvalidDecl(); 17825 } 17826 if (Record && FDTTy->getDecl()->hasObjectMember()) 17827 Record->setHasObjectMember(true); 17828 if (Record && FDTTy->getDecl()->hasVolatileMember()) 17829 Record->setHasVolatileMember(true); 17830 } else if (FDTy->isObjCObjectType()) { 17831 /// A field cannot be an Objective-c object 17832 Diag(FD->getLocation(), diag::err_statically_allocated_object) 17833 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 17834 QualType T = Context.getObjCObjectPointerType(FD->getType()); 17835 FD->setType(T); 17836 } else if (Record && Record->isUnion() && 17837 FD->getType().hasNonTrivialObjCLifetime() && 17838 getSourceManager().isInSystemHeader(FD->getLocation()) && 17839 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() && 17840 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong || 17841 !Context.hasDirectOwnershipQualifier(FD->getType()))) { 17842 // For backward compatibility, fields of C unions declared in system 17843 // headers that have non-trivial ObjC ownership qualifications are marked 17844 // as unavailable unless the qualifier is explicit and __strong. This can 17845 // break ABI compatibility between programs compiled with ARC and MRR, but 17846 // is a better option than rejecting programs using those unions under 17847 // ARC. 17848 FD->addAttr(UnavailableAttr::CreateImplicit( 17849 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, 17850 FD->getLocation())); 17851 } else if (getLangOpts().ObjC && 17852 getLangOpts().getGC() != LangOptions::NonGC && Record && 17853 !Record->hasObjectMember()) { 17854 if (FD->getType()->isObjCObjectPointerType() || 17855 FD->getType().isObjCGCStrong()) 17856 Record->setHasObjectMember(true); 17857 else if (Context.getAsArrayType(FD->getType())) { 17858 QualType BaseType = Context.getBaseElementType(FD->getType()); 17859 if (BaseType->isRecordType() && 17860 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember()) 17861 Record->setHasObjectMember(true); 17862 else if (BaseType->isObjCObjectPointerType() || 17863 BaseType.isObjCGCStrong()) 17864 Record->setHasObjectMember(true); 17865 } 17866 } 17867 17868 if (Record && !getLangOpts().CPlusPlus && 17869 !shouldIgnoreForRecordTriviality(FD)) { 17870 QualType FT = FD->getType(); 17871 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) { 17872 Record->setNonTrivialToPrimitiveDefaultInitialize(true); 17873 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 17874 Record->isUnion()) 17875 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true); 17876 } 17877 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); 17878 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) { 17879 Record->setNonTrivialToPrimitiveCopy(true); 17880 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion()) 17881 Record->setHasNonTrivialToPrimitiveCopyCUnion(true); 17882 } 17883 if (FT.isDestructedType()) { 17884 Record->setNonTrivialToPrimitiveDestroy(true); 17885 Record->setParamDestroyedInCallee(true); 17886 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion()) 17887 Record->setHasNonTrivialToPrimitiveDestructCUnion(true); 17888 } 17889 17890 if (const auto *RT = FT->getAs<RecordType>()) { 17891 if (RT->getDecl()->getArgPassingRestrictions() == 17892 RecordDecl::APK_CanNeverPassInRegs) 17893 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17894 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) 17895 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17896 } 17897 17898 if (Record && FD->getType().isVolatileQualified()) 17899 Record->setHasVolatileMember(true); 17900 // Keep track of the number of named members. 17901 if (FD->getIdentifier()) 17902 ++NumNamedMembers; 17903 } 17904 17905 // Okay, we successfully defined 'Record'. 17906 if (Record) { 17907 bool Completed = false; 17908 if (CXXRecord) { 17909 if (!CXXRecord->isInvalidDecl()) { 17910 // Set access bits correctly on the directly-declared conversions. 17911 for (CXXRecordDecl::conversion_iterator 17912 I = CXXRecord->conversion_begin(), 17913 E = CXXRecord->conversion_end(); I != E; ++I) 17914 I.setAccess((*I)->getAccess()); 17915 } 17916 17917 // Add any implicitly-declared members to this class. 17918 AddImplicitlyDeclaredMembersToClass(CXXRecord); 17919 17920 if (!CXXRecord->isDependentType()) { 17921 if (!CXXRecord->isInvalidDecl()) { 17922 // If we have virtual base classes, we may end up finding multiple 17923 // final overriders for a given virtual function. Check for this 17924 // problem now. 17925 if (CXXRecord->getNumVBases()) { 17926 CXXFinalOverriderMap FinalOverriders; 17927 CXXRecord->getFinalOverriders(FinalOverriders); 17928 17929 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 17930 MEnd = FinalOverriders.end(); 17931 M != MEnd; ++M) { 17932 for (OverridingMethods::iterator SO = M->second.begin(), 17933 SOEnd = M->second.end(); 17934 SO != SOEnd; ++SO) { 17935 assert(SO->second.size() > 0 && 17936 "Virtual function without overriding functions?"); 17937 if (SO->second.size() == 1) 17938 continue; 17939 17940 // C++ [class.virtual]p2: 17941 // In a derived class, if a virtual member function of a base 17942 // class subobject has more than one final overrider the 17943 // program is ill-formed. 17944 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 17945 << (const NamedDecl *)M->first << Record; 17946 Diag(M->first->getLocation(), 17947 diag::note_overridden_virtual_function); 17948 for (OverridingMethods::overriding_iterator 17949 OM = SO->second.begin(), 17950 OMEnd = SO->second.end(); 17951 OM != OMEnd; ++OM) 17952 Diag(OM->Method->getLocation(), diag::note_final_overrider) 17953 << (const NamedDecl *)M->first << OM->Method->getParent(); 17954 17955 Record->setInvalidDecl(); 17956 } 17957 } 17958 CXXRecord->completeDefinition(&FinalOverriders); 17959 Completed = true; 17960 } 17961 } 17962 } 17963 } 17964 17965 if (!Completed) 17966 Record->completeDefinition(); 17967 17968 // Handle attributes before checking the layout. 17969 ProcessDeclAttributeList(S, Record, Attrs); 17970 17971 // We may have deferred checking for a deleted destructor. Check now. 17972 if (CXXRecord) { 17973 auto *Dtor = CXXRecord->getDestructor(); 17974 if (Dtor && Dtor->isImplicit() && 17975 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { 17976 CXXRecord->setImplicitDestructorIsDeleted(); 17977 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 17978 } 17979 } 17980 17981 if (Record->hasAttrs()) { 17982 CheckAlignasUnderalignment(Record); 17983 17984 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 17985 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 17986 IA->getRange(), IA->getBestCase(), 17987 IA->getInheritanceModel()); 17988 } 17989 17990 // Check if the structure/union declaration is a type that can have zero 17991 // size in C. For C this is a language extension, for C++ it may cause 17992 // compatibility problems. 17993 bool CheckForZeroSize; 17994 if (!getLangOpts().CPlusPlus) { 17995 CheckForZeroSize = true; 17996 } else { 17997 // For C++ filter out types that cannot be referenced in C code. 17998 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 17999 CheckForZeroSize = 18000 CXXRecord->getLexicalDeclContext()->isExternCContext() && 18001 !CXXRecord->isDependentType() && !inTemplateInstantiation() && 18002 CXXRecord->isCLike(); 18003 } 18004 if (CheckForZeroSize) { 18005 bool ZeroSize = true; 18006 bool IsEmpty = true; 18007 unsigned NonBitFields = 0; 18008 for (RecordDecl::field_iterator I = Record->field_begin(), 18009 E = Record->field_end(); 18010 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 18011 IsEmpty = false; 18012 if (I->isUnnamedBitfield()) { 18013 if (!I->isZeroLengthBitField(Context)) 18014 ZeroSize = false; 18015 } else { 18016 ++NonBitFields; 18017 QualType FieldType = I->getType(); 18018 if (FieldType->isIncompleteType() || 18019 !Context.getTypeSizeInChars(FieldType).isZero()) 18020 ZeroSize = false; 18021 } 18022 } 18023 18024 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 18025 // allowed in C++, but warn if its declaration is inside 18026 // extern "C" block. 18027 if (ZeroSize) { 18028 Diag(RecLoc, getLangOpts().CPlusPlus ? 18029 diag::warn_zero_size_struct_union_in_extern_c : 18030 diag::warn_zero_size_struct_union_compat) 18031 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 18032 } 18033 18034 // Structs without named members are extension in C (C99 6.7.2.1p7), 18035 // but are accepted by GCC. 18036 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 18037 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 18038 diag::ext_no_named_members_in_struct_union) 18039 << Record->isUnion(); 18040 } 18041 } 18042 } else { 18043 ObjCIvarDecl **ClsFields = 18044 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 18045 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 18046 ID->setEndOfDefinitionLoc(RBrac); 18047 // Add ivar's to class's DeclContext. 18048 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 18049 ClsFields[i]->setLexicalDeclContext(ID); 18050 ID->addDecl(ClsFields[i]); 18051 } 18052 // Must enforce the rule that ivars in the base classes may not be 18053 // duplicates. 18054 if (ID->getSuperClass()) 18055 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 18056 } else if (ObjCImplementationDecl *IMPDecl = 18057 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 18058 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 18059 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 18060 // Ivar declared in @implementation never belongs to the implementation. 18061 // Only it is in implementation's lexical context. 18062 ClsFields[I]->setLexicalDeclContext(IMPDecl); 18063 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 18064 IMPDecl->setIvarLBraceLoc(LBrac); 18065 IMPDecl->setIvarRBraceLoc(RBrac); 18066 } else if (ObjCCategoryDecl *CDecl = 18067 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 18068 // case of ivars in class extension; all other cases have been 18069 // reported as errors elsewhere. 18070 // FIXME. Class extension does not have a LocEnd field. 18071 // CDecl->setLocEnd(RBrac); 18072 // Add ivar's to class extension's DeclContext. 18073 // Diagnose redeclaration of private ivars. 18074 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 18075 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 18076 if (IDecl) { 18077 if (const ObjCIvarDecl *ClsIvar = 18078 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 18079 Diag(ClsFields[i]->getLocation(), 18080 diag::err_duplicate_ivar_declaration); 18081 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 18082 continue; 18083 } 18084 for (const auto *Ext : IDecl->known_extensions()) { 18085 if (const ObjCIvarDecl *ClsExtIvar 18086 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 18087 Diag(ClsFields[i]->getLocation(), 18088 diag::err_duplicate_ivar_declaration); 18089 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 18090 continue; 18091 } 18092 } 18093 } 18094 ClsFields[i]->setLexicalDeclContext(CDecl); 18095 CDecl->addDecl(ClsFields[i]); 18096 } 18097 CDecl->setIvarLBraceLoc(LBrac); 18098 CDecl->setIvarRBraceLoc(RBrac); 18099 } 18100 } 18101 } 18102 18103 /// Determine whether the given integral value is representable within 18104 /// the given type T. 18105 static bool isRepresentableIntegerValue(ASTContext &Context, 18106 llvm::APSInt &Value, 18107 QualType T) { 18108 assert((T->isIntegralType(Context) || T->isEnumeralType()) && 18109 "Integral type required!"); 18110 unsigned BitWidth = Context.getIntWidth(T); 18111 18112 if (Value.isUnsigned() || Value.isNonNegative()) { 18113 if (T->isSignedIntegerOrEnumerationType()) 18114 --BitWidth; 18115 return Value.getActiveBits() <= BitWidth; 18116 } 18117 return Value.getMinSignedBits() <= BitWidth; 18118 } 18119 18120 // Given an integral type, return the next larger integral type 18121 // (or a NULL type of no such type exists). 18122 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 18123 // FIXME: Int128/UInt128 support, which also needs to be introduced into 18124 // enum checking below. 18125 assert((T->isIntegralType(Context) || 18126 T->isEnumeralType()) && "Integral type required!"); 18127 const unsigned NumTypes = 4; 18128 QualType SignedIntegralTypes[NumTypes] = { 18129 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 18130 }; 18131 QualType UnsignedIntegralTypes[NumTypes] = { 18132 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 18133 Context.UnsignedLongLongTy 18134 }; 18135 18136 unsigned BitWidth = Context.getTypeSize(T); 18137 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 18138 : UnsignedIntegralTypes; 18139 for (unsigned I = 0; I != NumTypes; ++I) 18140 if (Context.getTypeSize(Types[I]) > BitWidth) 18141 return Types[I]; 18142 18143 return QualType(); 18144 } 18145 18146 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 18147 EnumConstantDecl *LastEnumConst, 18148 SourceLocation IdLoc, 18149 IdentifierInfo *Id, 18150 Expr *Val) { 18151 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 18152 llvm::APSInt EnumVal(IntWidth); 18153 QualType EltTy; 18154 18155 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 18156 Val = nullptr; 18157 18158 if (Val) 18159 Val = DefaultLvalueConversion(Val).get(); 18160 18161 if (Val) { 18162 if (Enum->isDependentType() || Val->isTypeDependent() || 18163 Val->containsErrors()) 18164 EltTy = Context.DependentTy; 18165 else { 18166 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed 18167 // underlying type, but do allow it in all other contexts. 18168 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) { 18169 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 18170 // constant-expression in the enumerator-definition shall be a converted 18171 // constant expression of the underlying type. 18172 EltTy = Enum->getIntegerType(); 18173 ExprResult Converted = 18174 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 18175 CCEK_Enumerator); 18176 if (Converted.isInvalid()) 18177 Val = nullptr; 18178 else 18179 Val = Converted.get(); 18180 } else if (!Val->isValueDependent() && 18181 !(Val = 18182 VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold) 18183 .get())) { 18184 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 18185 } else { 18186 if (Enum->isComplete()) { 18187 EltTy = Enum->getIntegerType(); 18188 18189 // In Obj-C and Microsoft mode, require the enumeration value to be 18190 // representable in the underlying type of the enumeration. In C++11, 18191 // we perform a non-narrowing conversion as part of converted constant 18192 // expression checking. 18193 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 18194 if (Context.getTargetInfo() 18195 .getTriple() 18196 .isWindowsMSVCEnvironment()) { 18197 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 18198 } else { 18199 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 18200 } 18201 } 18202 18203 // Cast to the underlying type. 18204 Val = ImpCastExprToType(Val, EltTy, 18205 EltTy->isBooleanType() ? CK_IntegralToBoolean 18206 : CK_IntegralCast) 18207 .get(); 18208 } else if (getLangOpts().CPlusPlus) { 18209 // C++11 [dcl.enum]p5: 18210 // If the underlying type is not fixed, the type of each enumerator 18211 // is the type of its initializing value: 18212 // - If an initializer is specified for an enumerator, the 18213 // initializing value has the same type as the expression. 18214 EltTy = Val->getType(); 18215 } else { 18216 // C99 6.7.2.2p2: 18217 // The expression that defines the value of an enumeration constant 18218 // shall be an integer constant expression that has a value 18219 // representable as an int. 18220 18221 // Complain if the value is not representable in an int. 18222 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 18223 Diag(IdLoc, diag::ext_enum_value_not_int) 18224 << toString(EnumVal, 10) << Val->getSourceRange() 18225 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 18226 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 18227 // Force the type of the expression to 'int'. 18228 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 18229 } 18230 EltTy = Val->getType(); 18231 } 18232 } 18233 } 18234 } 18235 18236 if (!Val) { 18237 if (Enum->isDependentType()) 18238 EltTy = Context.DependentTy; 18239 else if (!LastEnumConst) { 18240 // C++0x [dcl.enum]p5: 18241 // If the underlying type is not fixed, the type of each enumerator 18242 // is the type of its initializing value: 18243 // - If no initializer is specified for the first enumerator, the 18244 // initializing value has an unspecified integral type. 18245 // 18246 // GCC uses 'int' for its unspecified integral type, as does 18247 // C99 6.7.2.2p3. 18248 if (Enum->isFixed()) { 18249 EltTy = Enum->getIntegerType(); 18250 } 18251 else { 18252 EltTy = Context.IntTy; 18253 } 18254 } else { 18255 // Assign the last value + 1. 18256 EnumVal = LastEnumConst->getInitVal(); 18257 ++EnumVal; 18258 EltTy = LastEnumConst->getType(); 18259 18260 // Check for overflow on increment. 18261 if (EnumVal < LastEnumConst->getInitVal()) { 18262 // C++0x [dcl.enum]p5: 18263 // If the underlying type is not fixed, the type of each enumerator 18264 // is the type of its initializing value: 18265 // 18266 // - Otherwise the type of the initializing value is the same as 18267 // the type of the initializing value of the preceding enumerator 18268 // unless the incremented value is not representable in that type, 18269 // in which case the type is an unspecified integral type 18270 // sufficient to contain the incremented value. If no such type 18271 // exists, the program is ill-formed. 18272 QualType T = getNextLargerIntegralType(Context, EltTy); 18273 if (T.isNull() || Enum->isFixed()) { 18274 // There is no integral type larger enough to represent this 18275 // value. Complain, then allow the value to wrap around. 18276 EnumVal = LastEnumConst->getInitVal(); 18277 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 18278 ++EnumVal; 18279 if (Enum->isFixed()) 18280 // When the underlying type is fixed, this is ill-formed. 18281 Diag(IdLoc, diag::err_enumerator_wrapped) 18282 << toString(EnumVal, 10) 18283 << EltTy; 18284 else 18285 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 18286 << toString(EnumVal, 10); 18287 } else { 18288 EltTy = T; 18289 } 18290 18291 // Retrieve the last enumerator's value, extent that type to the 18292 // type that is supposed to be large enough to represent the incremented 18293 // value, then increment. 18294 EnumVal = LastEnumConst->getInitVal(); 18295 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 18296 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 18297 ++EnumVal; 18298 18299 // If we're not in C++, diagnose the overflow of enumerator values, 18300 // which in C99 means that the enumerator value is not representable in 18301 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 18302 // permits enumerator values that are representable in some larger 18303 // integral type. 18304 if (!getLangOpts().CPlusPlus && !T.isNull()) 18305 Diag(IdLoc, diag::warn_enum_value_overflow); 18306 } else if (!getLangOpts().CPlusPlus && 18307 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 18308 // Enforce C99 6.7.2.2p2 even when we compute the next value. 18309 Diag(IdLoc, diag::ext_enum_value_not_int) 18310 << toString(EnumVal, 10) << 1; 18311 } 18312 } 18313 } 18314 18315 if (!EltTy->isDependentType()) { 18316 // Make the enumerator value match the signedness and size of the 18317 // enumerator's type. 18318 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 18319 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 18320 } 18321 18322 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 18323 Val, EnumVal); 18324 } 18325 18326 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 18327 SourceLocation IILoc) { 18328 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 18329 !getLangOpts().CPlusPlus) 18330 return SkipBodyInfo(); 18331 18332 // We have an anonymous enum definition. Look up the first enumerator to 18333 // determine if we should merge the definition with an existing one and 18334 // skip the body. 18335 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 18336 forRedeclarationInCurContext()); 18337 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 18338 if (!PrevECD) 18339 return SkipBodyInfo(); 18340 18341 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 18342 NamedDecl *Hidden; 18343 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 18344 SkipBodyInfo Skip; 18345 Skip.Previous = Hidden; 18346 return Skip; 18347 } 18348 18349 return SkipBodyInfo(); 18350 } 18351 18352 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 18353 SourceLocation IdLoc, IdentifierInfo *Id, 18354 const ParsedAttributesView &Attrs, 18355 SourceLocation EqualLoc, Expr *Val) { 18356 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 18357 EnumConstantDecl *LastEnumConst = 18358 cast_or_null<EnumConstantDecl>(lastEnumConst); 18359 18360 // The scope passed in may not be a decl scope. Zip up the scope tree until 18361 // we find one that is. 18362 S = getNonFieldDeclScope(S); 18363 18364 // Verify that there isn't already something declared with this name in this 18365 // scope. 18366 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration); 18367 LookupName(R, S); 18368 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>(); 18369 18370 if (PrevDecl && PrevDecl->isTemplateParameter()) { 18371 // Maybe we will complain about the shadowed template parameter. 18372 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 18373 // Just pretend that we didn't see the previous declaration. 18374 PrevDecl = nullptr; 18375 } 18376 18377 // C++ [class.mem]p15: 18378 // If T is the name of a class, then each of the following shall have a name 18379 // different from T: 18380 // - every enumerator of every member of class T that is an unscoped 18381 // enumerated type 18382 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) 18383 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 18384 DeclarationNameInfo(Id, IdLoc)); 18385 18386 EnumConstantDecl *New = 18387 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 18388 if (!New) 18389 return nullptr; 18390 18391 if (PrevDecl) { 18392 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) { 18393 // Check for other kinds of shadowing not already handled. 18394 CheckShadow(New, PrevDecl, R); 18395 } 18396 18397 // When in C++, we may get a TagDecl with the same name; in this case the 18398 // enum constant will 'hide' the tag. 18399 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 18400 "Received TagDecl when not in C++!"); 18401 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 18402 if (isa<EnumConstantDecl>(PrevDecl)) 18403 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 18404 else 18405 Diag(IdLoc, diag::err_redefinition) << Id; 18406 notePreviousDefinition(PrevDecl, IdLoc); 18407 return nullptr; 18408 } 18409 } 18410 18411 // Process attributes. 18412 ProcessDeclAttributeList(S, New, Attrs); 18413 AddPragmaAttributes(S, New); 18414 18415 // Register this decl in the current scope stack. 18416 New->setAccess(TheEnumDecl->getAccess()); 18417 PushOnScopeChains(New, S); 18418 18419 ActOnDocumentableDecl(New); 18420 18421 return New; 18422 } 18423 18424 // Returns true when the enum initial expression does not trigger the 18425 // duplicate enum warning. A few common cases are exempted as follows: 18426 // Element2 = Element1 18427 // Element2 = Element1 + 1 18428 // Element2 = Element1 - 1 18429 // Where Element2 and Element1 are from the same enum. 18430 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 18431 Expr *InitExpr = ECD->getInitExpr(); 18432 if (!InitExpr) 18433 return true; 18434 InitExpr = InitExpr->IgnoreImpCasts(); 18435 18436 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 18437 if (!BO->isAdditiveOp()) 18438 return true; 18439 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 18440 if (!IL) 18441 return true; 18442 if (IL->getValue() != 1) 18443 return true; 18444 18445 InitExpr = BO->getLHS(); 18446 } 18447 18448 // This checks if the elements are from the same enum. 18449 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 18450 if (!DRE) 18451 return true; 18452 18453 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 18454 if (!EnumConstant) 18455 return true; 18456 18457 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 18458 Enum) 18459 return true; 18460 18461 return false; 18462 } 18463 18464 // Emits a warning when an element is implicitly set a value that 18465 // a previous element has already been set to. 18466 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 18467 EnumDecl *Enum, QualType EnumType) { 18468 // Avoid anonymous enums 18469 if (!Enum->getIdentifier()) 18470 return; 18471 18472 // Only check for small enums. 18473 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 18474 return; 18475 18476 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 18477 return; 18478 18479 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 18480 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; 18481 18482 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 18483 18484 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map. 18485 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap; 18486 18487 // Use int64_t as a key to avoid needing special handling for map keys. 18488 auto EnumConstantToKey = [](const EnumConstantDecl *D) { 18489 llvm::APSInt Val = D->getInitVal(); 18490 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); 18491 }; 18492 18493 DuplicatesVector DupVector; 18494 ValueToVectorMap EnumMap; 18495 18496 // Populate the EnumMap with all values represented by enum constants without 18497 // an initializer. 18498 for (auto *Element : Elements) { 18499 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); 18500 18501 // Null EnumConstantDecl means a previous diagnostic has been emitted for 18502 // this constant. Skip this enum since it may be ill-formed. 18503 if (!ECD) { 18504 return; 18505 } 18506 18507 // Constants with initalizers are handled in the next loop. 18508 if (ECD->getInitExpr()) 18509 continue; 18510 18511 // Duplicate values are handled in the next loop. 18512 EnumMap.insert({EnumConstantToKey(ECD), ECD}); 18513 } 18514 18515 if (EnumMap.size() == 0) 18516 return; 18517 18518 // Create vectors for any values that has duplicates. 18519 for (auto *Element : Elements) { 18520 // The last loop returned if any constant was null. 18521 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); 18522 if (!ValidDuplicateEnum(ECD, Enum)) 18523 continue; 18524 18525 auto Iter = EnumMap.find(EnumConstantToKey(ECD)); 18526 if (Iter == EnumMap.end()) 18527 continue; 18528 18529 DeclOrVector& Entry = Iter->second; 18530 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 18531 // Ensure constants are different. 18532 if (D == ECD) 18533 continue; 18534 18535 // Create new vector and push values onto it. 18536 auto Vec = std::make_unique<ECDVector>(); 18537 Vec->push_back(D); 18538 Vec->push_back(ECD); 18539 18540 // Update entry to point to the duplicates vector. 18541 Entry = Vec.get(); 18542 18543 // Store the vector somewhere we can consult later for quick emission of 18544 // diagnostics. 18545 DupVector.emplace_back(std::move(Vec)); 18546 continue; 18547 } 18548 18549 ECDVector *Vec = Entry.get<ECDVector*>(); 18550 // Make sure constants are not added more than once. 18551 if (*Vec->begin() == ECD) 18552 continue; 18553 18554 Vec->push_back(ECD); 18555 } 18556 18557 // Emit diagnostics. 18558 for (const auto &Vec : DupVector) { 18559 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 18560 18561 // Emit warning for one enum constant. 18562 auto *FirstECD = Vec->front(); 18563 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) 18564 << FirstECD << toString(FirstECD->getInitVal(), 10) 18565 << FirstECD->getSourceRange(); 18566 18567 // Emit one note for each of the remaining enum constants with 18568 // the same value. 18569 for (auto *ECD : llvm::drop_begin(*Vec)) 18570 S.Diag(ECD->getLocation(), diag::note_duplicate_element) 18571 << ECD << toString(ECD->getInitVal(), 10) 18572 << ECD->getSourceRange(); 18573 } 18574 } 18575 18576 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 18577 bool AllowMask) const { 18578 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 18579 assert(ED->isCompleteDefinition() && "expected enum definition"); 18580 18581 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 18582 llvm::APInt &FlagBits = R.first->second; 18583 18584 if (R.second) { 18585 for (auto *E : ED->enumerators()) { 18586 const auto &EVal = E->getInitVal(); 18587 // Only single-bit enumerators introduce new flag values. 18588 if (EVal.isPowerOf2()) 18589 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 18590 } 18591 } 18592 18593 // A value is in a flag enum if either its bits are a subset of the enum's 18594 // flag bits (the first condition) or we are allowing masks and the same is 18595 // true of its complement (the second condition). When masks are allowed, we 18596 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 18597 // 18598 // While it's true that any value could be used as a mask, the assumption is 18599 // that a mask will have all of the insignificant bits set. Anything else is 18600 // likely a logic error. 18601 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 18602 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 18603 } 18604 18605 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 18606 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S, 18607 const ParsedAttributesView &Attrs) { 18608 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 18609 QualType EnumType = Context.getTypeDeclType(Enum); 18610 18611 ProcessDeclAttributeList(S, Enum, Attrs); 18612 18613 if (Enum->isDependentType()) { 18614 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 18615 EnumConstantDecl *ECD = 18616 cast_or_null<EnumConstantDecl>(Elements[i]); 18617 if (!ECD) continue; 18618 18619 ECD->setType(EnumType); 18620 } 18621 18622 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 18623 return; 18624 } 18625 18626 // TODO: If the result value doesn't fit in an int, it must be a long or long 18627 // long value. ISO C does not support this, but GCC does as an extension, 18628 // emit a warning. 18629 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 18630 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 18631 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 18632 18633 // Verify that all the values are okay, compute the size of the values, and 18634 // reverse the list. 18635 unsigned NumNegativeBits = 0; 18636 unsigned NumPositiveBits = 0; 18637 18638 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 18639 EnumConstantDecl *ECD = 18640 cast_or_null<EnumConstantDecl>(Elements[i]); 18641 if (!ECD) continue; // Already issued a diagnostic. 18642 18643 const llvm::APSInt &InitVal = ECD->getInitVal(); 18644 18645 // Keep track of the size of positive and negative values. 18646 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 18647 NumPositiveBits = std::max(NumPositiveBits, 18648 (unsigned)InitVal.getActiveBits()); 18649 else 18650 NumNegativeBits = std::max(NumNegativeBits, 18651 (unsigned)InitVal.getMinSignedBits()); 18652 } 18653 18654 // Figure out the type that should be used for this enum. 18655 QualType BestType; 18656 unsigned BestWidth; 18657 18658 // C++0x N3000 [conv.prom]p3: 18659 // An rvalue of an unscoped enumeration type whose underlying 18660 // type is not fixed can be converted to an rvalue of the first 18661 // of the following types that can represent all the values of 18662 // the enumeration: int, unsigned int, long int, unsigned long 18663 // int, long long int, or unsigned long long int. 18664 // C99 6.4.4.3p2: 18665 // An identifier declared as an enumeration constant has type int. 18666 // The C99 rule is modified by a gcc extension 18667 QualType BestPromotionType; 18668 18669 bool Packed = Enum->hasAttr<PackedAttr>(); 18670 // -fshort-enums is the equivalent to specifying the packed attribute on all 18671 // enum definitions. 18672 if (LangOpts.ShortEnums) 18673 Packed = true; 18674 18675 // If the enum already has a type because it is fixed or dictated by the 18676 // target, promote that type instead of analyzing the enumerators. 18677 if (Enum->isComplete()) { 18678 BestType = Enum->getIntegerType(); 18679 if (BestType->isPromotableIntegerType()) 18680 BestPromotionType = Context.getPromotedIntegerType(BestType); 18681 else 18682 BestPromotionType = BestType; 18683 18684 BestWidth = Context.getIntWidth(BestType); 18685 } 18686 else if (NumNegativeBits) { 18687 // If there is a negative value, figure out the smallest integer type (of 18688 // int/long/longlong) that fits. 18689 // If it's packed, check also if it fits a char or a short. 18690 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 18691 BestType = Context.SignedCharTy; 18692 BestWidth = CharWidth; 18693 } else if (Packed && NumNegativeBits <= ShortWidth && 18694 NumPositiveBits < ShortWidth) { 18695 BestType = Context.ShortTy; 18696 BestWidth = ShortWidth; 18697 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 18698 BestType = Context.IntTy; 18699 BestWidth = IntWidth; 18700 } else { 18701 BestWidth = Context.getTargetInfo().getLongWidth(); 18702 18703 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 18704 BestType = Context.LongTy; 18705 } else { 18706 BestWidth = Context.getTargetInfo().getLongLongWidth(); 18707 18708 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 18709 Diag(Enum->getLocation(), diag::ext_enum_too_large); 18710 BestType = Context.LongLongTy; 18711 } 18712 } 18713 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 18714 } else { 18715 // If there is no negative value, figure out the smallest type that fits 18716 // all of the enumerator values. 18717 // If it's packed, check also if it fits a char or a short. 18718 if (Packed && NumPositiveBits <= CharWidth) { 18719 BestType = Context.UnsignedCharTy; 18720 BestPromotionType = Context.IntTy; 18721 BestWidth = CharWidth; 18722 } else if (Packed && NumPositiveBits <= ShortWidth) { 18723 BestType = Context.UnsignedShortTy; 18724 BestPromotionType = Context.IntTy; 18725 BestWidth = ShortWidth; 18726 } else if (NumPositiveBits <= IntWidth) { 18727 BestType = Context.UnsignedIntTy; 18728 BestWidth = IntWidth; 18729 BestPromotionType 18730 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18731 ? Context.UnsignedIntTy : Context.IntTy; 18732 } else if (NumPositiveBits <= 18733 (BestWidth = Context.getTargetInfo().getLongWidth())) { 18734 BestType = Context.UnsignedLongTy; 18735 BestPromotionType 18736 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18737 ? Context.UnsignedLongTy : Context.LongTy; 18738 } else { 18739 BestWidth = Context.getTargetInfo().getLongLongWidth(); 18740 assert(NumPositiveBits <= BestWidth && 18741 "How could an initializer get larger than ULL?"); 18742 BestType = Context.UnsignedLongLongTy; 18743 BestPromotionType 18744 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18745 ? Context.UnsignedLongLongTy : Context.LongLongTy; 18746 } 18747 } 18748 18749 // Loop over all of the enumerator constants, changing their types to match 18750 // the type of the enum if needed. 18751 for (auto *D : Elements) { 18752 auto *ECD = cast_or_null<EnumConstantDecl>(D); 18753 if (!ECD) continue; // Already issued a diagnostic. 18754 18755 // Standard C says the enumerators have int type, but we allow, as an 18756 // extension, the enumerators to be larger than int size. If each 18757 // enumerator value fits in an int, type it as an int, otherwise type it the 18758 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 18759 // that X has type 'int', not 'unsigned'. 18760 18761 // Determine whether the value fits into an int. 18762 llvm::APSInt InitVal = ECD->getInitVal(); 18763 18764 // If it fits into an integer type, force it. Otherwise force it to match 18765 // the enum decl type. 18766 QualType NewTy; 18767 unsigned NewWidth; 18768 bool NewSign; 18769 if (!getLangOpts().CPlusPlus && 18770 !Enum->isFixed() && 18771 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 18772 NewTy = Context.IntTy; 18773 NewWidth = IntWidth; 18774 NewSign = true; 18775 } else if (ECD->getType() == BestType) { 18776 // Already the right type! 18777 if (getLangOpts().CPlusPlus) 18778 // C++ [dcl.enum]p4: Following the closing brace of an 18779 // enum-specifier, each enumerator has the type of its 18780 // enumeration. 18781 ECD->setType(EnumType); 18782 continue; 18783 } else { 18784 NewTy = BestType; 18785 NewWidth = BestWidth; 18786 NewSign = BestType->isSignedIntegerOrEnumerationType(); 18787 } 18788 18789 // Adjust the APSInt value. 18790 InitVal = InitVal.extOrTrunc(NewWidth); 18791 InitVal.setIsSigned(NewSign); 18792 ECD->setInitVal(InitVal); 18793 18794 // Adjust the Expr initializer and type. 18795 if (ECD->getInitExpr() && 18796 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 18797 ECD->setInitExpr(ImplicitCastExpr::Create( 18798 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(), 18799 /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride())); 18800 if (getLangOpts().CPlusPlus) 18801 // C++ [dcl.enum]p4: Following the closing brace of an 18802 // enum-specifier, each enumerator has the type of its 18803 // enumeration. 18804 ECD->setType(EnumType); 18805 else 18806 ECD->setType(NewTy); 18807 } 18808 18809 Enum->completeDefinition(BestType, BestPromotionType, 18810 NumPositiveBits, NumNegativeBits); 18811 18812 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 18813 18814 if (Enum->isClosedFlag()) { 18815 for (Decl *D : Elements) { 18816 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 18817 if (!ECD) continue; // Already issued a diagnostic. 18818 18819 llvm::APSInt InitVal = ECD->getInitVal(); 18820 if (InitVal != 0 && !InitVal.isPowerOf2() && 18821 !IsValueInFlagEnum(Enum, InitVal, true)) 18822 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 18823 << ECD << Enum; 18824 } 18825 } 18826 18827 // Now that the enum type is defined, ensure it's not been underaligned. 18828 if (Enum->hasAttrs()) 18829 CheckAlignasUnderalignment(Enum); 18830 } 18831 18832 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 18833 SourceLocation StartLoc, 18834 SourceLocation EndLoc) { 18835 StringLiteral *AsmString = cast<StringLiteral>(expr); 18836 18837 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 18838 AsmString, StartLoc, 18839 EndLoc); 18840 CurContext->addDecl(New); 18841 return New; 18842 } 18843 18844 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 18845 IdentifierInfo* AliasName, 18846 SourceLocation PragmaLoc, 18847 SourceLocation NameLoc, 18848 SourceLocation AliasNameLoc) { 18849 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 18850 LookupOrdinaryName); 18851 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc), 18852 AttributeCommonInfo::AS_Pragma); 18853 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit( 18854 Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info); 18855 18856 // If a declaration that: 18857 // 1) declares a function or a variable 18858 // 2) has external linkage 18859 // already exists, add a label attribute to it. 18860 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18861 if (isDeclExternC(PrevDecl)) 18862 PrevDecl->addAttr(Attr); 18863 else 18864 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 18865 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 18866 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 18867 } else 18868 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 18869 } 18870 18871 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 18872 SourceLocation PragmaLoc, 18873 SourceLocation NameLoc) { 18874 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 18875 18876 if (PrevDecl) { 18877 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma)); 18878 } else { 18879 (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc)); 18880 } 18881 } 18882 18883 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 18884 IdentifierInfo* AliasName, 18885 SourceLocation PragmaLoc, 18886 SourceLocation NameLoc, 18887 SourceLocation AliasNameLoc) { 18888 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 18889 LookupOrdinaryName); 18890 WeakInfo W = WeakInfo(Name, NameLoc); 18891 18892 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18893 if (!PrevDecl->hasAttr<AliasAttr>()) 18894 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 18895 DeclApplyPragmaWeak(TUScope, ND, W); 18896 } else { 18897 (void)WeakUndeclaredIdentifiers[AliasName].insert(W); 18898 } 18899 } 18900 18901 Decl *Sema::getObjCDeclContext() const { 18902 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 18903 } 18904 18905 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD, 18906 bool Final) { 18907 assert(FD && "Expected non-null FunctionDecl"); 18908 18909 // SYCL functions can be template, so we check if they have appropriate 18910 // attribute prior to checking if it is a template. 18911 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>()) 18912 return FunctionEmissionStatus::Emitted; 18913 18914 // Templates are emitted when they're instantiated. 18915 if (FD->isDependentContext()) 18916 return FunctionEmissionStatus::TemplateDiscarded; 18917 18918 // Check whether this function is an externally visible definition. 18919 auto IsEmittedForExternalSymbol = [this, FD]() { 18920 // We have to check the GVA linkage of the function's *definition* -- if we 18921 // only have a declaration, we don't know whether or not the function will 18922 // be emitted, because (say) the definition could include "inline". 18923 FunctionDecl *Def = FD->getDefinition(); 18924 18925 return Def && !isDiscardableGVALinkage( 18926 getASTContext().GetGVALinkageForFunction(Def)); 18927 }; 18928 18929 if (LangOpts.OpenMPIsDevice) { 18930 // In OpenMP device mode we will not emit host only functions, or functions 18931 // we don't need due to their linkage. 18932 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18933 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18934 // DevTy may be changed later by 18935 // #pragma omp declare target to(*) device_type(*). 18936 // Therefore DevTy having no value does not imply host. The emission status 18937 // will be checked again at the end of compilation unit with Final = true. 18938 if (DevTy.hasValue()) 18939 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host) 18940 return FunctionEmissionStatus::OMPDiscarded; 18941 // If we have an explicit value for the device type, or we are in a target 18942 // declare context, we need to emit all extern and used symbols. 18943 if (isInOpenMPDeclareTargetContext() || DevTy.hasValue()) 18944 if (IsEmittedForExternalSymbol()) 18945 return FunctionEmissionStatus::Emitted; 18946 // Device mode only emits what it must, if it wasn't tagged yet and needed, 18947 // we'll omit it. 18948 if (Final) 18949 return FunctionEmissionStatus::OMPDiscarded; 18950 } else if (LangOpts.OpenMP > 45) { 18951 // In OpenMP host compilation prior to 5.0 everything was an emitted host 18952 // function. In 5.0, no_host was introduced which might cause a function to 18953 // be ommitted. 18954 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18955 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18956 if (DevTy.hasValue()) 18957 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) 18958 return FunctionEmissionStatus::OMPDiscarded; 18959 } 18960 18961 if (Final && LangOpts.OpenMP && !LangOpts.CUDA) 18962 return FunctionEmissionStatus::Emitted; 18963 18964 if (LangOpts.CUDA) { 18965 // When compiling for device, host functions are never emitted. Similarly, 18966 // when compiling for host, device and global functions are never emitted. 18967 // (Technically, we do emit a host-side stub for global functions, but this 18968 // doesn't count for our purposes here.) 18969 Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD); 18970 if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host) 18971 return FunctionEmissionStatus::CUDADiscarded; 18972 if (!LangOpts.CUDAIsDevice && 18973 (T == Sema::CFT_Device || T == Sema::CFT_Global)) 18974 return FunctionEmissionStatus::CUDADiscarded; 18975 18976 if (IsEmittedForExternalSymbol()) 18977 return FunctionEmissionStatus::Emitted; 18978 } 18979 18980 // Otherwise, the function is known-emitted if it's in our set of 18981 // known-emitted functions. 18982 return FunctionEmissionStatus::Unknown; 18983 } 18984 18985 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) { 18986 // Host-side references to a __global__ function refer to the stub, so the 18987 // function itself is never emitted and therefore should not be marked. 18988 // If we have host fn calls kernel fn calls host+device, the HD function 18989 // does not get instantiated on the host. We model this by omitting at the 18990 // call to the kernel from the callgraph. This ensures that, when compiling 18991 // for host, only HD functions actually called from the host get marked as 18992 // known-emitted. 18993 return LangOpts.CUDA && !LangOpts.CUDAIsDevice && 18994 IdentifyCUDATarget(Callee) == CFT_Global; 18995 } 18996