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 Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New; 1683 Diag(Old->getLocation(), diag::note_previous_declaration); 1684 return true; 1685 } 1686 1687 // A wrapper function for checking the semantic restrictions of 1688 // a redeclaration within a module. 1689 bool Sema::CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old) { 1690 if (CheckRedeclarationModuleOwnership(New, Old)) 1691 return true; 1692 1693 if (CheckRedeclarationExported(New, Old)) 1694 return true; 1695 1696 return false; 1697 } 1698 1699 static bool isUsingDecl(NamedDecl *D) { 1700 return isa<UsingShadowDecl>(D) || 1701 isa<UnresolvedUsingTypenameDecl>(D) || 1702 isa<UnresolvedUsingValueDecl>(D); 1703 } 1704 1705 /// Removes using shadow declarations from the lookup results. 1706 static void RemoveUsingDecls(LookupResult &R) { 1707 LookupResult::Filter F = R.makeFilter(); 1708 while (F.hasNext()) 1709 if (isUsingDecl(F.next())) 1710 F.erase(); 1711 1712 F.done(); 1713 } 1714 1715 /// Check for this common pattern: 1716 /// @code 1717 /// class S { 1718 /// S(const S&); // DO NOT IMPLEMENT 1719 /// void operator=(const S&); // DO NOT IMPLEMENT 1720 /// }; 1721 /// @endcode 1722 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1723 // FIXME: Should check for private access too but access is set after we get 1724 // the decl here. 1725 if (D->doesThisDeclarationHaveABody()) 1726 return false; 1727 1728 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1729 return CD->isCopyConstructor(); 1730 return D->isCopyAssignmentOperator(); 1731 } 1732 1733 // We need this to handle 1734 // 1735 // typedef struct { 1736 // void *foo() { return 0; } 1737 // } A; 1738 // 1739 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1740 // for example. If 'A', foo will have external linkage. If we have '*A', 1741 // foo will have no linkage. Since we can't know until we get to the end 1742 // of the typedef, this function finds out if D might have non-external linkage. 1743 // Callers should verify at the end of the TU if it D has external linkage or 1744 // not. 1745 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1746 const DeclContext *DC = D->getDeclContext(); 1747 while (!DC->isTranslationUnit()) { 1748 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1749 if (!RD->hasNameForLinkage()) 1750 return true; 1751 } 1752 DC = DC->getParent(); 1753 } 1754 1755 return !D->isExternallyVisible(); 1756 } 1757 1758 // FIXME: This needs to be refactored; some other isInMainFile users want 1759 // these semantics. 1760 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1761 if (S.TUKind != TU_Complete) 1762 return false; 1763 return S.SourceMgr.isInMainFile(Loc); 1764 } 1765 1766 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1767 assert(D); 1768 1769 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1770 return false; 1771 1772 // Ignore all entities declared within templates, and out-of-line definitions 1773 // of members of class templates. 1774 if (D->getDeclContext()->isDependentContext() || 1775 D->getLexicalDeclContext()->isDependentContext()) 1776 return false; 1777 1778 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1779 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1780 return false; 1781 // A non-out-of-line declaration of a member specialization was implicitly 1782 // instantiated; it's the out-of-line declaration that we're interested in. 1783 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1784 FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) 1785 return false; 1786 1787 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1788 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1789 return false; 1790 } else { 1791 // 'static inline' functions are defined in headers; don't warn. 1792 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1793 return false; 1794 } 1795 1796 if (FD->doesThisDeclarationHaveABody() && 1797 Context.DeclMustBeEmitted(FD)) 1798 return false; 1799 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1800 // Constants and utility variables are defined in headers with internal 1801 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1802 // like "inline".) 1803 if (!isMainFileLoc(*this, VD->getLocation())) 1804 return false; 1805 1806 if (Context.DeclMustBeEmitted(VD)) 1807 return false; 1808 1809 if (VD->isStaticDataMember() && 1810 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1811 return false; 1812 if (VD->isStaticDataMember() && 1813 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1814 VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) 1815 return false; 1816 1817 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) 1818 return false; 1819 } else { 1820 return false; 1821 } 1822 1823 // Only warn for unused decls internal to the translation unit. 1824 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1825 // for inline functions defined in the main source file, for instance. 1826 return mightHaveNonExternalLinkage(D); 1827 } 1828 1829 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1830 if (!D) 1831 return; 1832 1833 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1834 const FunctionDecl *First = FD->getFirstDecl(); 1835 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1836 return; // First should already be in the vector. 1837 } 1838 1839 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1840 const VarDecl *First = VD->getFirstDecl(); 1841 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1842 return; // First should already be in the vector. 1843 } 1844 1845 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1846 UnusedFileScopedDecls.push_back(D); 1847 } 1848 1849 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1850 if (D->isInvalidDecl()) 1851 return false; 1852 1853 if (auto *DD = dyn_cast<DecompositionDecl>(D)) { 1854 // For a decomposition declaration, warn if none of the bindings are 1855 // referenced, instead of if the variable itself is referenced (which 1856 // it is, by the bindings' expressions). 1857 for (auto *BD : DD->bindings()) 1858 if (BD->isReferenced()) 1859 return false; 1860 } else if (!D->getDeclName()) { 1861 return false; 1862 } else if (D->isReferenced() || D->isUsed()) { 1863 return false; 1864 } 1865 1866 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>()) 1867 return false; 1868 1869 if (isa<LabelDecl>(D)) 1870 return true; 1871 1872 // Except for labels, we only care about unused decls that are local to 1873 // functions. 1874 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1875 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1876 // For dependent types, the diagnostic is deferred. 1877 WithinFunction = 1878 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1879 if (!WithinFunction) 1880 return false; 1881 1882 if (isa<TypedefNameDecl>(D)) 1883 return true; 1884 1885 // White-list anything that isn't a local variable. 1886 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1887 return false; 1888 1889 // Types of valid local variables should be complete, so this should succeed. 1890 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1891 1892 // White-list anything with an __attribute__((unused)) type. 1893 const auto *Ty = VD->getType().getTypePtr(); 1894 1895 // Only look at the outermost level of typedef. 1896 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1897 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1898 return false; 1899 } 1900 1901 // If we failed to complete the type for some reason, or if the type is 1902 // dependent, don't diagnose the variable. 1903 if (Ty->isIncompleteType() || Ty->isDependentType()) 1904 return false; 1905 1906 // Look at the element type to ensure that the warning behaviour is 1907 // consistent for both scalars and arrays. 1908 Ty = Ty->getBaseElementTypeUnsafe(); 1909 1910 if (const TagType *TT = Ty->getAs<TagType>()) { 1911 const TagDecl *Tag = TT->getDecl(); 1912 if (Tag->hasAttr<UnusedAttr>()) 1913 return false; 1914 1915 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1916 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1917 return false; 1918 1919 if (const Expr *Init = VD->getInit()) { 1920 if (const ExprWithCleanups *Cleanups = 1921 dyn_cast<ExprWithCleanups>(Init)) 1922 Init = Cleanups->getSubExpr(); 1923 const CXXConstructExpr *Construct = 1924 dyn_cast<CXXConstructExpr>(Init); 1925 if (Construct && !Construct->isElidable()) { 1926 CXXConstructorDecl *CD = Construct->getConstructor(); 1927 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() && 1928 (VD->getInit()->isValueDependent() || !VD->evaluateValue())) 1929 return false; 1930 } 1931 1932 // Suppress the warning if we don't know how this is constructed, and 1933 // it could possibly be non-trivial constructor. 1934 if (Init->isTypeDependent()) 1935 for (const CXXConstructorDecl *Ctor : RD->ctors()) 1936 if (!Ctor->isTrivial()) 1937 return false; 1938 } 1939 } 1940 } 1941 1942 // TODO: __attribute__((unused)) templates? 1943 } 1944 1945 return true; 1946 } 1947 1948 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1949 FixItHint &Hint) { 1950 if (isa<LabelDecl>(D)) { 1951 SourceLocation AfterColon = Lexer::findLocationAfterToken( 1952 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), 1953 true); 1954 if (AfterColon.isInvalid()) 1955 return; 1956 Hint = FixItHint::CreateRemoval( 1957 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon)); 1958 } 1959 } 1960 1961 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1962 if (D->getTypeForDecl()->isDependentType()) 1963 return; 1964 1965 for (auto *TmpD : D->decls()) { 1966 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1967 DiagnoseUnusedDecl(T); 1968 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1969 DiagnoseUnusedNestedTypedefs(R); 1970 } 1971 } 1972 1973 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1974 /// unless they are marked attr(unused). 1975 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1976 if (!ShouldDiagnoseUnusedDecl(D)) 1977 return; 1978 1979 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1980 // typedefs can be referenced later on, so the diagnostics are emitted 1981 // at end-of-translation-unit. 1982 UnusedLocalTypedefNameCandidates.insert(TD); 1983 return; 1984 } 1985 1986 FixItHint Hint; 1987 GenerateFixForUnusedDecl(D, Context, Hint); 1988 1989 unsigned DiagID; 1990 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1991 DiagID = diag::warn_unused_exception_param; 1992 else if (isa<LabelDecl>(D)) 1993 DiagID = diag::warn_unused_label; 1994 else 1995 DiagID = diag::warn_unused_variable; 1996 1997 Diag(D->getLocation(), DiagID) << D << Hint; 1998 } 1999 2000 void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD) { 2001 // If it's not referenced, it can't be set. If it has the Cleanup attribute, 2002 // it's not really unused. 2003 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<UnusedAttr>() || 2004 VD->hasAttr<CleanupAttr>()) 2005 return; 2006 2007 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe(); 2008 2009 if (Ty->isReferenceType() || Ty->isDependentType()) 2010 return; 2011 2012 if (const TagType *TT = Ty->getAs<TagType>()) { 2013 const TagDecl *Tag = TT->getDecl(); 2014 if (Tag->hasAttr<UnusedAttr>()) 2015 return; 2016 // In C++, don't warn for record types that don't have WarnUnusedAttr, to 2017 // mimic gcc's behavior. 2018 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 2019 if (!RD->hasAttr<WarnUnusedAttr>()) 2020 return; 2021 } 2022 } 2023 2024 // Don't warn about __block Objective-C pointer variables, as they might 2025 // be assigned in the block but not used elsewhere for the purpose of lifetime 2026 // extension. 2027 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType()) 2028 return; 2029 2030 // Don't warn about Objective-C pointer variables with precise lifetime 2031 // semantics; they can be used to ensure ARC releases the object at a known 2032 // time, which may mean assignment but no other references. 2033 if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType()) 2034 return; 2035 2036 auto iter = RefsMinusAssignments.find(VD); 2037 if (iter == RefsMinusAssignments.end()) 2038 return; 2039 2040 assert(iter->getSecond() >= 0 && 2041 "Found a negative number of references to a VarDecl"); 2042 if (iter->getSecond() != 0) 2043 return; 2044 unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter 2045 : diag::warn_unused_but_set_variable; 2046 Diag(VD->getLocation(), DiagID) << VD; 2047 } 2048 2049 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 2050 // Verify that we have no forward references left. If so, there was a goto 2051 // or address of a label taken, but no definition of it. Label fwd 2052 // definitions are indicated with a null substmt which is also not a resolved 2053 // MS inline assembly label name. 2054 bool Diagnose = false; 2055 if (L->isMSAsmLabel()) 2056 Diagnose = !L->isResolvedMSAsmLabel(); 2057 else 2058 Diagnose = L->getStmt() == nullptr; 2059 if (Diagnose) 2060 S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L; 2061 } 2062 2063 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 2064 S->mergeNRVOIntoParent(); 2065 2066 if (S->decl_empty()) return; 2067 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 2068 "Scope shouldn't contain decls!"); 2069 2070 for (auto *TmpD : S->decls()) { 2071 assert(TmpD && "This decl didn't get pushed??"); 2072 2073 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 2074 NamedDecl *D = cast<NamedDecl>(TmpD); 2075 2076 // Diagnose unused variables in this scope. 2077 if (!S->hasUnrecoverableErrorOccurred()) { 2078 DiagnoseUnusedDecl(D); 2079 if (const auto *RD = dyn_cast<RecordDecl>(D)) 2080 DiagnoseUnusedNestedTypedefs(RD); 2081 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 2082 DiagnoseUnusedButSetDecl(VD); 2083 RefsMinusAssignments.erase(VD); 2084 } 2085 } 2086 2087 if (!D->getDeclName()) continue; 2088 2089 // If this was a forward reference to a label, verify it was defined. 2090 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 2091 CheckPoppedLabel(LD, *this); 2092 2093 // Remove this name from our lexical scope, and warn on it if we haven't 2094 // already. 2095 IdResolver.RemoveDecl(D); 2096 auto ShadowI = ShadowingDecls.find(D); 2097 if (ShadowI != ShadowingDecls.end()) { 2098 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { 2099 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) 2100 << D << FD << FD->getParent(); 2101 Diag(FD->getLocation(), diag::note_previous_declaration); 2102 } 2103 ShadowingDecls.erase(ShadowI); 2104 } 2105 } 2106 } 2107 2108 /// Look for an Objective-C class in the translation unit. 2109 /// 2110 /// \param Id The name of the Objective-C class we're looking for. If 2111 /// typo-correction fixes this name, the Id will be updated 2112 /// to the fixed name. 2113 /// 2114 /// \param IdLoc The location of the name in the translation unit. 2115 /// 2116 /// \param DoTypoCorrection If true, this routine will attempt typo correction 2117 /// if there is no class with the given name. 2118 /// 2119 /// \returns The declaration of the named Objective-C class, or NULL if the 2120 /// class could not be found. 2121 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 2122 SourceLocation IdLoc, 2123 bool DoTypoCorrection) { 2124 // The third "scope" argument is 0 since we aren't enabling lazy built-in 2125 // creation from this context. 2126 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 2127 2128 if (!IDecl && DoTypoCorrection) { 2129 // Perform typo correction at the given location, but only if we 2130 // find an Objective-C class name. 2131 DeclFilterCCC<ObjCInterfaceDecl> CCC{}; 2132 if (TypoCorrection C = 2133 CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, 2134 TUScope, nullptr, CCC, CTK_ErrorRecovery)) { 2135 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 2136 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 2137 Id = IDecl->getIdentifier(); 2138 } 2139 } 2140 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 2141 // This routine must always return a class definition, if any. 2142 if (Def && Def->getDefinition()) 2143 Def = Def->getDefinition(); 2144 return Def; 2145 } 2146 2147 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 2148 /// from S, where a non-field would be declared. This routine copes 2149 /// with the difference between C and C++ scoping rules in structs and 2150 /// unions. For example, the following code is well-formed in C but 2151 /// ill-formed in C++: 2152 /// @code 2153 /// struct S6 { 2154 /// enum { BAR } e; 2155 /// }; 2156 /// 2157 /// void test_S6() { 2158 /// struct S6 a; 2159 /// a.e = BAR; 2160 /// } 2161 /// @endcode 2162 /// For the declaration of BAR, this routine will return a different 2163 /// scope. The scope S will be the scope of the unnamed enumeration 2164 /// within S6. In C++, this routine will return the scope associated 2165 /// with S6, because the enumeration's scope is a transparent 2166 /// context but structures can contain non-field names. In C, this 2167 /// routine will return the translation unit scope, since the 2168 /// enumeration's scope is a transparent context and structures cannot 2169 /// contain non-field names. 2170 Scope *Sema::getNonFieldDeclScope(Scope *S) { 2171 while (((S->getFlags() & Scope::DeclScope) == 0) || 2172 (S->getEntity() && S->getEntity()->isTransparentContext()) || 2173 (S->isClassScope() && !getLangOpts().CPlusPlus)) 2174 S = S->getParent(); 2175 return S; 2176 } 2177 2178 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, 2179 ASTContext::GetBuiltinTypeError Error) { 2180 switch (Error) { 2181 case ASTContext::GE_None: 2182 return ""; 2183 case ASTContext::GE_Missing_type: 2184 return BuiltinInfo.getHeaderName(ID); 2185 case ASTContext::GE_Missing_stdio: 2186 return "stdio.h"; 2187 case ASTContext::GE_Missing_setjmp: 2188 return "setjmp.h"; 2189 case ASTContext::GE_Missing_ucontext: 2190 return "ucontext.h"; 2191 } 2192 llvm_unreachable("unhandled error kind"); 2193 } 2194 2195 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type, 2196 unsigned ID, SourceLocation Loc) { 2197 DeclContext *Parent = Context.getTranslationUnitDecl(); 2198 2199 if (getLangOpts().CPlusPlus) { 2200 LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create( 2201 Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false); 2202 CLinkageDecl->setImplicit(); 2203 Parent->addDecl(CLinkageDecl); 2204 Parent = CLinkageDecl; 2205 } 2206 2207 FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type, 2208 /*TInfo=*/nullptr, SC_Extern, 2209 getCurFPFeatures().isFPConstrained(), 2210 false, Type->isFunctionProtoType()); 2211 New->setImplicit(); 2212 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID)); 2213 2214 // Create Decl objects for each parameter, adding them to the 2215 // FunctionDecl. 2216 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) { 2217 SmallVector<ParmVarDecl *, 16> Params; 2218 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 2219 ParmVarDecl *parm = ParmVarDecl::Create( 2220 Context, New, SourceLocation(), SourceLocation(), nullptr, 2221 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr); 2222 parm->setScopeInfo(0, i); 2223 Params.push_back(parm); 2224 } 2225 New->setParams(Params); 2226 } 2227 2228 AddKnownFunctionAttributes(New); 2229 return New; 2230 } 2231 2232 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 2233 /// file scope. lazily create a decl for it. ForRedeclaration is true 2234 /// if we're creating this built-in in anticipation of redeclaring the 2235 /// built-in. 2236 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 2237 Scope *S, bool ForRedeclaration, 2238 SourceLocation Loc) { 2239 LookupNecessaryTypesForBuiltin(S, ID); 2240 2241 ASTContext::GetBuiltinTypeError Error; 2242 QualType R = Context.GetBuiltinType(ID, Error); 2243 if (Error) { 2244 if (!ForRedeclaration) 2245 return nullptr; 2246 2247 // If we have a builtin without an associated type we should not emit a 2248 // warning when we were not able to find a type for it. 2249 if (Error == ASTContext::GE_Missing_type || 2250 Context.BuiltinInfo.allowTypeMismatch(ID)) 2251 return nullptr; 2252 2253 // If we could not find a type for setjmp it is because the jmp_buf type was 2254 // not defined prior to the setjmp declaration. 2255 if (Error == ASTContext::GE_Missing_setjmp) { 2256 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf) 2257 << Context.BuiltinInfo.getName(ID); 2258 return nullptr; 2259 } 2260 2261 // Generally, we emit a warning that the declaration requires the 2262 // appropriate header. 2263 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 2264 << getHeaderName(Context.BuiltinInfo, ID, Error) 2265 << Context.BuiltinInfo.getName(ID); 2266 return nullptr; 2267 } 2268 2269 if (!ForRedeclaration && 2270 (Context.BuiltinInfo.isPredefinedLibFunction(ID) || 2271 Context.BuiltinInfo.isHeaderDependentFunction(ID))) { 2272 Diag(Loc, diag::ext_implicit_lib_function_decl) 2273 << Context.BuiltinInfo.getName(ID) << R; 2274 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID)) 2275 Diag(Loc, diag::note_include_header_or_declare) 2276 << Header << Context.BuiltinInfo.getName(ID); 2277 } 2278 2279 if (R.isNull()) 2280 return nullptr; 2281 2282 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc); 2283 RegisterLocallyScopedExternCDecl(New, S); 2284 2285 // TUScope is the translation-unit scope to insert this function into. 2286 // FIXME: This is hideous. We need to teach PushOnScopeChains to 2287 // relate Scopes to DeclContexts, and probably eliminate CurContext 2288 // entirely, but we're not there yet. 2289 DeclContext *SavedContext = CurContext; 2290 CurContext = New->getDeclContext(); 2291 PushOnScopeChains(New, TUScope); 2292 CurContext = SavedContext; 2293 return New; 2294 } 2295 2296 /// Typedef declarations don't have linkage, but they still denote the same 2297 /// entity if their types are the same. 2298 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 2299 /// isSameEntity. 2300 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 2301 TypedefNameDecl *Decl, 2302 LookupResult &Previous) { 2303 // This is only interesting when modules are enabled. 2304 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 2305 return; 2306 2307 // Empty sets are uninteresting. 2308 if (Previous.empty()) 2309 return; 2310 2311 LookupResult::Filter Filter = Previous.makeFilter(); 2312 while (Filter.hasNext()) { 2313 NamedDecl *Old = Filter.next(); 2314 2315 // Non-hidden declarations are never ignored. 2316 if (S.isVisible(Old)) 2317 continue; 2318 2319 // Declarations of the same entity are not ignored, even if they have 2320 // different linkages. 2321 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2322 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 2323 Decl->getUnderlyingType())) 2324 continue; 2325 2326 // If both declarations give a tag declaration a typedef name for linkage 2327 // purposes, then they declare the same entity. 2328 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 2329 Decl->getAnonDeclWithTypedefName()) 2330 continue; 2331 } 2332 2333 Filter.erase(); 2334 } 2335 2336 Filter.done(); 2337 } 2338 2339 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 2340 QualType OldType; 2341 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 2342 OldType = OldTypedef->getUnderlyingType(); 2343 else 2344 OldType = Context.getTypeDeclType(Old); 2345 QualType NewType = New->getUnderlyingType(); 2346 2347 if (NewType->isVariablyModifiedType()) { 2348 // Must not redefine a typedef with a variably-modified type. 2349 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2350 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 2351 << Kind << NewType; 2352 if (Old->getLocation().isValid()) 2353 notePreviousDefinition(Old, New->getLocation()); 2354 New->setInvalidDecl(); 2355 return true; 2356 } 2357 2358 if (OldType != NewType && 2359 !OldType->isDependentType() && 2360 !NewType->isDependentType() && 2361 !Context.hasSameType(OldType, NewType)) { 2362 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2363 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 2364 << Kind << NewType << OldType; 2365 if (Old->getLocation().isValid()) 2366 notePreviousDefinition(Old, New->getLocation()); 2367 New->setInvalidDecl(); 2368 return true; 2369 } 2370 return false; 2371 } 2372 2373 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 2374 /// same name and scope as a previous declaration 'Old'. Figure out 2375 /// how to resolve this situation, merging decls or emitting 2376 /// diagnostics as appropriate. If there was an error, set New to be invalid. 2377 /// 2378 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 2379 LookupResult &OldDecls) { 2380 // If the new decl is known invalid already, don't bother doing any 2381 // merging checks. 2382 if (New->isInvalidDecl()) return; 2383 2384 // Allow multiple definitions for ObjC built-in typedefs. 2385 // FIXME: Verify the underlying types are equivalent! 2386 if (getLangOpts().ObjC) { 2387 const IdentifierInfo *TypeID = New->getIdentifier(); 2388 switch (TypeID->getLength()) { 2389 default: break; 2390 case 2: 2391 { 2392 if (!TypeID->isStr("id")) 2393 break; 2394 QualType T = New->getUnderlyingType(); 2395 if (!T->isPointerType()) 2396 break; 2397 if (!T->isVoidPointerType()) { 2398 QualType PT = T->castAs<PointerType>()->getPointeeType(); 2399 if (!PT->isStructureType()) 2400 break; 2401 } 2402 Context.setObjCIdRedefinitionType(T); 2403 // Install the built-in type for 'id', ignoring the current definition. 2404 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 2405 return; 2406 } 2407 case 5: 2408 if (!TypeID->isStr("Class")) 2409 break; 2410 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 2411 // Install the built-in type for 'Class', ignoring the current definition. 2412 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 2413 return; 2414 case 3: 2415 if (!TypeID->isStr("SEL")) 2416 break; 2417 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 2418 // Install the built-in type for 'SEL', ignoring the current definition. 2419 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 2420 return; 2421 } 2422 // Fall through - the typedef name was not a builtin type. 2423 } 2424 2425 // Verify the old decl was also a type. 2426 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 2427 if (!Old) { 2428 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2429 << New->getDeclName(); 2430 2431 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 2432 if (OldD->getLocation().isValid()) 2433 notePreviousDefinition(OldD, New->getLocation()); 2434 2435 return New->setInvalidDecl(); 2436 } 2437 2438 // If the old declaration is invalid, just give up here. 2439 if (Old->isInvalidDecl()) 2440 return New->setInvalidDecl(); 2441 2442 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2443 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2444 auto *NewTag = New->getAnonDeclWithTypedefName(); 2445 NamedDecl *Hidden = nullptr; 2446 if (OldTag && NewTag && 2447 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 2448 !hasVisibleDefinition(OldTag, &Hidden)) { 2449 // There is a definition of this tag, but it is not visible. Use it 2450 // instead of our tag. 2451 New->setTypeForDecl(OldTD->getTypeForDecl()); 2452 if (OldTD->isModed()) 2453 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 2454 OldTD->getUnderlyingType()); 2455 else 2456 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 2457 2458 // Make the old tag definition visible. 2459 makeMergedDefinitionVisible(Hidden); 2460 2461 // If this was an unscoped enumeration, yank all of its enumerators 2462 // out of the scope. 2463 if (isa<EnumDecl>(NewTag)) { 2464 Scope *EnumScope = getNonFieldDeclScope(S); 2465 for (auto *D : NewTag->decls()) { 2466 auto *ED = cast<EnumConstantDecl>(D); 2467 assert(EnumScope->isDeclScope(ED)); 2468 EnumScope->RemoveDecl(ED); 2469 IdResolver.RemoveDecl(ED); 2470 ED->getLexicalDeclContext()->removeDecl(ED); 2471 } 2472 } 2473 } 2474 } 2475 2476 // If the typedef types are not identical, reject them in all languages and 2477 // with any extensions enabled. 2478 if (isIncompatibleTypedef(Old, New)) 2479 return; 2480 2481 // The types match. Link up the redeclaration chain and merge attributes if 2482 // the old declaration was a typedef. 2483 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2484 New->setPreviousDecl(Typedef); 2485 mergeDeclAttributes(New, Old); 2486 } 2487 2488 if (getLangOpts().MicrosoftExt) 2489 return; 2490 2491 if (getLangOpts().CPlusPlus) { 2492 // C++ [dcl.typedef]p2: 2493 // In a given non-class scope, a typedef specifier can be used to 2494 // redefine the name of any type declared in that scope to refer 2495 // to the type to which it already refers. 2496 if (!isa<CXXRecordDecl>(CurContext)) 2497 return; 2498 2499 // C++0x [dcl.typedef]p4: 2500 // In a given class scope, a typedef specifier can be used to redefine 2501 // any class-name declared in that scope that is not also a typedef-name 2502 // to refer to the type to which it already refers. 2503 // 2504 // This wording came in via DR424, which was a correction to the 2505 // wording in DR56, which accidentally banned code like: 2506 // 2507 // struct S { 2508 // typedef struct A { } A; 2509 // }; 2510 // 2511 // in the C++03 standard. We implement the C++0x semantics, which 2512 // allow the above but disallow 2513 // 2514 // struct S { 2515 // typedef int I; 2516 // typedef int I; 2517 // }; 2518 // 2519 // since that was the intent of DR56. 2520 if (!isa<TypedefNameDecl>(Old)) 2521 return; 2522 2523 Diag(New->getLocation(), diag::err_redefinition) 2524 << New->getDeclName(); 2525 notePreviousDefinition(Old, New->getLocation()); 2526 return New->setInvalidDecl(); 2527 } 2528 2529 // Modules always permit redefinition of typedefs, as does C11. 2530 if (getLangOpts().Modules || getLangOpts().C11) 2531 return; 2532 2533 // If we have a redefinition of a typedef in C, emit a warning. This warning 2534 // is normally mapped to an error, but can be controlled with 2535 // -Wtypedef-redefinition. If either the original or the redefinition is 2536 // in a system header, don't emit this for compatibility with GCC. 2537 if (getDiagnostics().getSuppressSystemWarnings() && 2538 // Some standard types are defined implicitly in Clang (e.g. OpenCL). 2539 (Old->isImplicit() || 2540 Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2541 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2542 return; 2543 2544 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2545 << New->getDeclName(); 2546 notePreviousDefinition(Old, New->getLocation()); 2547 } 2548 2549 /// DeclhasAttr - returns true if decl Declaration already has the target 2550 /// attribute. 2551 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2552 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2553 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2554 for (const auto *i : D->attrs()) 2555 if (i->getKind() == A->getKind()) { 2556 if (Ann) { 2557 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2558 return true; 2559 continue; 2560 } 2561 // FIXME: Don't hardcode this check 2562 if (OA && isa<OwnershipAttr>(i)) 2563 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2564 return true; 2565 } 2566 2567 return false; 2568 } 2569 2570 static bool isAttributeTargetADefinition(Decl *D) { 2571 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2572 return VD->isThisDeclarationADefinition(); 2573 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2574 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2575 return true; 2576 } 2577 2578 /// Merge alignment attributes from \p Old to \p New, taking into account the 2579 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2580 /// 2581 /// \return \c true if any attributes were added to \p New. 2582 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2583 // Look for alignas attributes on Old, and pick out whichever attribute 2584 // specifies the strictest alignment requirement. 2585 AlignedAttr *OldAlignasAttr = nullptr; 2586 AlignedAttr *OldStrictestAlignAttr = nullptr; 2587 unsigned OldAlign = 0; 2588 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2589 // FIXME: We have no way of representing inherited dependent alignments 2590 // in a case like: 2591 // template<int A, int B> struct alignas(A) X; 2592 // template<int A, int B> struct alignas(B) X {}; 2593 // For now, we just ignore any alignas attributes which are not on the 2594 // definition in such a case. 2595 if (I->isAlignmentDependent()) 2596 return false; 2597 2598 if (I->isAlignas()) 2599 OldAlignasAttr = I; 2600 2601 unsigned Align = I->getAlignment(S.Context); 2602 if (Align > OldAlign) { 2603 OldAlign = Align; 2604 OldStrictestAlignAttr = I; 2605 } 2606 } 2607 2608 // Look for alignas attributes on New. 2609 AlignedAttr *NewAlignasAttr = nullptr; 2610 unsigned NewAlign = 0; 2611 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2612 if (I->isAlignmentDependent()) 2613 return false; 2614 2615 if (I->isAlignas()) 2616 NewAlignasAttr = I; 2617 2618 unsigned Align = I->getAlignment(S.Context); 2619 if (Align > NewAlign) 2620 NewAlign = Align; 2621 } 2622 2623 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2624 // Both declarations have 'alignas' attributes. We require them to match. 2625 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2626 // fall short. (If two declarations both have alignas, they must both match 2627 // every definition, and so must match each other if there is a definition.) 2628 2629 // If either declaration only contains 'alignas(0)' specifiers, then it 2630 // specifies the natural alignment for the type. 2631 if (OldAlign == 0 || NewAlign == 0) { 2632 QualType Ty; 2633 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2634 Ty = VD->getType(); 2635 else 2636 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2637 2638 if (OldAlign == 0) 2639 OldAlign = S.Context.getTypeAlign(Ty); 2640 if (NewAlign == 0) 2641 NewAlign = S.Context.getTypeAlign(Ty); 2642 } 2643 2644 if (OldAlign != NewAlign) { 2645 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2646 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2647 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2648 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2649 } 2650 } 2651 2652 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2653 // C++11 [dcl.align]p6: 2654 // if any declaration of an entity has an alignment-specifier, 2655 // every defining declaration of that entity shall specify an 2656 // equivalent alignment. 2657 // C11 6.7.5/7: 2658 // If the definition of an object does not have an alignment 2659 // specifier, any other declaration of that object shall also 2660 // have no alignment specifier. 2661 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2662 << OldAlignasAttr; 2663 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2664 << OldAlignasAttr; 2665 } 2666 2667 bool AnyAdded = false; 2668 2669 // Ensure we have an attribute representing the strictest alignment. 2670 if (OldAlign > NewAlign) { 2671 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2672 Clone->setInherited(true); 2673 New->addAttr(Clone); 2674 AnyAdded = true; 2675 } 2676 2677 // Ensure we have an alignas attribute if the old declaration had one. 2678 if (OldAlignasAttr && !NewAlignasAttr && 2679 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2680 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2681 Clone->setInherited(true); 2682 New->addAttr(Clone); 2683 AnyAdded = true; 2684 } 2685 2686 return AnyAdded; 2687 } 2688 2689 #define WANT_DECL_MERGE_LOGIC 2690 #include "clang/Sema/AttrParsedAttrImpl.inc" 2691 #undef WANT_DECL_MERGE_LOGIC 2692 2693 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2694 const InheritableAttr *Attr, 2695 Sema::AvailabilityMergeKind AMK) { 2696 // Diagnose any mutual exclusions between the attribute that we want to add 2697 // and attributes that already exist on the declaration. 2698 if (!DiagnoseMutualExclusions(S, D, Attr)) 2699 return false; 2700 2701 // This function copies an attribute Attr from a previous declaration to the 2702 // new declaration D if the new declaration doesn't itself have that attribute 2703 // yet or if that attribute allows duplicates. 2704 // If you're adding a new attribute that requires logic different from 2705 // "use explicit attribute on decl if present, else use attribute from 2706 // previous decl", for example if the attribute needs to be consistent 2707 // between redeclarations, you need to call a custom merge function here. 2708 InheritableAttr *NewAttr = nullptr; 2709 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2710 NewAttr = S.mergeAvailabilityAttr( 2711 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(), 2712 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(), 2713 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK, 2714 AA->getPriority()); 2715 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2716 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility()); 2717 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2718 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility()); 2719 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2720 NewAttr = S.mergeDLLImportAttr(D, *ImportA); 2721 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2722 NewAttr = S.mergeDLLExportAttr(D, *ExportA); 2723 else if (const auto *EA = dyn_cast<ErrorAttr>(Attr)) 2724 NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic()); 2725 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2726 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(), 2727 FA->getFirstArg()); 2728 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2729 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName()); 2730 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr)) 2731 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName()); 2732 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2733 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(), 2734 IA->getInheritanceModel()); 2735 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2736 NewAttr = S.mergeAlwaysInlineAttr(D, *AA, 2737 &S.Context.Idents.get(AA->getSpelling())); 2738 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2739 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2740 isa<CUDAGlobalAttr>(Attr))) { 2741 // CUDA target attributes are part of function signature for 2742 // overloading purposes and must not be merged. 2743 return false; 2744 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2745 NewAttr = S.mergeMinSizeAttr(D, *MA); 2746 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr)) 2747 NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName()); 2748 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2749 NewAttr = S.mergeOptimizeNoneAttr(D, *OA); 2750 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2751 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA); 2752 else if (isa<AlignedAttr>(Attr)) 2753 // AlignedAttrs are handled separately, because we need to handle all 2754 // such attributes on a declaration at the same time. 2755 NewAttr = nullptr; 2756 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2757 (AMK == Sema::AMK_Override || 2758 AMK == Sema::AMK_ProtocolImplementation || 2759 AMK == Sema::AMK_OptionalProtocolImplementation)) 2760 NewAttr = nullptr; 2761 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2762 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl()); 2763 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr)) 2764 NewAttr = S.mergeImportModuleAttr(D, *IMA); 2765 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr)) 2766 NewAttr = S.mergeImportNameAttr(D, *INA); 2767 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr)) 2768 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA); 2769 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr)) 2770 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA); 2771 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr)) 2772 NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA); 2773 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr)) 2774 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2775 2776 if (NewAttr) { 2777 NewAttr->setInherited(true); 2778 D->addAttr(NewAttr); 2779 if (isa<MSInheritanceAttr>(NewAttr)) 2780 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2781 return true; 2782 } 2783 2784 return false; 2785 } 2786 2787 static const NamedDecl *getDefinition(const Decl *D) { 2788 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2789 return TD->getDefinition(); 2790 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2791 const VarDecl *Def = VD->getDefinition(); 2792 if (Def) 2793 return Def; 2794 return VD->getActingDefinition(); 2795 } 2796 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2797 const FunctionDecl *Def = nullptr; 2798 if (FD->isDefined(Def, true)) 2799 return Def; 2800 } 2801 return nullptr; 2802 } 2803 2804 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2805 for (const auto *Attribute : D->attrs()) 2806 if (Attribute->getKind() == Kind) 2807 return true; 2808 return false; 2809 } 2810 2811 /// checkNewAttributesAfterDef - If we already have a definition, check that 2812 /// there are no new attributes in this declaration. 2813 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2814 if (!New->hasAttrs()) 2815 return; 2816 2817 const NamedDecl *Def = getDefinition(Old); 2818 if (!Def || Def == New) 2819 return; 2820 2821 AttrVec &NewAttributes = New->getAttrs(); 2822 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2823 const Attr *NewAttribute = NewAttributes[I]; 2824 2825 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 2826 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2827 Sema::SkipBodyInfo SkipBody; 2828 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2829 2830 // If we're skipping this definition, drop the "alias" attribute. 2831 if (SkipBody.ShouldSkip) { 2832 NewAttributes.erase(NewAttributes.begin() + I); 2833 --E; 2834 continue; 2835 } 2836 } else { 2837 VarDecl *VD = cast<VarDecl>(New); 2838 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2839 VarDecl::TentativeDefinition 2840 ? diag::err_alias_after_tentative 2841 : diag::err_redefinition; 2842 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2843 if (Diag == diag::err_redefinition) 2844 S.notePreviousDefinition(Def, VD->getLocation()); 2845 else 2846 S.Diag(Def->getLocation(), diag::note_previous_definition); 2847 VD->setInvalidDecl(); 2848 } 2849 ++I; 2850 continue; 2851 } 2852 2853 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2854 // Tentative definitions are only interesting for the alias check above. 2855 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2856 ++I; 2857 continue; 2858 } 2859 } 2860 2861 if (hasAttribute(Def, NewAttribute->getKind())) { 2862 ++I; 2863 continue; // regular attr merging will take care of validating this. 2864 } 2865 2866 if (isa<C11NoReturnAttr>(NewAttribute)) { 2867 // C's _Noreturn is allowed to be added to a function after it is defined. 2868 ++I; 2869 continue; 2870 } else if (isa<UuidAttr>(NewAttribute)) { 2871 // msvc will allow a subsequent definition to add an uuid to a class 2872 ++I; 2873 continue; 2874 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2875 if (AA->isAlignas()) { 2876 // C++11 [dcl.align]p6: 2877 // if any declaration of an entity has an alignment-specifier, 2878 // every defining declaration of that entity shall specify an 2879 // equivalent alignment. 2880 // C11 6.7.5/7: 2881 // If the definition of an object does not have an alignment 2882 // specifier, any other declaration of that object shall also 2883 // have no alignment specifier. 2884 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2885 << AA; 2886 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2887 << AA; 2888 NewAttributes.erase(NewAttributes.begin() + I); 2889 --E; 2890 continue; 2891 } 2892 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) { 2893 // If there is a C definition followed by a redeclaration with this 2894 // attribute then there are two different definitions. In C++, prefer the 2895 // standard diagnostics. 2896 if (!S.getLangOpts().CPlusPlus) { 2897 S.Diag(NewAttribute->getLocation(), 2898 diag::err_loader_uninitialized_redeclaration); 2899 S.Diag(Def->getLocation(), diag::note_previous_definition); 2900 NewAttributes.erase(NewAttributes.begin() + I); 2901 --E; 2902 continue; 2903 } 2904 } else if (isa<SelectAnyAttr>(NewAttribute) && 2905 cast<VarDecl>(New)->isInline() && 2906 !cast<VarDecl>(New)->isInlineSpecified()) { 2907 // Don't warn about applying selectany to implicitly inline variables. 2908 // Older compilers and language modes would require the use of selectany 2909 // to make such variables inline, and it would have no effect if we 2910 // honored it. 2911 ++I; 2912 continue; 2913 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) { 2914 // We allow to add OMP[Begin]DeclareVariantAttr to be added to 2915 // declarations after defintions. 2916 ++I; 2917 continue; 2918 } 2919 2920 S.Diag(NewAttribute->getLocation(), 2921 diag::warn_attribute_precede_definition); 2922 S.Diag(Def->getLocation(), diag::note_previous_definition); 2923 NewAttributes.erase(NewAttributes.begin() + I); 2924 --E; 2925 } 2926 } 2927 2928 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, 2929 const ConstInitAttr *CIAttr, 2930 bool AttrBeforeInit) { 2931 SourceLocation InsertLoc = InitDecl->getInnerLocStart(); 2932 2933 // Figure out a good way to write this specifier on the old declaration. 2934 // FIXME: We should just use the spelling of CIAttr, but we don't preserve 2935 // enough of the attribute list spelling information to extract that without 2936 // heroics. 2937 std::string SuitableSpelling; 2938 if (S.getLangOpts().CPlusPlus20) 2939 SuitableSpelling = std::string( 2940 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit})); 2941 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2942 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2943 InsertLoc, {tok::l_square, tok::l_square, 2944 S.PP.getIdentifierInfo("clang"), tok::coloncolon, 2945 S.PP.getIdentifierInfo("require_constant_initialization"), 2946 tok::r_square, tok::r_square})); 2947 if (SuitableSpelling.empty()) 2948 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2949 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren, 2950 S.PP.getIdentifierInfo("require_constant_initialization"), 2951 tok::r_paren, tok::r_paren})); 2952 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20) 2953 SuitableSpelling = "constinit"; 2954 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2955 SuitableSpelling = "[[clang::require_constant_initialization]]"; 2956 if (SuitableSpelling.empty()) 2957 SuitableSpelling = "__attribute__((require_constant_initialization))"; 2958 SuitableSpelling += " "; 2959 2960 if (AttrBeforeInit) { 2961 // extern constinit int a; 2962 // int a = 0; // error (missing 'constinit'), accepted as extension 2963 assert(CIAttr->isConstinit() && "should not diagnose this for attribute"); 2964 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing) 2965 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 2966 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here); 2967 } else { 2968 // int a = 0; 2969 // constinit extern int a; // error (missing 'constinit') 2970 S.Diag(CIAttr->getLocation(), 2971 CIAttr->isConstinit() ? diag::err_constinit_added_too_late 2972 : diag::warn_require_const_init_added_too_late) 2973 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation())); 2974 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here) 2975 << CIAttr->isConstinit() 2976 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 2977 } 2978 } 2979 2980 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2981 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2982 AvailabilityMergeKind AMK) { 2983 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2984 UsedAttr *NewAttr = OldAttr->clone(Context); 2985 NewAttr->setInherited(true); 2986 New->addAttr(NewAttr); 2987 } 2988 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) { 2989 RetainAttr *NewAttr = OldAttr->clone(Context); 2990 NewAttr->setInherited(true); 2991 New->addAttr(NewAttr); 2992 } 2993 2994 if (!Old->hasAttrs() && !New->hasAttrs()) 2995 return; 2996 2997 // [dcl.constinit]p1: 2998 // If the [constinit] specifier is applied to any declaration of a 2999 // variable, it shall be applied to the initializing declaration. 3000 const auto *OldConstInit = Old->getAttr<ConstInitAttr>(); 3001 const auto *NewConstInit = New->getAttr<ConstInitAttr>(); 3002 if (bool(OldConstInit) != bool(NewConstInit)) { 3003 const auto *OldVD = cast<VarDecl>(Old); 3004 auto *NewVD = cast<VarDecl>(New); 3005 3006 // Find the initializing declaration. Note that we might not have linked 3007 // the new declaration into the redeclaration chain yet. 3008 const VarDecl *InitDecl = OldVD->getInitializingDeclaration(); 3009 if (!InitDecl && 3010 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition())) 3011 InitDecl = NewVD; 3012 3013 if (InitDecl == NewVD) { 3014 // This is the initializing declaration. If it would inherit 'constinit', 3015 // that's ill-formed. (Note that we do not apply this to the attribute 3016 // form). 3017 if (OldConstInit && OldConstInit->isConstinit()) 3018 diagnoseMissingConstinit(*this, NewVD, OldConstInit, 3019 /*AttrBeforeInit=*/true); 3020 } else if (NewConstInit) { 3021 // This is the first time we've been told that this declaration should 3022 // have a constant initializer. If we already saw the initializing 3023 // declaration, this is too late. 3024 if (InitDecl && InitDecl != NewVD) { 3025 diagnoseMissingConstinit(*this, InitDecl, NewConstInit, 3026 /*AttrBeforeInit=*/false); 3027 NewVD->dropAttr<ConstInitAttr>(); 3028 } 3029 } 3030 } 3031 3032 // Attributes declared post-definition are currently ignored. 3033 checkNewAttributesAfterDef(*this, New, Old); 3034 3035 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 3036 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 3037 if (!OldA->isEquivalent(NewA)) { 3038 // This redeclaration changes __asm__ label. 3039 Diag(New->getLocation(), diag::err_different_asm_label); 3040 Diag(OldA->getLocation(), diag::note_previous_declaration); 3041 } 3042 } else if (Old->isUsed()) { 3043 // This redeclaration adds an __asm__ label to a declaration that has 3044 // already been ODR-used. 3045 Diag(New->getLocation(), diag::err_late_asm_label_name) 3046 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 3047 } 3048 } 3049 3050 // Re-declaration cannot add abi_tag's. 3051 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 3052 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 3053 for (const auto &NewTag : NewAbiTagAttr->tags()) { 3054 if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) { 3055 Diag(NewAbiTagAttr->getLocation(), 3056 diag::err_new_abi_tag_on_redeclaration) 3057 << NewTag; 3058 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 3059 } 3060 } 3061 } else { 3062 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 3063 Diag(Old->getLocation(), diag::note_previous_declaration); 3064 } 3065 } 3066 3067 // This redeclaration adds a section attribute. 3068 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { 3069 if (auto *VD = dyn_cast<VarDecl>(New)) { 3070 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) { 3071 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration); 3072 Diag(Old->getLocation(), diag::note_previous_declaration); 3073 } 3074 } 3075 } 3076 3077 // Redeclaration adds code-seg attribute. 3078 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 3079 if (NewCSA && !Old->hasAttr<CodeSegAttr>() && 3080 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) { 3081 Diag(New->getLocation(), diag::warn_mismatched_section) 3082 << 0 /*codeseg*/; 3083 Diag(Old->getLocation(), diag::note_previous_declaration); 3084 } 3085 3086 if (!Old->hasAttrs()) 3087 return; 3088 3089 bool foundAny = New->hasAttrs(); 3090 3091 // Ensure that any moving of objects within the allocated map is done before 3092 // we process them. 3093 if (!foundAny) New->setAttrs(AttrVec()); 3094 3095 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 3096 // Ignore deprecated/unavailable/availability attributes if requested. 3097 AvailabilityMergeKind LocalAMK = AMK_None; 3098 if (isa<DeprecatedAttr>(I) || 3099 isa<UnavailableAttr>(I) || 3100 isa<AvailabilityAttr>(I)) { 3101 switch (AMK) { 3102 case AMK_None: 3103 continue; 3104 3105 case AMK_Redeclaration: 3106 case AMK_Override: 3107 case AMK_ProtocolImplementation: 3108 case AMK_OptionalProtocolImplementation: 3109 LocalAMK = AMK; 3110 break; 3111 } 3112 } 3113 3114 // Already handled. 3115 if (isa<UsedAttr>(I) || isa<RetainAttr>(I)) 3116 continue; 3117 3118 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 3119 foundAny = true; 3120 } 3121 3122 if (mergeAlignedAttrs(*this, New, Old)) 3123 foundAny = true; 3124 3125 if (!foundAny) New->dropAttrs(); 3126 } 3127 3128 /// mergeParamDeclAttributes - Copy attributes from the old parameter 3129 /// to the new one. 3130 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 3131 const ParmVarDecl *oldDecl, 3132 Sema &S) { 3133 // C++11 [dcl.attr.depend]p2: 3134 // The first declaration of a function shall specify the 3135 // carries_dependency attribute for its declarator-id if any declaration 3136 // of the function specifies the carries_dependency attribute. 3137 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 3138 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 3139 S.Diag(CDA->getLocation(), 3140 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 3141 // Find the first declaration of the parameter. 3142 // FIXME: Should we build redeclaration chains for function parameters? 3143 const FunctionDecl *FirstFD = 3144 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 3145 const ParmVarDecl *FirstVD = 3146 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 3147 S.Diag(FirstVD->getLocation(), 3148 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 3149 } 3150 3151 if (!oldDecl->hasAttrs()) 3152 return; 3153 3154 bool foundAny = newDecl->hasAttrs(); 3155 3156 // Ensure that any moving of objects within the allocated map is 3157 // done before we process them. 3158 if (!foundAny) newDecl->setAttrs(AttrVec()); 3159 3160 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 3161 if (!DeclHasAttr(newDecl, I)) { 3162 InheritableAttr *newAttr = 3163 cast<InheritableParamAttr>(I->clone(S.Context)); 3164 newAttr->setInherited(true); 3165 newDecl->addAttr(newAttr); 3166 foundAny = true; 3167 } 3168 } 3169 3170 if (!foundAny) newDecl->dropAttrs(); 3171 } 3172 3173 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 3174 const ParmVarDecl *OldParam, 3175 Sema &S) { 3176 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 3177 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 3178 if (*Oldnullability != *Newnullability) { 3179 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 3180 << DiagNullabilityKind( 3181 *Newnullability, 3182 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3183 != 0)) 3184 << DiagNullabilityKind( 3185 *Oldnullability, 3186 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3187 != 0)); 3188 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 3189 } 3190 } else { 3191 QualType NewT = NewParam->getType(); 3192 NewT = S.Context.getAttributedType( 3193 AttributedType::getNullabilityAttrKind(*Oldnullability), 3194 NewT, NewT); 3195 NewParam->setType(NewT); 3196 } 3197 } 3198 } 3199 3200 namespace { 3201 3202 /// Used in MergeFunctionDecl to keep track of function parameters in 3203 /// C. 3204 struct GNUCompatibleParamWarning { 3205 ParmVarDecl *OldParm; 3206 ParmVarDecl *NewParm; 3207 QualType PromotedType; 3208 }; 3209 3210 } // end anonymous namespace 3211 3212 // Determine whether the previous declaration was a definition, implicit 3213 // declaration, or a declaration. 3214 template <typename T> 3215 static std::pair<diag::kind, SourceLocation> 3216 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 3217 diag::kind PrevDiag; 3218 SourceLocation OldLocation = Old->getLocation(); 3219 if (Old->isThisDeclarationADefinition()) 3220 PrevDiag = diag::note_previous_definition; 3221 else if (Old->isImplicit()) { 3222 PrevDiag = diag::note_previous_implicit_declaration; 3223 if (OldLocation.isInvalid()) 3224 OldLocation = New->getLocation(); 3225 } else 3226 PrevDiag = diag::note_previous_declaration; 3227 return std::make_pair(PrevDiag, OldLocation); 3228 } 3229 3230 /// canRedefineFunction - checks if a function can be redefined. Currently, 3231 /// only extern inline functions can be redefined, and even then only in 3232 /// GNU89 mode. 3233 static bool canRedefineFunction(const FunctionDecl *FD, 3234 const LangOptions& LangOpts) { 3235 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 3236 !LangOpts.CPlusPlus && 3237 FD->isInlineSpecified() && 3238 FD->getStorageClass() == SC_Extern); 3239 } 3240 3241 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 3242 const AttributedType *AT = T->getAs<AttributedType>(); 3243 while (AT && !AT->isCallingConv()) 3244 AT = AT->getModifiedType()->getAs<AttributedType>(); 3245 return AT; 3246 } 3247 3248 template <typename T> 3249 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 3250 const DeclContext *DC = Old->getDeclContext(); 3251 if (DC->isRecord()) 3252 return false; 3253 3254 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 3255 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 3256 return true; 3257 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 3258 return true; 3259 return false; 3260 } 3261 3262 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 3263 static bool isExternC(VarTemplateDecl *) { return false; } 3264 static bool isExternC(FunctionTemplateDecl *) { return false; } 3265 3266 /// Check whether a redeclaration of an entity introduced by a 3267 /// using-declaration is valid, given that we know it's not an overload 3268 /// (nor a hidden tag declaration). 3269 template<typename ExpectedDecl> 3270 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 3271 ExpectedDecl *New) { 3272 // C++11 [basic.scope.declarative]p4: 3273 // Given a set of declarations in a single declarative region, each of 3274 // which specifies the same unqualified name, 3275 // -- they shall all refer to the same entity, or all refer to functions 3276 // and function templates; or 3277 // -- exactly one declaration shall declare a class name or enumeration 3278 // name that is not a typedef name and the other declarations shall all 3279 // refer to the same variable or enumerator, or all refer to functions 3280 // and function templates; in this case the class name or enumeration 3281 // name is hidden (3.3.10). 3282 3283 // C++11 [namespace.udecl]p14: 3284 // If a function declaration in namespace scope or block scope has the 3285 // same name and the same parameter-type-list as a function introduced 3286 // by a using-declaration, and the declarations do not declare the same 3287 // function, the program is ill-formed. 3288 3289 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 3290 if (Old && 3291 !Old->getDeclContext()->getRedeclContext()->Equals( 3292 New->getDeclContext()->getRedeclContext()) && 3293 !(isExternC(Old) && isExternC(New))) 3294 Old = nullptr; 3295 3296 if (!Old) { 3297 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 3298 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 3299 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0; 3300 return true; 3301 } 3302 return false; 3303 } 3304 3305 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 3306 const FunctionDecl *B) { 3307 assert(A->getNumParams() == B->getNumParams()); 3308 3309 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 3310 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 3311 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 3312 if (AttrA == AttrB) 3313 return true; 3314 return AttrA && AttrB && AttrA->getType() == AttrB->getType() && 3315 AttrA->isDynamic() == AttrB->isDynamic(); 3316 }; 3317 3318 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 3319 } 3320 3321 /// If necessary, adjust the semantic declaration context for a qualified 3322 /// declaration to name the correct inline namespace within the qualifier. 3323 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, 3324 DeclaratorDecl *OldD) { 3325 // The only case where we need to update the DeclContext is when 3326 // redeclaration lookup for a qualified name finds a declaration 3327 // in an inline namespace within the context named by the qualifier: 3328 // 3329 // inline namespace N { int f(); } 3330 // int ::f(); // Sema DC needs adjusting from :: to N::. 3331 // 3332 // For unqualified declarations, the semantic context *can* change 3333 // along the redeclaration chain (for local extern declarations, 3334 // extern "C" declarations, and friend declarations in particular). 3335 if (!NewD->getQualifier()) 3336 return; 3337 3338 // NewD is probably already in the right context. 3339 auto *NamedDC = NewD->getDeclContext()->getRedeclContext(); 3340 auto *SemaDC = OldD->getDeclContext()->getRedeclContext(); 3341 if (NamedDC->Equals(SemaDC)) 3342 return; 3343 3344 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || 3345 NewD->isInvalidDecl() || OldD->isInvalidDecl()) && 3346 "unexpected context for redeclaration"); 3347 3348 auto *LexDC = NewD->getLexicalDeclContext(); 3349 auto FixSemaDC = [=](NamedDecl *D) { 3350 if (!D) 3351 return; 3352 D->setDeclContext(SemaDC); 3353 D->setLexicalDeclContext(LexDC); 3354 }; 3355 3356 FixSemaDC(NewD); 3357 if (auto *FD = dyn_cast<FunctionDecl>(NewD)) 3358 FixSemaDC(FD->getDescribedFunctionTemplate()); 3359 else if (auto *VD = dyn_cast<VarDecl>(NewD)) 3360 FixSemaDC(VD->getDescribedVarTemplate()); 3361 } 3362 3363 /// MergeFunctionDecl - We just parsed a function 'New' from 3364 /// declarator D which has the same name and scope as a previous 3365 /// declaration 'Old'. Figure out how to resolve this situation, 3366 /// merging decls or emitting diagnostics as appropriate. 3367 /// 3368 /// In C++, New and Old must be declarations that are not 3369 /// overloaded. Use IsOverload to determine whether New and Old are 3370 /// overloaded, and to select the Old declaration that New should be 3371 /// merged with. 3372 /// 3373 /// Returns true if there was an error, false otherwise. 3374 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 3375 Scope *S, bool MergeTypeWithOld) { 3376 // Verify the old decl was also a function. 3377 FunctionDecl *Old = OldD->getAsFunction(); 3378 if (!Old) { 3379 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 3380 if (New->getFriendObjectKind()) { 3381 Diag(New->getLocation(), diag::err_using_decl_friend); 3382 Diag(Shadow->getTargetDecl()->getLocation(), 3383 diag::note_using_decl_target); 3384 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) 3385 << 0; 3386 return true; 3387 } 3388 3389 // Check whether the two declarations might declare the same function or 3390 // function template. 3391 if (FunctionTemplateDecl *NewTemplate = 3392 New->getDescribedFunctionTemplate()) { 3393 if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow, 3394 NewTemplate)) 3395 return true; 3396 OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl()) 3397 ->getAsFunction(); 3398 } else { 3399 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 3400 return true; 3401 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 3402 } 3403 } else { 3404 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3405 << New->getDeclName(); 3406 notePreviousDefinition(OldD, New->getLocation()); 3407 return true; 3408 } 3409 } 3410 3411 // If the old declaration was found in an inline namespace and the new 3412 // declaration was qualified, update the DeclContext to match. 3413 adjustDeclContextForDeclaratorDecl(New, Old); 3414 3415 // If the old declaration is invalid, just give up here. 3416 if (Old->isInvalidDecl()) 3417 return true; 3418 3419 // Disallow redeclaration of some builtins. 3420 if (!getASTContext().canBuiltinBeRedeclared(Old)) { 3421 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName(); 3422 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 3423 << Old << Old->getType(); 3424 return true; 3425 } 3426 3427 diag::kind PrevDiag; 3428 SourceLocation OldLocation; 3429 std::tie(PrevDiag, OldLocation) = 3430 getNoteDiagForInvalidRedeclaration(Old, New); 3431 3432 // Don't complain about this if we're in GNU89 mode and the old function 3433 // is an extern inline function. 3434 // Don't complain about specializations. They are not supposed to have 3435 // storage classes. 3436 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 3437 New->getStorageClass() == SC_Static && 3438 Old->hasExternalFormalLinkage() && 3439 !New->getTemplateSpecializationInfo() && 3440 !canRedefineFunction(Old, getLangOpts())) { 3441 if (getLangOpts().MicrosoftExt) { 3442 Diag(New->getLocation(), diag::ext_static_non_static) << New; 3443 Diag(OldLocation, PrevDiag); 3444 } else { 3445 Diag(New->getLocation(), diag::err_static_non_static) << New; 3446 Diag(OldLocation, PrevDiag); 3447 return true; 3448 } 3449 } 3450 3451 if (const auto *ILA = New->getAttr<InternalLinkageAttr>()) 3452 if (!Old->hasAttr<InternalLinkageAttr>()) { 3453 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl) 3454 << ILA; 3455 Diag(Old->getLocation(), diag::note_previous_declaration); 3456 New->dropAttr<InternalLinkageAttr>(); 3457 } 3458 3459 if (auto *EA = New->getAttr<ErrorAttr>()) { 3460 if (!Old->hasAttr<ErrorAttr>()) { 3461 Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA; 3462 Diag(Old->getLocation(), diag::note_previous_declaration); 3463 New->dropAttr<ErrorAttr>(); 3464 } 3465 } 3466 3467 if (CheckRedeclarationInModule(New, Old)) 3468 return true; 3469 3470 if (!getLangOpts().CPlusPlus) { 3471 bool OldOvl = Old->hasAttr<OverloadableAttr>(); 3472 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { 3473 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) 3474 << New << OldOvl; 3475 3476 // Try our best to find a decl that actually has the overloadable 3477 // attribute for the note. In most cases (e.g. programs with only one 3478 // broken declaration/definition), this won't matter. 3479 // 3480 // FIXME: We could do this if we juggled some extra state in 3481 // OverloadableAttr, rather than just removing it. 3482 const Decl *DiagOld = Old; 3483 if (OldOvl) { 3484 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { 3485 const auto *A = D->getAttr<OverloadableAttr>(); 3486 return A && !A->isImplicit(); 3487 }); 3488 // If we've implicitly added *all* of the overloadable attrs to this 3489 // chain, emitting a "previous redecl" note is pointless. 3490 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; 3491 } 3492 3493 if (DiagOld) 3494 Diag(DiagOld->getLocation(), 3495 diag::note_attribute_overloadable_prev_overload) 3496 << OldOvl; 3497 3498 if (OldOvl) 3499 New->addAttr(OverloadableAttr::CreateImplicit(Context)); 3500 else 3501 New->dropAttr<OverloadableAttr>(); 3502 } 3503 } 3504 3505 // If a function is first declared with a calling convention, but is later 3506 // declared or defined without one, all following decls assume the calling 3507 // convention of the first. 3508 // 3509 // It's OK if a function is first declared without a calling convention, 3510 // but is later declared or defined with the default calling convention. 3511 // 3512 // To test if either decl has an explicit calling convention, we look for 3513 // AttributedType sugar nodes on the type as written. If they are missing or 3514 // were canonicalized away, we assume the calling convention was implicit. 3515 // 3516 // Note also that we DO NOT return at this point, because we still have 3517 // other tests to run. 3518 QualType OldQType = Context.getCanonicalType(Old->getType()); 3519 QualType NewQType = Context.getCanonicalType(New->getType()); 3520 const FunctionType *OldType = cast<FunctionType>(OldQType); 3521 const FunctionType *NewType = cast<FunctionType>(NewQType); 3522 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 3523 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 3524 bool RequiresAdjustment = false; 3525 3526 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 3527 FunctionDecl *First = Old->getFirstDecl(); 3528 const FunctionType *FT = 3529 First->getType().getCanonicalType()->castAs<FunctionType>(); 3530 FunctionType::ExtInfo FI = FT->getExtInfo(); 3531 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 3532 if (!NewCCExplicit) { 3533 // Inherit the CC from the previous declaration if it was specified 3534 // there but not here. 3535 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3536 RequiresAdjustment = true; 3537 } else if (Old->getBuiltinID()) { 3538 // Builtin attribute isn't propagated to the new one yet at this point, 3539 // so we check if the old one is a builtin. 3540 3541 // Calling Conventions on a Builtin aren't really useful and setting a 3542 // default calling convention and cdecl'ing some builtin redeclarations is 3543 // common, so warn and ignore the calling convention on the redeclaration. 3544 Diag(New->getLocation(), diag::warn_cconv_unsupported) 3545 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3546 << (int)CallingConventionIgnoredReason::BuiltinFunction; 3547 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3548 RequiresAdjustment = true; 3549 } else { 3550 // Calling conventions aren't compatible, so complain. 3551 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 3552 Diag(New->getLocation(), diag::err_cconv_change) 3553 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3554 << !FirstCCExplicit 3555 << (!FirstCCExplicit ? "" : 3556 FunctionType::getNameForCallConv(FI.getCC())); 3557 3558 // Put the note on the first decl, since it is the one that matters. 3559 Diag(First->getLocation(), diag::note_previous_declaration); 3560 return true; 3561 } 3562 } 3563 3564 // FIXME: diagnose the other way around? 3565 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 3566 NewTypeInfo = NewTypeInfo.withNoReturn(true); 3567 RequiresAdjustment = true; 3568 } 3569 3570 // Merge regparm attribute. 3571 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 3572 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 3573 if (NewTypeInfo.getHasRegParm()) { 3574 Diag(New->getLocation(), diag::err_regparm_mismatch) 3575 << NewType->getRegParmType() 3576 << OldType->getRegParmType(); 3577 Diag(OldLocation, diag::note_previous_declaration); 3578 return true; 3579 } 3580 3581 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 3582 RequiresAdjustment = true; 3583 } 3584 3585 // Merge ns_returns_retained attribute. 3586 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 3587 if (NewTypeInfo.getProducesResult()) { 3588 Diag(New->getLocation(), diag::err_function_attribute_mismatch) 3589 << "'ns_returns_retained'"; 3590 Diag(OldLocation, diag::note_previous_declaration); 3591 return true; 3592 } 3593 3594 NewTypeInfo = NewTypeInfo.withProducesResult(true); 3595 RequiresAdjustment = true; 3596 } 3597 3598 if (OldTypeInfo.getNoCallerSavedRegs() != 3599 NewTypeInfo.getNoCallerSavedRegs()) { 3600 if (NewTypeInfo.getNoCallerSavedRegs()) { 3601 AnyX86NoCallerSavedRegistersAttr *Attr = 3602 New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); 3603 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; 3604 Diag(OldLocation, diag::note_previous_declaration); 3605 return true; 3606 } 3607 3608 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); 3609 RequiresAdjustment = true; 3610 } 3611 3612 if (RequiresAdjustment) { 3613 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 3614 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 3615 New->setType(QualType(AdjustedType, 0)); 3616 NewQType = Context.getCanonicalType(New->getType()); 3617 } 3618 3619 // If this redeclaration makes the function inline, we may need to add it to 3620 // UndefinedButUsed. 3621 if (!Old->isInlined() && New->isInlined() && 3622 !New->hasAttr<GNUInlineAttr>() && 3623 !getLangOpts().GNUInline && 3624 Old->isUsed(false) && 3625 !Old->isDefined() && !New->isThisDeclarationADefinition()) 3626 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3627 SourceLocation())); 3628 3629 // If this redeclaration makes it newly gnu_inline, we don't want to warn 3630 // about it. 3631 if (New->hasAttr<GNUInlineAttr>() && 3632 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 3633 UndefinedButUsed.erase(Old->getCanonicalDecl()); 3634 } 3635 3636 // If pass_object_size params don't match up perfectly, this isn't a valid 3637 // redeclaration. 3638 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 3639 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 3640 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 3641 << New->getDeclName(); 3642 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3643 return true; 3644 } 3645 3646 if (getLangOpts().CPlusPlus) { 3647 // C++1z [over.load]p2 3648 // Certain function declarations cannot be overloaded: 3649 // -- Function declarations that differ only in the return type, 3650 // the exception specification, or both cannot be overloaded. 3651 3652 // Check the exception specifications match. This may recompute the type of 3653 // both Old and New if it resolved exception specifications, so grab the 3654 // types again after this. Because this updates the type, we do this before 3655 // any of the other checks below, which may update the "de facto" NewQType 3656 // but do not necessarily update the type of New. 3657 if (CheckEquivalentExceptionSpec(Old, New)) 3658 return true; 3659 OldQType = Context.getCanonicalType(Old->getType()); 3660 NewQType = Context.getCanonicalType(New->getType()); 3661 3662 // Go back to the type source info to compare the declared return types, 3663 // per C++1y [dcl.type.auto]p13: 3664 // Redeclarations or specializations of a function or function template 3665 // with a declared return type that uses a placeholder type shall also 3666 // use that placeholder, not a deduced type. 3667 QualType OldDeclaredReturnType = Old->getDeclaredReturnType(); 3668 QualType NewDeclaredReturnType = New->getDeclaredReturnType(); 3669 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 3670 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType, 3671 OldDeclaredReturnType)) { 3672 QualType ResQT; 3673 if (NewDeclaredReturnType->isObjCObjectPointerType() && 3674 OldDeclaredReturnType->isObjCObjectPointerType()) 3675 // FIXME: This does the wrong thing for a deduced return type. 3676 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 3677 if (ResQT.isNull()) { 3678 if (New->isCXXClassMember() && New->isOutOfLine()) 3679 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 3680 << New << New->getReturnTypeSourceRange(); 3681 else 3682 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 3683 << New->getReturnTypeSourceRange(); 3684 Diag(OldLocation, PrevDiag) << Old << Old->getType() 3685 << Old->getReturnTypeSourceRange(); 3686 return true; 3687 } 3688 else 3689 NewQType = ResQT; 3690 } 3691 3692 QualType OldReturnType = OldType->getReturnType(); 3693 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 3694 if (OldReturnType != NewReturnType) { 3695 // If this function has a deduced return type and has already been 3696 // defined, copy the deduced value from the old declaration. 3697 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 3698 if (OldAT && OldAT->isDeduced()) { 3699 QualType DT = OldAT->getDeducedType(); 3700 if (DT.isNull()) { 3701 New->setType(SubstAutoTypeDependent(New->getType())); 3702 NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType)); 3703 } else { 3704 New->setType(SubstAutoType(New->getType(), DT)); 3705 NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT)); 3706 } 3707 } 3708 } 3709 3710 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 3711 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 3712 if (OldMethod && NewMethod) { 3713 // Preserve triviality. 3714 NewMethod->setTrivial(OldMethod->isTrivial()); 3715 3716 // MSVC allows explicit template specialization at class scope: 3717 // 2 CXXMethodDecls referring to the same function will be injected. 3718 // We don't want a redeclaration error. 3719 bool IsClassScopeExplicitSpecialization = 3720 OldMethod->isFunctionTemplateSpecialization() && 3721 NewMethod->isFunctionTemplateSpecialization(); 3722 bool isFriend = NewMethod->getFriendObjectKind(); 3723 3724 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 3725 !IsClassScopeExplicitSpecialization) { 3726 // -- Member function declarations with the same name and the 3727 // same parameter types cannot be overloaded if any of them 3728 // is a static member function declaration. 3729 if (OldMethod->isStatic() != NewMethod->isStatic()) { 3730 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 3731 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3732 return true; 3733 } 3734 3735 // C++ [class.mem]p1: 3736 // [...] A member shall not be declared twice in the 3737 // member-specification, except that a nested class or member 3738 // class template can be declared and then later defined. 3739 if (!inTemplateInstantiation()) { 3740 unsigned NewDiag; 3741 if (isa<CXXConstructorDecl>(OldMethod)) 3742 NewDiag = diag::err_constructor_redeclared; 3743 else if (isa<CXXDestructorDecl>(NewMethod)) 3744 NewDiag = diag::err_destructor_redeclared; 3745 else if (isa<CXXConversionDecl>(NewMethod)) 3746 NewDiag = diag::err_conv_function_redeclared; 3747 else 3748 NewDiag = diag::err_member_redeclared; 3749 3750 Diag(New->getLocation(), NewDiag); 3751 } else { 3752 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 3753 << New << New->getType(); 3754 } 3755 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3756 return true; 3757 3758 // Complain if this is an explicit declaration of a special 3759 // member that was initially declared implicitly. 3760 // 3761 // As an exception, it's okay to befriend such methods in order 3762 // to permit the implicit constructor/destructor/operator calls. 3763 } else if (OldMethod->isImplicit()) { 3764 if (isFriend) { 3765 NewMethod->setImplicit(); 3766 } else { 3767 Diag(NewMethod->getLocation(), 3768 diag::err_definition_of_implicitly_declared_member) 3769 << New << getSpecialMember(OldMethod); 3770 return true; 3771 } 3772 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 3773 Diag(NewMethod->getLocation(), 3774 diag::err_definition_of_explicitly_defaulted_member) 3775 << getSpecialMember(OldMethod); 3776 return true; 3777 } 3778 } 3779 3780 // C++11 [dcl.attr.noreturn]p1: 3781 // The first declaration of a function shall specify the noreturn 3782 // attribute if any declaration of that function specifies the noreturn 3783 // attribute. 3784 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>()) 3785 if (!Old->hasAttr<CXX11NoReturnAttr>()) { 3786 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl) 3787 << NRA; 3788 Diag(Old->getLocation(), diag::note_previous_declaration); 3789 } 3790 3791 // C++11 [dcl.attr.depend]p2: 3792 // The first declaration of a function shall specify the 3793 // carries_dependency attribute for its declarator-id if any declaration 3794 // of the function specifies the carries_dependency attribute. 3795 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 3796 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 3797 Diag(CDA->getLocation(), 3798 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 3799 Diag(Old->getFirstDecl()->getLocation(), 3800 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 3801 } 3802 3803 // (C++98 8.3.5p3): 3804 // All declarations for a function shall agree exactly in both the 3805 // return type and the parameter-type-list. 3806 // We also want to respect all the extended bits except noreturn. 3807 3808 // noreturn should now match unless the old type info didn't have it. 3809 QualType OldQTypeForComparison = OldQType; 3810 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3811 auto *OldType = OldQType->castAs<FunctionProtoType>(); 3812 const FunctionType *OldTypeForComparison 3813 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3814 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3815 assert(OldQTypeForComparison.isCanonical()); 3816 } 3817 3818 if (haveIncompatibleLanguageLinkages(Old, New)) { 3819 // As a special case, retain the language linkage from previous 3820 // declarations of a friend function as an extension. 3821 // 3822 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3823 // and is useful because there's otherwise no way to specify language 3824 // linkage within class scope. 3825 // 3826 // Check cautiously as the friend object kind isn't yet complete. 3827 if (New->getFriendObjectKind() != Decl::FOK_None) { 3828 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3829 Diag(OldLocation, PrevDiag); 3830 } else { 3831 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3832 Diag(OldLocation, PrevDiag); 3833 return true; 3834 } 3835 } 3836 3837 // If the function types are compatible, merge the declarations. Ignore the 3838 // exception specifier because it was already checked above in 3839 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics 3840 // about incompatible types under -fms-compatibility. 3841 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison, 3842 NewQType)) 3843 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3844 3845 // If the types are imprecise (due to dependent constructs in friends or 3846 // local extern declarations), it's OK if they differ. We'll check again 3847 // during instantiation. 3848 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType)) 3849 return false; 3850 3851 // Fall through for conflicting redeclarations and redefinitions. 3852 } 3853 3854 // C: Function types need to be compatible, not identical. This handles 3855 // duplicate function decls like "void f(int); void f(enum X);" properly. 3856 if (!getLangOpts().CPlusPlus && 3857 Context.typesAreCompatible(OldQType, NewQType)) { 3858 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 3859 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 3860 const FunctionProtoType *OldProto = nullptr; 3861 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 3862 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 3863 // The old declaration provided a function prototype, but the 3864 // new declaration does not. Merge in the prototype. 3865 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 3866 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 3867 NewQType = 3868 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 3869 OldProto->getExtProtoInfo()); 3870 New->setType(NewQType); 3871 New->setHasInheritedPrototype(); 3872 3873 // Synthesize parameters with the same types. 3874 SmallVector<ParmVarDecl*, 16> Params; 3875 for (const auto &ParamType : OldProto->param_types()) { 3876 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 3877 SourceLocation(), nullptr, 3878 ParamType, /*TInfo=*/nullptr, 3879 SC_None, nullptr); 3880 Param->setScopeInfo(0, Params.size()); 3881 Param->setImplicit(); 3882 Params.push_back(Param); 3883 } 3884 3885 New->setParams(Params); 3886 } 3887 3888 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3889 } 3890 3891 // Check if the function types are compatible when pointer size address 3892 // spaces are ignored. 3893 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType)) 3894 return false; 3895 3896 // GNU C permits a K&R definition to follow a prototype declaration 3897 // if the declared types of the parameters in the K&R definition 3898 // match the types in the prototype declaration, even when the 3899 // promoted types of the parameters from the K&R definition differ 3900 // from the types in the prototype. GCC then keeps the types from 3901 // the prototype. 3902 // 3903 // If a variadic prototype is followed by a non-variadic K&R definition, 3904 // the K&R definition becomes variadic. This is sort of an edge case, but 3905 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 3906 // C99 6.9.1p8. 3907 if (!getLangOpts().CPlusPlus && 3908 Old->hasPrototype() && !New->hasPrototype() && 3909 New->getType()->getAs<FunctionProtoType>() && 3910 Old->getNumParams() == New->getNumParams()) { 3911 SmallVector<QualType, 16> ArgTypes; 3912 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 3913 const FunctionProtoType *OldProto 3914 = Old->getType()->getAs<FunctionProtoType>(); 3915 const FunctionProtoType *NewProto 3916 = New->getType()->getAs<FunctionProtoType>(); 3917 3918 // Determine whether this is the GNU C extension. 3919 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 3920 NewProto->getReturnType()); 3921 bool LooseCompatible = !MergedReturn.isNull(); 3922 for (unsigned Idx = 0, End = Old->getNumParams(); 3923 LooseCompatible && Idx != End; ++Idx) { 3924 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 3925 ParmVarDecl *NewParm = New->getParamDecl(Idx); 3926 if (Context.typesAreCompatible(OldParm->getType(), 3927 NewProto->getParamType(Idx))) { 3928 ArgTypes.push_back(NewParm->getType()); 3929 } else if (Context.typesAreCompatible(OldParm->getType(), 3930 NewParm->getType(), 3931 /*CompareUnqualified=*/true)) { 3932 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 3933 NewProto->getParamType(Idx) }; 3934 Warnings.push_back(Warn); 3935 ArgTypes.push_back(NewParm->getType()); 3936 } else 3937 LooseCompatible = false; 3938 } 3939 3940 if (LooseCompatible) { 3941 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 3942 Diag(Warnings[Warn].NewParm->getLocation(), 3943 diag::ext_param_promoted_not_compatible_with_prototype) 3944 << Warnings[Warn].PromotedType 3945 << Warnings[Warn].OldParm->getType(); 3946 if (Warnings[Warn].OldParm->getLocation().isValid()) 3947 Diag(Warnings[Warn].OldParm->getLocation(), 3948 diag::note_previous_declaration); 3949 } 3950 3951 if (MergeTypeWithOld) 3952 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 3953 OldProto->getExtProtoInfo())); 3954 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3955 } 3956 3957 // Fall through to diagnose conflicting types. 3958 } 3959 3960 // A function that has already been declared has been redeclared or 3961 // defined with a different type; show an appropriate diagnostic. 3962 3963 // If the previous declaration was an implicitly-generated builtin 3964 // declaration, then at the very least we should use a specialized note. 3965 unsigned BuiltinID; 3966 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3967 // If it's actually a library-defined builtin function like 'malloc' 3968 // or 'printf', just warn about the incompatible redeclaration. 3969 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3970 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3971 Diag(OldLocation, diag::note_previous_builtin_declaration) 3972 << Old << Old->getType(); 3973 return false; 3974 } 3975 3976 PrevDiag = diag::note_previous_builtin_declaration; 3977 } 3978 3979 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3980 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3981 return true; 3982 } 3983 3984 /// Completes the merge of two function declarations that are 3985 /// known to be compatible. 3986 /// 3987 /// This routine handles the merging of attributes and other 3988 /// properties of function declarations from the old declaration to 3989 /// the new declaration, once we know that New is in fact a 3990 /// redeclaration of Old. 3991 /// 3992 /// \returns false 3993 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3994 Scope *S, bool MergeTypeWithOld) { 3995 // Merge the attributes 3996 mergeDeclAttributes(New, Old); 3997 3998 // Merge "pure" flag. 3999 if (Old->isPure()) 4000 New->setPure(); 4001 4002 // Merge "used" flag. 4003 if (Old->getMostRecentDecl()->isUsed(false)) 4004 New->setIsUsed(); 4005 4006 // Merge attributes from the parameters. These can mismatch with K&R 4007 // declarations. 4008 if (New->getNumParams() == Old->getNumParams()) 4009 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 4010 ParmVarDecl *NewParam = New->getParamDecl(i); 4011 ParmVarDecl *OldParam = Old->getParamDecl(i); 4012 mergeParamDeclAttributes(NewParam, OldParam, *this); 4013 mergeParamDeclTypes(NewParam, OldParam, *this); 4014 } 4015 4016 if (getLangOpts().CPlusPlus) 4017 return MergeCXXFunctionDecl(New, Old, S); 4018 4019 // Merge the function types so the we get the composite types for the return 4020 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 4021 // was visible. 4022 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 4023 if (!Merged.isNull() && MergeTypeWithOld) 4024 New->setType(Merged); 4025 4026 return false; 4027 } 4028 4029 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 4030 ObjCMethodDecl *oldMethod) { 4031 // Merge the attributes, including deprecated/unavailable 4032 AvailabilityMergeKind MergeKind = 4033 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 4034 ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation 4035 : AMK_ProtocolImplementation) 4036 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 4037 : AMK_Override; 4038 4039 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 4040 4041 // Merge attributes from the parameters. 4042 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 4043 oe = oldMethod->param_end(); 4044 for (ObjCMethodDecl::param_iterator 4045 ni = newMethod->param_begin(), ne = newMethod->param_end(); 4046 ni != ne && oi != oe; ++ni, ++oi) 4047 mergeParamDeclAttributes(*ni, *oi, *this); 4048 4049 CheckObjCMethodOverride(newMethod, oldMethod); 4050 } 4051 4052 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 4053 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 4054 4055 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 4056 ? diag::err_redefinition_different_type 4057 : diag::err_redeclaration_different_type) 4058 << New->getDeclName() << New->getType() << Old->getType(); 4059 4060 diag::kind PrevDiag; 4061 SourceLocation OldLocation; 4062 std::tie(PrevDiag, OldLocation) 4063 = getNoteDiagForInvalidRedeclaration(Old, New); 4064 S.Diag(OldLocation, PrevDiag); 4065 New->setInvalidDecl(); 4066 } 4067 4068 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 4069 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 4070 /// emitting diagnostics as appropriate. 4071 /// 4072 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 4073 /// to here in AddInitializerToDecl. We can't check them before the initializer 4074 /// is attached. 4075 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 4076 bool MergeTypeWithOld) { 4077 if (New->isInvalidDecl() || Old->isInvalidDecl()) 4078 return; 4079 4080 QualType MergedT; 4081 if (getLangOpts().CPlusPlus) { 4082 if (New->getType()->isUndeducedType()) { 4083 // We don't know what the new type is until the initializer is attached. 4084 return; 4085 } else if (Context.hasSameType(New->getType(), Old->getType())) { 4086 // These could still be something that needs exception specs checked. 4087 return MergeVarDeclExceptionSpecs(New, Old); 4088 } 4089 // C++ [basic.link]p10: 4090 // [...] the types specified by all declarations referring to a given 4091 // object or function shall be identical, except that declarations for an 4092 // array object can specify array types that differ by the presence or 4093 // absence of a major array bound (8.3.4). 4094 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 4095 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 4096 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 4097 4098 // We are merging a variable declaration New into Old. If it has an array 4099 // bound, and that bound differs from Old's bound, we should diagnose the 4100 // mismatch. 4101 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 4102 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 4103 PrevVD = PrevVD->getPreviousDecl()) { 4104 QualType PrevVDTy = PrevVD->getType(); 4105 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 4106 continue; 4107 4108 if (!Context.hasSameType(New->getType(), PrevVDTy)) 4109 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 4110 } 4111 } 4112 4113 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 4114 if (Context.hasSameType(OldArray->getElementType(), 4115 NewArray->getElementType())) 4116 MergedT = New->getType(); 4117 } 4118 // FIXME: Check visibility. New is hidden but has a complete type. If New 4119 // has no array bound, it should not inherit one from Old, if Old is not 4120 // visible. 4121 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 4122 if (Context.hasSameType(OldArray->getElementType(), 4123 NewArray->getElementType())) 4124 MergedT = Old->getType(); 4125 } 4126 } 4127 else if (New->getType()->isObjCObjectPointerType() && 4128 Old->getType()->isObjCObjectPointerType()) { 4129 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 4130 Old->getType()); 4131 } 4132 } else { 4133 // C 6.2.7p2: 4134 // All declarations that refer to the same object or function shall have 4135 // compatible type. 4136 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 4137 } 4138 if (MergedT.isNull()) { 4139 // It's OK if we couldn't merge types if either type is dependent, for a 4140 // block-scope variable. In other cases (static data members of class 4141 // templates, variable templates, ...), we require the types to be 4142 // equivalent. 4143 // FIXME: The C++ standard doesn't say anything about this. 4144 if ((New->getType()->isDependentType() || 4145 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 4146 // If the old type was dependent, we can't merge with it, so the new type 4147 // becomes dependent for now. We'll reproduce the original type when we 4148 // instantiate the TypeSourceInfo for the variable. 4149 if (!New->getType()->isDependentType() && MergeTypeWithOld) 4150 New->setType(Context.DependentTy); 4151 return; 4152 } 4153 return diagnoseVarDeclTypeMismatch(*this, New, Old); 4154 } 4155 4156 // Don't actually update the type on the new declaration if the old 4157 // declaration was an extern declaration in a different scope. 4158 if (MergeTypeWithOld) 4159 New->setType(MergedT); 4160 } 4161 4162 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 4163 LookupResult &Previous) { 4164 // C11 6.2.7p4: 4165 // For an identifier with internal or external linkage declared 4166 // in a scope in which a prior declaration of that identifier is 4167 // visible, if the prior declaration specifies internal or 4168 // external linkage, the type of the identifier at the later 4169 // declaration becomes the composite type. 4170 // 4171 // If the variable isn't visible, we do not merge with its type. 4172 if (Previous.isShadowed()) 4173 return false; 4174 4175 if (S.getLangOpts().CPlusPlus) { 4176 // C++11 [dcl.array]p3: 4177 // If there is a preceding declaration of the entity in the same 4178 // scope in which the bound was specified, an omitted array bound 4179 // is taken to be the same as in that earlier declaration. 4180 return NewVD->isPreviousDeclInSameBlockScope() || 4181 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 4182 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 4183 } else { 4184 // If the old declaration was function-local, don't merge with its 4185 // type unless we're in the same function. 4186 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 4187 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 4188 } 4189 } 4190 4191 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 4192 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 4193 /// situation, merging decls or emitting diagnostics as appropriate. 4194 /// 4195 /// Tentative definition rules (C99 6.9.2p2) are checked by 4196 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 4197 /// definitions here, since the initializer hasn't been attached. 4198 /// 4199 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 4200 // If the new decl is already invalid, don't do any other checking. 4201 if (New->isInvalidDecl()) 4202 return; 4203 4204 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 4205 return; 4206 4207 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 4208 4209 // Verify the old decl was also a variable or variable template. 4210 VarDecl *Old = nullptr; 4211 VarTemplateDecl *OldTemplate = nullptr; 4212 if (Previous.isSingleResult()) { 4213 if (NewTemplate) { 4214 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 4215 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 4216 4217 if (auto *Shadow = 4218 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4219 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 4220 return New->setInvalidDecl(); 4221 } else { 4222 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 4223 4224 if (auto *Shadow = 4225 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4226 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 4227 return New->setInvalidDecl(); 4228 } 4229 } 4230 if (!Old) { 4231 Diag(New->getLocation(), diag::err_redefinition_different_kind) 4232 << New->getDeclName(); 4233 notePreviousDefinition(Previous.getRepresentativeDecl(), 4234 New->getLocation()); 4235 return New->setInvalidDecl(); 4236 } 4237 4238 // If the old declaration was found in an inline namespace and the new 4239 // declaration was qualified, update the DeclContext to match. 4240 adjustDeclContextForDeclaratorDecl(New, Old); 4241 4242 // Ensure the template parameters are compatible. 4243 if (NewTemplate && 4244 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 4245 OldTemplate->getTemplateParameters(), 4246 /*Complain=*/true, TPL_TemplateMatch)) 4247 return New->setInvalidDecl(); 4248 4249 // C++ [class.mem]p1: 4250 // A member shall not be declared twice in the member-specification [...] 4251 // 4252 // Here, we need only consider static data members. 4253 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 4254 Diag(New->getLocation(), diag::err_duplicate_member) 4255 << New->getIdentifier(); 4256 Diag(Old->getLocation(), diag::note_previous_declaration); 4257 New->setInvalidDecl(); 4258 } 4259 4260 mergeDeclAttributes(New, Old); 4261 // Warn if an already-declared variable is made a weak_import in a subsequent 4262 // declaration 4263 if (New->hasAttr<WeakImportAttr>() && 4264 Old->getStorageClass() == SC_None && 4265 !Old->hasAttr<WeakImportAttr>()) { 4266 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 4267 Diag(Old->getLocation(), diag::note_previous_declaration); 4268 // Remove weak_import attribute on new declaration. 4269 New->dropAttr<WeakImportAttr>(); 4270 } 4271 4272 if (const auto *ILA = New->getAttr<InternalLinkageAttr>()) 4273 if (!Old->hasAttr<InternalLinkageAttr>()) { 4274 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl) 4275 << ILA; 4276 Diag(Old->getLocation(), diag::note_previous_declaration); 4277 New->dropAttr<InternalLinkageAttr>(); 4278 } 4279 4280 // Merge the types. 4281 VarDecl *MostRecent = Old->getMostRecentDecl(); 4282 if (MostRecent != Old) { 4283 MergeVarDeclTypes(New, MostRecent, 4284 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 4285 if (New->isInvalidDecl()) 4286 return; 4287 } 4288 4289 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 4290 if (New->isInvalidDecl()) 4291 return; 4292 4293 diag::kind PrevDiag; 4294 SourceLocation OldLocation; 4295 std::tie(PrevDiag, OldLocation) = 4296 getNoteDiagForInvalidRedeclaration(Old, New); 4297 4298 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 4299 if (New->getStorageClass() == SC_Static && 4300 !New->isStaticDataMember() && 4301 Old->hasExternalFormalLinkage()) { 4302 if (getLangOpts().MicrosoftExt) { 4303 Diag(New->getLocation(), diag::ext_static_non_static) 4304 << New->getDeclName(); 4305 Diag(OldLocation, PrevDiag); 4306 } else { 4307 Diag(New->getLocation(), diag::err_static_non_static) 4308 << New->getDeclName(); 4309 Diag(OldLocation, PrevDiag); 4310 return New->setInvalidDecl(); 4311 } 4312 } 4313 // C99 6.2.2p4: 4314 // For an identifier declared with the storage-class specifier 4315 // extern in a scope in which a prior declaration of that 4316 // identifier is visible,23) if the prior declaration specifies 4317 // internal or external linkage, the linkage of the identifier at 4318 // the later declaration is the same as the linkage specified at 4319 // the prior declaration. If no prior declaration is visible, or 4320 // if the prior declaration specifies no linkage, then the 4321 // identifier has external linkage. 4322 if (New->hasExternalStorage() && Old->hasLinkage()) 4323 /* Okay */; 4324 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 4325 !New->isStaticDataMember() && 4326 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 4327 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 4328 Diag(OldLocation, PrevDiag); 4329 return New->setInvalidDecl(); 4330 } 4331 4332 // Check if extern is followed by non-extern and vice-versa. 4333 if (New->hasExternalStorage() && 4334 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 4335 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 4336 Diag(OldLocation, PrevDiag); 4337 return New->setInvalidDecl(); 4338 } 4339 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 4340 !New->hasExternalStorage()) { 4341 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 4342 Diag(OldLocation, PrevDiag); 4343 return New->setInvalidDecl(); 4344 } 4345 4346 if (CheckRedeclarationInModule(New, Old)) 4347 return; 4348 4349 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 4350 4351 // FIXME: The test for external storage here seems wrong? We still 4352 // need to check for mismatches. 4353 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 4354 // Don't complain about out-of-line definitions of static members. 4355 !(Old->getLexicalDeclContext()->isRecord() && 4356 !New->getLexicalDeclContext()->isRecord())) { 4357 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 4358 Diag(OldLocation, PrevDiag); 4359 return New->setInvalidDecl(); 4360 } 4361 4362 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 4363 if (VarDecl *Def = Old->getDefinition()) { 4364 // C++1z [dcl.fcn.spec]p4: 4365 // If the definition of a variable appears in a translation unit before 4366 // its first declaration as inline, the program is ill-formed. 4367 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 4368 Diag(Def->getLocation(), diag::note_previous_definition); 4369 } 4370 } 4371 4372 // If this redeclaration makes the variable inline, we may need to add it to 4373 // UndefinedButUsed. 4374 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 4375 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 4376 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 4377 SourceLocation())); 4378 4379 if (New->getTLSKind() != Old->getTLSKind()) { 4380 if (!Old->getTLSKind()) { 4381 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 4382 Diag(OldLocation, PrevDiag); 4383 } else if (!New->getTLSKind()) { 4384 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 4385 Diag(OldLocation, PrevDiag); 4386 } else { 4387 // Do not allow redeclaration to change the variable between requiring 4388 // static and dynamic initialization. 4389 // FIXME: GCC allows this, but uses the TLS keyword on the first 4390 // declaration to determine the kind. Do we need to be compatible here? 4391 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 4392 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 4393 Diag(OldLocation, PrevDiag); 4394 } 4395 } 4396 4397 // C++ doesn't have tentative definitions, so go right ahead and check here. 4398 if (getLangOpts().CPlusPlus && 4399 New->isThisDeclarationADefinition() == VarDecl::Definition) { 4400 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 4401 Old->getCanonicalDecl()->isConstexpr()) { 4402 // This definition won't be a definition any more once it's been merged. 4403 Diag(New->getLocation(), 4404 diag::warn_deprecated_redundant_constexpr_static_def); 4405 } else if (VarDecl *Def = Old->getDefinition()) { 4406 if (checkVarDeclRedefinition(Def, New)) 4407 return; 4408 } 4409 } 4410 4411 if (haveIncompatibleLanguageLinkages(Old, New)) { 4412 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 4413 Diag(OldLocation, PrevDiag); 4414 New->setInvalidDecl(); 4415 return; 4416 } 4417 4418 // Merge "used" flag. 4419 if (Old->getMostRecentDecl()->isUsed(false)) 4420 New->setIsUsed(); 4421 4422 // Keep a chain of previous declarations. 4423 New->setPreviousDecl(Old); 4424 if (NewTemplate) 4425 NewTemplate->setPreviousDecl(OldTemplate); 4426 4427 // Inherit access appropriately. 4428 New->setAccess(Old->getAccess()); 4429 if (NewTemplate) 4430 NewTemplate->setAccess(New->getAccess()); 4431 4432 if (Old->isInline()) 4433 New->setImplicitlyInline(); 4434 } 4435 4436 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { 4437 SourceManager &SrcMgr = getSourceManager(); 4438 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); 4439 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); 4440 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); 4441 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); 4442 auto &HSI = PP.getHeaderSearchInfo(); 4443 StringRef HdrFilename = 4444 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); 4445 4446 auto noteFromModuleOrInclude = [&](Module *Mod, 4447 SourceLocation IncLoc) -> bool { 4448 // Redefinition errors with modules are common with non modular mapped 4449 // headers, example: a non-modular header H in module A that also gets 4450 // included directly in a TU. Pointing twice to the same header/definition 4451 // is confusing, try to get better diagnostics when modules is on. 4452 if (IncLoc.isValid()) { 4453 if (Mod) { 4454 Diag(IncLoc, diag::note_redefinition_modules_same_file) 4455 << HdrFilename.str() << Mod->getFullModuleName(); 4456 if (!Mod->DefinitionLoc.isInvalid()) 4457 Diag(Mod->DefinitionLoc, diag::note_defined_here) 4458 << Mod->getFullModuleName(); 4459 } else { 4460 Diag(IncLoc, diag::note_redefinition_include_same_file) 4461 << HdrFilename.str(); 4462 } 4463 return true; 4464 } 4465 4466 return false; 4467 }; 4468 4469 // Is it the same file and same offset? Provide more information on why 4470 // this leads to a redefinition error. 4471 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { 4472 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); 4473 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); 4474 bool EmittedDiag = 4475 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); 4476 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); 4477 4478 // If the header has no guards, emit a note suggesting one. 4479 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) 4480 Diag(Old->getLocation(), diag::note_use_ifdef_guards); 4481 4482 if (EmittedDiag) 4483 return; 4484 } 4485 4486 // Redefinition coming from different files or couldn't do better above. 4487 if (Old->getLocation().isValid()) 4488 Diag(Old->getLocation(), diag::note_previous_definition); 4489 } 4490 4491 /// We've just determined that \p Old and \p New both appear to be definitions 4492 /// of the same variable. Either diagnose or fix the problem. 4493 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 4494 if (!hasVisibleDefinition(Old) && 4495 (New->getFormalLinkage() == InternalLinkage || 4496 New->isInline() || 4497 New->getDescribedVarTemplate() || 4498 New->getNumTemplateParameterLists() || 4499 New->getDeclContext()->isDependentContext())) { 4500 // The previous definition is hidden, and multiple definitions are 4501 // permitted (in separate TUs). Demote this to a declaration. 4502 New->demoteThisDefinitionToDeclaration(); 4503 4504 // Make the canonical definition visible. 4505 if (auto *OldTD = Old->getDescribedVarTemplate()) 4506 makeMergedDefinitionVisible(OldTD); 4507 makeMergedDefinitionVisible(Old); 4508 return false; 4509 } else { 4510 Diag(New->getLocation(), diag::err_redefinition) << New; 4511 notePreviousDefinition(Old, New->getLocation()); 4512 New->setInvalidDecl(); 4513 return true; 4514 } 4515 } 4516 4517 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4518 /// no declarator (e.g. "struct foo;") is parsed. 4519 Decl * 4520 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4521 RecordDecl *&AnonRecord) { 4522 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, 4523 AnonRecord); 4524 } 4525 4526 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 4527 // disambiguate entities defined in different scopes. 4528 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 4529 // compatibility. 4530 // We will pick our mangling number depending on which version of MSVC is being 4531 // targeted. 4532 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 4533 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 4534 ? S->getMSCurManglingNumber() 4535 : S->getMSLastManglingNumber(); 4536 } 4537 4538 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 4539 if (!Context.getLangOpts().CPlusPlus) 4540 return; 4541 4542 if (isa<CXXRecordDecl>(Tag->getParent())) { 4543 // If this tag is the direct child of a class, number it if 4544 // it is anonymous. 4545 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 4546 return; 4547 MangleNumberingContext &MCtx = 4548 Context.getManglingNumberContext(Tag->getParent()); 4549 Context.setManglingNumber( 4550 Tag, MCtx.getManglingNumber( 4551 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4552 return; 4553 } 4554 4555 // If this tag isn't a direct child of a class, number it if it is local. 4556 MangleNumberingContext *MCtx; 4557 Decl *ManglingContextDecl; 4558 std::tie(MCtx, ManglingContextDecl) = 4559 getCurrentMangleNumberContext(Tag->getDeclContext()); 4560 if (MCtx) { 4561 Context.setManglingNumber( 4562 Tag, MCtx->getManglingNumber( 4563 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4564 } 4565 } 4566 4567 namespace { 4568 struct NonCLikeKind { 4569 enum { 4570 None, 4571 BaseClass, 4572 DefaultMemberInit, 4573 Lambda, 4574 Friend, 4575 OtherMember, 4576 Invalid, 4577 } Kind = None; 4578 SourceRange Range; 4579 4580 explicit operator bool() { return Kind != None; } 4581 }; 4582 } 4583 4584 /// Determine whether a class is C-like, according to the rules of C++ 4585 /// [dcl.typedef] for anonymous classes with typedef names for linkage. 4586 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) { 4587 if (RD->isInvalidDecl()) 4588 return {NonCLikeKind::Invalid, {}}; 4589 4590 // C++ [dcl.typedef]p9: [P1766R1] 4591 // An unnamed class with a typedef name for linkage purposes shall not 4592 // 4593 // -- have any base classes 4594 if (RD->getNumBases()) 4595 return {NonCLikeKind::BaseClass, 4596 SourceRange(RD->bases_begin()->getBeginLoc(), 4597 RD->bases_end()[-1].getEndLoc())}; 4598 bool Invalid = false; 4599 for (Decl *D : RD->decls()) { 4600 // Don't complain about things we already diagnosed. 4601 if (D->isInvalidDecl()) { 4602 Invalid = true; 4603 continue; 4604 } 4605 4606 // -- have any [...] default member initializers 4607 if (auto *FD = dyn_cast<FieldDecl>(D)) { 4608 if (FD->hasInClassInitializer()) { 4609 auto *Init = FD->getInClassInitializer(); 4610 return {NonCLikeKind::DefaultMemberInit, 4611 Init ? Init->getSourceRange() : D->getSourceRange()}; 4612 } 4613 continue; 4614 } 4615 4616 // FIXME: We don't allow friend declarations. This violates the wording of 4617 // P1766, but not the intent. 4618 if (isa<FriendDecl>(D)) 4619 return {NonCLikeKind::Friend, D->getSourceRange()}; 4620 4621 // -- declare any members other than non-static data members, member 4622 // enumerations, or member classes, 4623 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) || 4624 isa<EnumDecl>(D)) 4625 continue; 4626 auto *MemberRD = dyn_cast<CXXRecordDecl>(D); 4627 if (!MemberRD) { 4628 if (D->isImplicit()) 4629 continue; 4630 return {NonCLikeKind::OtherMember, D->getSourceRange()}; 4631 } 4632 4633 // -- contain a lambda-expression, 4634 if (MemberRD->isLambda()) 4635 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()}; 4636 4637 // and all member classes shall also satisfy these requirements 4638 // (recursively). 4639 if (MemberRD->isThisDeclarationADefinition()) { 4640 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD)) 4641 return Kind; 4642 } 4643 } 4644 4645 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}}; 4646 } 4647 4648 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 4649 TypedefNameDecl *NewTD) { 4650 if (TagFromDeclSpec->isInvalidDecl()) 4651 return; 4652 4653 // Do nothing if the tag already has a name for linkage purposes. 4654 if (TagFromDeclSpec->hasNameForLinkage()) 4655 return; 4656 4657 // A well-formed anonymous tag must always be a TUK_Definition. 4658 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 4659 4660 // The type must match the tag exactly; no qualifiers allowed. 4661 if (!Context.hasSameType(NewTD->getUnderlyingType(), 4662 Context.getTagDeclType(TagFromDeclSpec))) { 4663 if (getLangOpts().CPlusPlus) 4664 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 4665 return; 4666 } 4667 4668 // C++ [dcl.typedef]p9: [P1766R1, applied as DR] 4669 // An unnamed class with a typedef name for linkage purposes shall [be 4670 // C-like]. 4671 // 4672 // FIXME: Also diagnose if we've already computed the linkage. That ideally 4673 // shouldn't happen, but there are constructs that the language rule doesn't 4674 // disallow for which we can't reasonably avoid computing linkage early. 4675 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec); 4676 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD) 4677 : NonCLikeKind(); 4678 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed(); 4679 if (NonCLike || ChangesLinkage) { 4680 if (NonCLike.Kind == NonCLikeKind::Invalid) 4681 return; 4682 4683 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef; 4684 if (ChangesLinkage) { 4685 // If the linkage changes, we can't accept this as an extension. 4686 if (NonCLike.Kind == NonCLikeKind::None) 4687 DiagID = diag::err_typedef_changes_linkage; 4688 else 4689 DiagID = diag::err_non_c_like_anon_struct_in_typedef; 4690 } 4691 4692 SourceLocation FixitLoc = 4693 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart()); 4694 llvm::SmallString<40> TextToInsert; 4695 TextToInsert += ' '; 4696 TextToInsert += NewTD->getIdentifier()->getName(); 4697 4698 Diag(FixitLoc, DiagID) 4699 << isa<TypeAliasDecl>(NewTD) 4700 << FixItHint::CreateInsertion(FixitLoc, TextToInsert); 4701 if (NonCLike.Kind != NonCLikeKind::None) { 4702 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct) 4703 << NonCLike.Kind - 1 << NonCLike.Range; 4704 } 4705 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here) 4706 << NewTD << isa<TypeAliasDecl>(NewTD); 4707 4708 if (ChangesLinkage) 4709 return; 4710 } 4711 4712 // Otherwise, set this as the anon-decl typedef for the tag. 4713 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 4714 } 4715 4716 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 4717 switch (T) { 4718 case DeclSpec::TST_class: 4719 return 0; 4720 case DeclSpec::TST_struct: 4721 return 1; 4722 case DeclSpec::TST_interface: 4723 return 2; 4724 case DeclSpec::TST_union: 4725 return 3; 4726 case DeclSpec::TST_enum: 4727 return 4; 4728 default: 4729 llvm_unreachable("unexpected type specifier"); 4730 } 4731 } 4732 4733 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4734 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 4735 /// parameters to cope with template friend declarations. 4736 Decl * 4737 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4738 MultiTemplateParamsArg TemplateParams, 4739 bool IsExplicitInstantiation, 4740 RecordDecl *&AnonRecord) { 4741 Decl *TagD = nullptr; 4742 TagDecl *Tag = nullptr; 4743 if (DS.getTypeSpecType() == DeclSpec::TST_class || 4744 DS.getTypeSpecType() == DeclSpec::TST_struct || 4745 DS.getTypeSpecType() == DeclSpec::TST_interface || 4746 DS.getTypeSpecType() == DeclSpec::TST_union || 4747 DS.getTypeSpecType() == DeclSpec::TST_enum) { 4748 TagD = DS.getRepAsDecl(); 4749 4750 if (!TagD) // We probably had an error 4751 return nullptr; 4752 4753 // Note that the above type specs guarantee that the 4754 // type rep is a Decl, whereas in many of the others 4755 // it's a Type. 4756 if (isa<TagDecl>(TagD)) 4757 Tag = cast<TagDecl>(TagD); 4758 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 4759 Tag = CTD->getTemplatedDecl(); 4760 } 4761 4762 if (Tag) { 4763 handleTagNumbering(Tag, S); 4764 Tag->setFreeStanding(); 4765 if (Tag->isInvalidDecl()) 4766 return Tag; 4767 } 4768 4769 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 4770 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 4771 // or incomplete types shall not be restrict-qualified." 4772 if (TypeQuals & DeclSpec::TQ_restrict) 4773 Diag(DS.getRestrictSpecLoc(), 4774 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 4775 << DS.getSourceRange(); 4776 } 4777 4778 if (DS.isInlineSpecified()) 4779 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 4780 << getLangOpts().CPlusPlus17; 4781 4782 if (DS.hasConstexprSpecifier()) { 4783 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 4784 // and definitions of functions and variables. 4785 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to 4786 // the declaration of a function or function template 4787 if (Tag) 4788 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 4789 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) 4790 << static_cast<int>(DS.getConstexprSpecifier()); 4791 else 4792 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind) 4793 << static_cast<int>(DS.getConstexprSpecifier()); 4794 // Don't emit warnings after this error. 4795 return TagD; 4796 } 4797 4798 DiagnoseFunctionSpecifiers(DS); 4799 4800 if (DS.isFriendSpecified()) { 4801 // If we're dealing with a decl but not a TagDecl, assume that 4802 // whatever routines created it handled the friendship aspect. 4803 if (TagD && !Tag) 4804 return nullptr; 4805 return ActOnFriendTypeDecl(S, DS, TemplateParams); 4806 } 4807 4808 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 4809 bool IsExplicitSpecialization = 4810 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 4811 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 4812 !IsExplicitInstantiation && !IsExplicitSpecialization && 4813 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 4814 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 4815 // nested-name-specifier unless it is an explicit instantiation 4816 // or an explicit specialization. 4817 // 4818 // FIXME: We allow class template partial specializations here too, per the 4819 // obvious intent of DR1819. 4820 // 4821 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 4822 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 4823 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 4824 return nullptr; 4825 } 4826 4827 // Track whether this decl-specifier declares anything. 4828 bool DeclaresAnything = true; 4829 4830 // Handle anonymous struct definitions. 4831 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 4832 if (!Record->getDeclName() && Record->isCompleteDefinition() && 4833 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 4834 if (getLangOpts().CPlusPlus || 4835 Record->getDeclContext()->isRecord()) { 4836 // If CurContext is a DeclContext that can contain statements, 4837 // RecursiveASTVisitor won't visit the decls that 4838 // BuildAnonymousStructOrUnion() will put into CurContext. 4839 // Also store them here so that they can be part of the 4840 // DeclStmt that gets created in this case. 4841 // FIXME: Also return the IndirectFieldDecls created by 4842 // BuildAnonymousStructOr union, for the same reason? 4843 if (CurContext->isFunctionOrMethod()) 4844 AnonRecord = Record; 4845 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 4846 Context.getPrintingPolicy()); 4847 } 4848 4849 DeclaresAnything = false; 4850 } 4851 } 4852 4853 // C11 6.7.2.1p2: 4854 // A struct-declaration that does not declare an anonymous structure or 4855 // anonymous union shall contain a struct-declarator-list. 4856 // 4857 // This rule also existed in C89 and C99; the grammar for struct-declaration 4858 // did not permit a struct-declaration without a struct-declarator-list. 4859 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 4860 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 4861 // Check for Microsoft C extension: anonymous struct/union member. 4862 // Handle 2 kinds of anonymous struct/union: 4863 // struct STRUCT; 4864 // union UNION; 4865 // and 4866 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 4867 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 4868 if ((Tag && Tag->getDeclName()) || 4869 DS.getTypeSpecType() == DeclSpec::TST_typename) { 4870 RecordDecl *Record = nullptr; 4871 if (Tag) 4872 Record = dyn_cast<RecordDecl>(Tag); 4873 else if (const RecordType *RT = 4874 DS.getRepAsType().get()->getAsStructureType()) 4875 Record = RT->getDecl(); 4876 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 4877 Record = UT->getDecl(); 4878 4879 if (Record && getLangOpts().MicrosoftExt) { 4880 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record) 4881 << Record->isUnion() << DS.getSourceRange(); 4882 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 4883 } 4884 4885 DeclaresAnything = false; 4886 } 4887 } 4888 4889 // Skip all the checks below if we have a type error. 4890 if (DS.getTypeSpecType() == DeclSpec::TST_error || 4891 (TagD && TagD->isInvalidDecl())) 4892 return TagD; 4893 4894 if (getLangOpts().CPlusPlus && 4895 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 4896 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 4897 if (Enum->enumerator_begin() == Enum->enumerator_end() && 4898 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 4899 DeclaresAnything = false; 4900 4901 if (!DS.isMissingDeclaratorOk()) { 4902 // Customize diagnostic for a typedef missing a name. 4903 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 4904 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name) 4905 << DS.getSourceRange(); 4906 else 4907 DeclaresAnything = false; 4908 } 4909 4910 if (DS.isModulePrivateSpecified() && 4911 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 4912 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 4913 << Tag->getTagKind() 4914 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 4915 4916 ActOnDocumentableDecl(TagD); 4917 4918 // C 6.7/2: 4919 // A declaration [...] shall declare at least a declarator [...], a tag, 4920 // or the members of an enumeration. 4921 // C++ [dcl.dcl]p3: 4922 // [If there are no declarators], and except for the declaration of an 4923 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 4924 // names into the program, or shall redeclare a name introduced by a 4925 // previous declaration. 4926 if (!DeclaresAnything) { 4927 // In C, we allow this as a (popular) extension / bug. Don't bother 4928 // producing further diagnostics for redundant qualifiers after this. 4929 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty()) 4930 ? diag::err_no_declarators 4931 : diag::ext_no_declarators) 4932 << DS.getSourceRange(); 4933 return TagD; 4934 } 4935 4936 // C++ [dcl.stc]p1: 4937 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 4938 // init-declarator-list of the declaration shall not be empty. 4939 // C++ [dcl.fct.spec]p1: 4940 // If a cv-qualifier appears in a decl-specifier-seq, the 4941 // init-declarator-list of the declaration shall not be empty. 4942 // 4943 // Spurious qualifiers here appear to be valid in C. 4944 unsigned DiagID = diag::warn_standalone_specifier; 4945 if (getLangOpts().CPlusPlus) 4946 DiagID = diag::ext_standalone_specifier; 4947 4948 // Note that a linkage-specification sets a storage class, but 4949 // 'extern "C" struct foo;' is actually valid and not theoretically 4950 // useless. 4951 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 4952 if (SCS == DeclSpec::SCS_mutable) 4953 // Since mutable is not a viable storage class specifier in C, there is 4954 // no reason to treat it as an extension. Instead, diagnose as an error. 4955 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 4956 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 4957 Diag(DS.getStorageClassSpecLoc(), DiagID) 4958 << DeclSpec::getSpecifierName(SCS); 4959 } 4960 4961 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 4962 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 4963 << DeclSpec::getSpecifierName(TSCS); 4964 if (DS.getTypeQualifiers()) { 4965 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4966 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 4967 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4968 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 4969 // Restrict is covered above. 4970 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4971 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 4972 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4973 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 4974 } 4975 4976 // Warn about ignored type attributes, for example: 4977 // __attribute__((aligned)) struct A; 4978 // Attributes should be placed after tag to apply to type declaration. 4979 if (!DS.getAttributes().empty()) { 4980 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 4981 if (TypeSpecType == DeclSpec::TST_class || 4982 TypeSpecType == DeclSpec::TST_struct || 4983 TypeSpecType == DeclSpec::TST_interface || 4984 TypeSpecType == DeclSpec::TST_union || 4985 TypeSpecType == DeclSpec::TST_enum) { 4986 for (const ParsedAttr &AL : DS.getAttributes()) 4987 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored) 4988 << AL << GetDiagnosticTypeSpecifierID(TypeSpecType); 4989 } 4990 } 4991 4992 return TagD; 4993 } 4994 4995 /// We are trying to inject an anonymous member into the given scope; 4996 /// check if there's an existing declaration that can't be overloaded. 4997 /// 4998 /// \return true if this is a forbidden redeclaration 4999 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 5000 Scope *S, 5001 DeclContext *Owner, 5002 DeclarationName Name, 5003 SourceLocation NameLoc, 5004 bool IsUnion) { 5005 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 5006 Sema::ForVisibleRedeclaration); 5007 if (!SemaRef.LookupName(R, S)) return false; 5008 5009 // Pick a representative declaration. 5010 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 5011 assert(PrevDecl && "Expected a non-null Decl"); 5012 5013 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 5014 return false; 5015 5016 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 5017 << IsUnion << Name; 5018 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 5019 5020 return true; 5021 } 5022 5023 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 5024 /// anonymous struct or union AnonRecord into the owning context Owner 5025 /// and scope S. This routine will be invoked just after we realize 5026 /// that an unnamed union or struct is actually an anonymous union or 5027 /// struct, e.g., 5028 /// 5029 /// @code 5030 /// union { 5031 /// int i; 5032 /// float f; 5033 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 5034 /// // f into the surrounding scope.x 5035 /// @endcode 5036 /// 5037 /// This routine is recursive, injecting the names of nested anonymous 5038 /// structs/unions into the owning context and scope as well. 5039 static bool 5040 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 5041 RecordDecl *AnonRecord, AccessSpecifier AS, 5042 SmallVectorImpl<NamedDecl *> &Chaining) { 5043 bool Invalid = false; 5044 5045 // Look every FieldDecl and IndirectFieldDecl with a name. 5046 for (auto *D : AnonRecord->decls()) { 5047 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 5048 cast<NamedDecl>(D)->getDeclName()) { 5049 ValueDecl *VD = cast<ValueDecl>(D); 5050 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 5051 VD->getLocation(), 5052 AnonRecord->isUnion())) { 5053 // C++ [class.union]p2: 5054 // The names of the members of an anonymous union shall be 5055 // distinct from the names of any other entity in the 5056 // scope in which the anonymous union is declared. 5057 Invalid = true; 5058 } else { 5059 // C++ [class.union]p2: 5060 // For the purpose of name lookup, after the anonymous union 5061 // definition, the members of the anonymous union are 5062 // considered to have been defined in the scope in which the 5063 // anonymous union is declared. 5064 unsigned OldChainingSize = Chaining.size(); 5065 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 5066 Chaining.append(IF->chain_begin(), IF->chain_end()); 5067 else 5068 Chaining.push_back(VD); 5069 5070 assert(Chaining.size() >= 2); 5071 NamedDecl **NamedChain = 5072 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 5073 for (unsigned i = 0; i < Chaining.size(); i++) 5074 NamedChain[i] = Chaining[i]; 5075 5076 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 5077 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 5078 VD->getType(), {NamedChain, Chaining.size()}); 5079 5080 for (const auto *Attr : VD->attrs()) 5081 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 5082 5083 IndirectField->setAccess(AS); 5084 IndirectField->setImplicit(); 5085 SemaRef.PushOnScopeChains(IndirectField, S); 5086 5087 // That includes picking up the appropriate access specifier. 5088 if (AS != AS_none) IndirectField->setAccess(AS); 5089 5090 Chaining.resize(OldChainingSize); 5091 } 5092 } 5093 } 5094 5095 return Invalid; 5096 } 5097 5098 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 5099 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 5100 /// illegal input values are mapped to SC_None. 5101 static StorageClass 5102 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 5103 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 5104 assert(StorageClassSpec != DeclSpec::SCS_typedef && 5105 "Parser allowed 'typedef' as storage class VarDecl."); 5106 switch (StorageClassSpec) { 5107 case DeclSpec::SCS_unspecified: return SC_None; 5108 case DeclSpec::SCS_extern: 5109 if (DS.isExternInLinkageSpec()) 5110 return SC_None; 5111 return SC_Extern; 5112 case DeclSpec::SCS_static: return SC_Static; 5113 case DeclSpec::SCS_auto: return SC_Auto; 5114 case DeclSpec::SCS_register: return SC_Register; 5115 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 5116 // Illegal SCSs map to None: error reporting is up to the caller. 5117 case DeclSpec::SCS_mutable: // Fall through. 5118 case DeclSpec::SCS_typedef: return SC_None; 5119 } 5120 llvm_unreachable("unknown storage class specifier"); 5121 } 5122 5123 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 5124 assert(Record->hasInClassInitializer()); 5125 5126 for (const auto *I : Record->decls()) { 5127 const auto *FD = dyn_cast<FieldDecl>(I); 5128 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 5129 FD = IFD->getAnonField(); 5130 if (FD && FD->hasInClassInitializer()) 5131 return FD->getLocation(); 5132 } 5133 5134 llvm_unreachable("couldn't find in-class initializer"); 5135 } 5136 5137 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 5138 SourceLocation DefaultInitLoc) { 5139 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 5140 return; 5141 5142 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 5143 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 5144 } 5145 5146 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 5147 CXXRecordDecl *AnonUnion) { 5148 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 5149 return; 5150 5151 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 5152 } 5153 5154 /// BuildAnonymousStructOrUnion - Handle the declaration of an 5155 /// anonymous structure or union. Anonymous unions are a C++ feature 5156 /// (C++ [class.union]) and a C11 feature; anonymous structures 5157 /// are a C11 feature and GNU C++ extension. 5158 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 5159 AccessSpecifier AS, 5160 RecordDecl *Record, 5161 const PrintingPolicy &Policy) { 5162 DeclContext *Owner = Record->getDeclContext(); 5163 5164 // Diagnose whether this anonymous struct/union is an extension. 5165 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 5166 Diag(Record->getLocation(), diag::ext_anonymous_union); 5167 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 5168 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 5169 else if (!Record->isUnion() && !getLangOpts().C11) 5170 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 5171 5172 // C and C++ require different kinds of checks for anonymous 5173 // structs/unions. 5174 bool Invalid = false; 5175 if (getLangOpts().CPlusPlus) { 5176 const char *PrevSpec = nullptr; 5177 if (Record->isUnion()) { 5178 // C++ [class.union]p6: 5179 // C++17 [class.union.anon]p2: 5180 // Anonymous unions declared in a named namespace or in the 5181 // global namespace shall be declared static. 5182 unsigned DiagID; 5183 DeclContext *OwnerScope = Owner->getRedeclContext(); 5184 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 5185 (OwnerScope->isTranslationUnit() || 5186 (OwnerScope->isNamespace() && 5187 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) { 5188 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 5189 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 5190 5191 // Recover by adding 'static'. 5192 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 5193 PrevSpec, DiagID, Policy); 5194 } 5195 // C++ [class.union]p6: 5196 // A storage class is not allowed in a declaration of an 5197 // anonymous union in a class scope. 5198 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 5199 isa<RecordDecl>(Owner)) { 5200 Diag(DS.getStorageClassSpecLoc(), 5201 diag::err_anonymous_union_with_storage_spec) 5202 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 5203 5204 // Recover by removing the storage specifier. 5205 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 5206 SourceLocation(), 5207 PrevSpec, DiagID, Context.getPrintingPolicy()); 5208 } 5209 } 5210 5211 // Ignore const/volatile/restrict qualifiers. 5212 if (DS.getTypeQualifiers()) { 5213 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 5214 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 5215 << Record->isUnion() << "const" 5216 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 5217 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 5218 Diag(DS.getVolatileSpecLoc(), 5219 diag::ext_anonymous_struct_union_qualified) 5220 << Record->isUnion() << "volatile" 5221 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 5222 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 5223 Diag(DS.getRestrictSpecLoc(), 5224 diag::ext_anonymous_struct_union_qualified) 5225 << Record->isUnion() << "restrict" 5226 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 5227 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 5228 Diag(DS.getAtomicSpecLoc(), 5229 diag::ext_anonymous_struct_union_qualified) 5230 << Record->isUnion() << "_Atomic" 5231 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 5232 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 5233 Diag(DS.getUnalignedSpecLoc(), 5234 diag::ext_anonymous_struct_union_qualified) 5235 << Record->isUnion() << "__unaligned" 5236 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 5237 5238 DS.ClearTypeQualifiers(); 5239 } 5240 5241 // C++ [class.union]p2: 5242 // The member-specification of an anonymous union shall only 5243 // define non-static data members. [Note: nested types and 5244 // functions cannot be declared within an anonymous union. ] 5245 for (auto *Mem : Record->decls()) { 5246 // Ignore invalid declarations; we already diagnosed them. 5247 if (Mem->isInvalidDecl()) 5248 continue; 5249 5250 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 5251 // C++ [class.union]p3: 5252 // An anonymous union shall not have private or protected 5253 // members (clause 11). 5254 assert(FD->getAccess() != AS_none); 5255 if (FD->getAccess() != AS_public) { 5256 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 5257 << Record->isUnion() << (FD->getAccess() == AS_protected); 5258 Invalid = true; 5259 } 5260 5261 // C++ [class.union]p1 5262 // An object of a class with a non-trivial constructor, a non-trivial 5263 // copy constructor, a non-trivial destructor, or a non-trivial copy 5264 // assignment operator cannot be a member of a union, nor can an 5265 // array of such objects. 5266 if (CheckNontrivialField(FD)) 5267 Invalid = true; 5268 } else if (Mem->isImplicit()) { 5269 // Any implicit members are fine. 5270 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 5271 // This is a type that showed up in an 5272 // elaborated-type-specifier inside the anonymous struct or 5273 // union, but which actually declares a type outside of the 5274 // anonymous struct or union. It's okay. 5275 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 5276 if (!MemRecord->isAnonymousStructOrUnion() && 5277 MemRecord->getDeclName()) { 5278 // Visual C++ allows type definition in anonymous struct or union. 5279 if (getLangOpts().MicrosoftExt) 5280 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 5281 << Record->isUnion(); 5282 else { 5283 // This is a nested type declaration. 5284 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 5285 << Record->isUnion(); 5286 Invalid = true; 5287 } 5288 } else { 5289 // This is an anonymous type definition within another anonymous type. 5290 // This is a popular extension, provided by Plan9, MSVC and GCC, but 5291 // not part of standard C++. 5292 Diag(MemRecord->getLocation(), 5293 diag::ext_anonymous_record_with_anonymous_type) 5294 << Record->isUnion(); 5295 } 5296 } else if (isa<AccessSpecDecl>(Mem)) { 5297 // Any access specifier is fine. 5298 } else if (isa<StaticAssertDecl>(Mem)) { 5299 // In C++1z, static_assert declarations are also fine. 5300 } else { 5301 // We have something that isn't a non-static data 5302 // member. Complain about it. 5303 unsigned DK = diag::err_anonymous_record_bad_member; 5304 if (isa<TypeDecl>(Mem)) 5305 DK = diag::err_anonymous_record_with_type; 5306 else if (isa<FunctionDecl>(Mem)) 5307 DK = diag::err_anonymous_record_with_function; 5308 else if (isa<VarDecl>(Mem)) 5309 DK = diag::err_anonymous_record_with_static; 5310 5311 // Visual C++ allows type definition in anonymous struct or union. 5312 if (getLangOpts().MicrosoftExt && 5313 DK == diag::err_anonymous_record_with_type) 5314 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 5315 << Record->isUnion(); 5316 else { 5317 Diag(Mem->getLocation(), DK) << Record->isUnion(); 5318 Invalid = true; 5319 } 5320 } 5321 } 5322 5323 // C++11 [class.union]p8 (DR1460): 5324 // At most one variant member of a union may have a 5325 // brace-or-equal-initializer. 5326 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 5327 Owner->isRecord()) 5328 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 5329 cast<CXXRecordDecl>(Record)); 5330 } 5331 5332 if (!Record->isUnion() && !Owner->isRecord()) { 5333 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 5334 << getLangOpts().CPlusPlus; 5335 Invalid = true; 5336 } 5337 5338 // C++ [dcl.dcl]p3: 5339 // [If there are no declarators], and except for the declaration of an 5340 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 5341 // names into the program 5342 // C++ [class.mem]p2: 5343 // each such member-declaration shall either declare at least one member 5344 // name of the class or declare at least one unnamed bit-field 5345 // 5346 // For C this is an error even for a named struct, and is diagnosed elsewhere. 5347 if (getLangOpts().CPlusPlus && Record->field_empty()) 5348 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); 5349 5350 // Mock up a declarator. 5351 Declarator Dc(DS, DeclaratorContext::Member); 5352 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5353 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 5354 5355 // Create a declaration for this anonymous struct/union. 5356 NamedDecl *Anon = nullptr; 5357 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 5358 Anon = FieldDecl::Create( 5359 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(), 5360 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo, 5361 /*BitWidth=*/nullptr, /*Mutable=*/false, 5362 /*InitStyle=*/ICIS_NoInit); 5363 Anon->setAccess(AS); 5364 ProcessDeclAttributes(S, Anon, Dc); 5365 5366 if (getLangOpts().CPlusPlus) 5367 FieldCollector->Add(cast<FieldDecl>(Anon)); 5368 } else { 5369 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 5370 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 5371 if (SCSpec == DeclSpec::SCS_mutable) { 5372 // mutable can only appear on non-static class members, so it's always 5373 // an error here 5374 Diag(Record->getLocation(), diag::err_mutable_nonmember); 5375 Invalid = true; 5376 SC = SC_None; 5377 } 5378 5379 assert(DS.getAttributes().empty() && "No attribute expected"); 5380 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(), 5381 Record->getLocation(), /*IdentifierInfo=*/nullptr, 5382 Context.getTypeDeclType(Record), TInfo, SC); 5383 5384 // Default-initialize the implicit variable. This initialization will be 5385 // trivial in almost all cases, except if a union member has an in-class 5386 // initializer: 5387 // union { int n = 0; }; 5388 ActOnUninitializedDecl(Anon); 5389 } 5390 Anon->setImplicit(); 5391 5392 // Mark this as an anonymous struct/union type. 5393 Record->setAnonymousStructOrUnion(true); 5394 5395 // Add the anonymous struct/union object to the current 5396 // context. We'll be referencing this object when we refer to one of 5397 // its members. 5398 Owner->addDecl(Anon); 5399 5400 // Inject the members of the anonymous struct/union into the owning 5401 // context and into the identifier resolver chain for name lookup 5402 // purposes. 5403 SmallVector<NamedDecl*, 2> Chain; 5404 Chain.push_back(Anon); 5405 5406 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 5407 Invalid = true; 5408 5409 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 5410 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 5411 MangleNumberingContext *MCtx; 5412 Decl *ManglingContextDecl; 5413 std::tie(MCtx, ManglingContextDecl) = 5414 getCurrentMangleNumberContext(NewVD->getDeclContext()); 5415 if (MCtx) { 5416 Context.setManglingNumber( 5417 NewVD, MCtx->getManglingNumber( 5418 NewVD, getMSManglingNumber(getLangOpts(), S))); 5419 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 5420 } 5421 } 5422 } 5423 5424 if (Invalid) 5425 Anon->setInvalidDecl(); 5426 5427 return Anon; 5428 } 5429 5430 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 5431 /// Microsoft C anonymous structure. 5432 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 5433 /// Example: 5434 /// 5435 /// struct A { int a; }; 5436 /// struct B { struct A; int b; }; 5437 /// 5438 /// void foo() { 5439 /// B var; 5440 /// var.a = 3; 5441 /// } 5442 /// 5443 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 5444 RecordDecl *Record) { 5445 assert(Record && "expected a record!"); 5446 5447 // Mock up a declarator. 5448 Declarator Dc(DS, DeclaratorContext::TypeName); 5449 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5450 assert(TInfo && "couldn't build declarator info for anonymous struct"); 5451 5452 auto *ParentDecl = cast<RecordDecl>(CurContext); 5453 QualType RecTy = Context.getTypeDeclType(Record); 5454 5455 // Create a declaration for this anonymous struct. 5456 NamedDecl *Anon = 5457 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(), 5458 /*IdentifierInfo=*/nullptr, RecTy, TInfo, 5459 /*BitWidth=*/nullptr, /*Mutable=*/false, 5460 /*InitStyle=*/ICIS_NoInit); 5461 Anon->setImplicit(); 5462 5463 // Add the anonymous struct object to the current context. 5464 CurContext->addDecl(Anon); 5465 5466 // Inject the members of the anonymous struct into the current 5467 // context and into the identifier resolver chain for name lookup 5468 // purposes. 5469 SmallVector<NamedDecl*, 2> Chain; 5470 Chain.push_back(Anon); 5471 5472 RecordDecl *RecordDef = Record->getDefinition(); 5473 if (RequireCompleteSizedType(Anon->getLocation(), RecTy, 5474 diag::err_field_incomplete_or_sizeless) || 5475 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 5476 AS_none, Chain)) { 5477 Anon->setInvalidDecl(); 5478 ParentDecl->setInvalidDecl(); 5479 } 5480 5481 return Anon; 5482 } 5483 5484 /// GetNameForDeclarator - Determine the full declaration name for the 5485 /// given Declarator. 5486 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 5487 return GetNameFromUnqualifiedId(D.getName()); 5488 } 5489 5490 /// Retrieves the declaration name from a parsed unqualified-id. 5491 DeclarationNameInfo 5492 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 5493 DeclarationNameInfo NameInfo; 5494 NameInfo.setLoc(Name.StartLocation); 5495 5496 switch (Name.getKind()) { 5497 5498 case UnqualifiedIdKind::IK_ImplicitSelfParam: 5499 case UnqualifiedIdKind::IK_Identifier: 5500 NameInfo.setName(Name.Identifier); 5501 return NameInfo; 5502 5503 case UnqualifiedIdKind::IK_DeductionGuideName: { 5504 // C++ [temp.deduct.guide]p3: 5505 // The simple-template-id shall name a class template specialization. 5506 // The template-name shall be the same identifier as the template-name 5507 // of the simple-template-id. 5508 // These together intend to imply that the template-name shall name a 5509 // class template. 5510 // FIXME: template<typename T> struct X {}; 5511 // template<typename T> using Y = X<T>; 5512 // Y(int) -> Y<int>; 5513 // satisfies these rules but does not name a class template. 5514 TemplateName TN = Name.TemplateName.get().get(); 5515 auto *Template = TN.getAsTemplateDecl(); 5516 if (!Template || !isa<ClassTemplateDecl>(Template)) { 5517 Diag(Name.StartLocation, 5518 diag::err_deduction_guide_name_not_class_template) 5519 << (int)getTemplateNameKindForDiagnostics(TN) << TN; 5520 if (Template) 5521 Diag(Template->getLocation(), diag::note_template_decl_here); 5522 return DeclarationNameInfo(); 5523 } 5524 5525 NameInfo.setName( 5526 Context.DeclarationNames.getCXXDeductionGuideName(Template)); 5527 return NameInfo; 5528 } 5529 5530 case UnqualifiedIdKind::IK_OperatorFunctionId: 5531 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 5532 Name.OperatorFunctionId.Operator)); 5533 NameInfo.setCXXOperatorNameRange(SourceRange( 5534 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation)); 5535 return NameInfo; 5536 5537 case UnqualifiedIdKind::IK_LiteralOperatorId: 5538 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 5539 Name.Identifier)); 5540 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 5541 return NameInfo; 5542 5543 case UnqualifiedIdKind::IK_ConversionFunctionId: { 5544 TypeSourceInfo *TInfo; 5545 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 5546 if (Ty.isNull()) 5547 return DeclarationNameInfo(); 5548 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 5549 Context.getCanonicalType(Ty))); 5550 NameInfo.setNamedTypeInfo(TInfo); 5551 return NameInfo; 5552 } 5553 5554 case UnqualifiedIdKind::IK_ConstructorName: { 5555 TypeSourceInfo *TInfo; 5556 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 5557 if (Ty.isNull()) 5558 return DeclarationNameInfo(); 5559 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5560 Context.getCanonicalType(Ty))); 5561 NameInfo.setNamedTypeInfo(TInfo); 5562 return NameInfo; 5563 } 5564 5565 case UnqualifiedIdKind::IK_ConstructorTemplateId: { 5566 // In well-formed code, we can only have a constructor 5567 // template-id that refers to the current context, so go there 5568 // to find the actual type being constructed. 5569 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 5570 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 5571 return DeclarationNameInfo(); 5572 5573 // Determine the type of the class being constructed. 5574 QualType CurClassType = Context.getTypeDeclType(CurClass); 5575 5576 // FIXME: Check two things: that the template-id names the same type as 5577 // CurClassType, and that the template-id does not occur when the name 5578 // was qualified. 5579 5580 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5581 Context.getCanonicalType(CurClassType))); 5582 // FIXME: should we retrieve TypeSourceInfo? 5583 NameInfo.setNamedTypeInfo(nullptr); 5584 return NameInfo; 5585 } 5586 5587 case UnqualifiedIdKind::IK_DestructorName: { 5588 TypeSourceInfo *TInfo; 5589 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 5590 if (Ty.isNull()) 5591 return DeclarationNameInfo(); 5592 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 5593 Context.getCanonicalType(Ty))); 5594 NameInfo.setNamedTypeInfo(TInfo); 5595 return NameInfo; 5596 } 5597 5598 case UnqualifiedIdKind::IK_TemplateId: { 5599 TemplateName TName = Name.TemplateId->Template.get(); 5600 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 5601 return Context.getNameForTemplate(TName, TNameLoc); 5602 } 5603 5604 } // switch (Name.getKind()) 5605 5606 llvm_unreachable("Unknown name kind"); 5607 } 5608 5609 static QualType getCoreType(QualType Ty) { 5610 do { 5611 if (Ty->isPointerType() || Ty->isReferenceType()) 5612 Ty = Ty->getPointeeType(); 5613 else if (Ty->isArrayType()) 5614 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 5615 else 5616 return Ty.withoutLocalFastQualifiers(); 5617 } while (true); 5618 } 5619 5620 /// hasSimilarParameters - Determine whether the C++ functions Declaration 5621 /// and Definition have "nearly" matching parameters. This heuristic is 5622 /// used to improve diagnostics in the case where an out-of-line function 5623 /// definition doesn't match any declaration within the class or namespace. 5624 /// Also sets Params to the list of indices to the parameters that differ 5625 /// between the declaration and the definition. If hasSimilarParameters 5626 /// returns true and Params is empty, then all of the parameters match. 5627 static bool hasSimilarParameters(ASTContext &Context, 5628 FunctionDecl *Declaration, 5629 FunctionDecl *Definition, 5630 SmallVectorImpl<unsigned> &Params) { 5631 Params.clear(); 5632 if (Declaration->param_size() != Definition->param_size()) 5633 return false; 5634 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 5635 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 5636 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 5637 5638 // The parameter types are identical 5639 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy)) 5640 continue; 5641 5642 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 5643 QualType DefParamBaseTy = getCoreType(DefParamTy); 5644 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 5645 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 5646 5647 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 5648 (DeclTyName && DeclTyName == DefTyName)) 5649 Params.push_back(Idx); 5650 else // The two parameters aren't even close 5651 return false; 5652 } 5653 5654 return true; 5655 } 5656 5657 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 5658 /// declarator needs to be rebuilt in the current instantiation. 5659 /// Any bits of declarator which appear before the name are valid for 5660 /// consideration here. That's specifically the type in the decl spec 5661 /// and the base type in any member-pointer chunks. 5662 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 5663 DeclarationName Name) { 5664 // The types we specifically need to rebuild are: 5665 // - typenames, typeofs, and decltypes 5666 // - types which will become injected class names 5667 // Of course, we also need to rebuild any type referencing such a 5668 // type. It's safest to just say "dependent", but we call out a 5669 // few cases here. 5670 5671 DeclSpec &DS = D.getMutableDeclSpec(); 5672 switch (DS.getTypeSpecType()) { 5673 case DeclSpec::TST_typename: 5674 case DeclSpec::TST_typeofType: 5675 case DeclSpec::TST_underlyingType: 5676 case DeclSpec::TST_atomic: { 5677 // Grab the type from the parser. 5678 TypeSourceInfo *TSI = nullptr; 5679 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 5680 if (T.isNull() || !T->isInstantiationDependentType()) break; 5681 5682 // Make sure there's a type source info. This isn't really much 5683 // of a waste; most dependent types should have type source info 5684 // attached already. 5685 if (!TSI) 5686 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 5687 5688 // Rebuild the type in the current instantiation. 5689 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 5690 if (!TSI) return true; 5691 5692 // Store the new type back in the decl spec. 5693 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 5694 DS.UpdateTypeRep(LocType); 5695 break; 5696 } 5697 5698 case DeclSpec::TST_decltype: 5699 case DeclSpec::TST_typeofExpr: { 5700 Expr *E = DS.getRepAsExpr(); 5701 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 5702 if (Result.isInvalid()) return true; 5703 DS.UpdateExprRep(Result.get()); 5704 break; 5705 } 5706 5707 default: 5708 // Nothing to do for these decl specs. 5709 break; 5710 } 5711 5712 // It doesn't matter what order we do this in. 5713 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 5714 DeclaratorChunk &Chunk = D.getTypeObject(I); 5715 5716 // The only type information in the declarator which can come 5717 // before the declaration name is the base type of a member 5718 // pointer. 5719 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 5720 continue; 5721 5722 // Rebuild the scope specifier in-place. 5723 CXXScopeSpec &SS = Chunk.Mem.Scope(); 5724 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 5725 return true; 5726 } 5727 5728 return false; 5729 } 5730 5731 /// Returns true if the declaration is declared in a system header or from a 5732 /// system macro. 5733 static bool isFromSystemHeader(SourceManager &SM, const Decl *D) { 5734 return SM.isInSystemHeader(D->getLocation()) || 5735 SM.isInSystemMacro(D->getLocation()); 5736 } 5737 5738 void Sema::warnOnReservedIdentifier(const NamedDecl *D) { 5739 // Avoid warning twice on the same identifier, and don't warn on redeclaration 5740 // of system decl. 5741 if (D->getPreviousDecl() || D->isImplicit()) 5742 return; 5743 ReservedIdentifierStatus Status = D->isReserved(getLangOpts()); 5744 if (Status != ReservedIdentifierStatus::NotReserved && 5745 !isFromSystemHeader(Context.getSourceManager(), D)) { 5746 Diag(D->getLocation(), diag::warn_reserved_extern_symbol) 5747 << D << static_cast<int>(Status); 5748 } 5749 } 5750 5751 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 5752 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration); 5753 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 5754 5755 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 5756 Dcl && Dcl->getDeclContext()->isFileContext()) 5757 Dcl->setTopLevelDeclInObjCContainer(); 5758 5759 return Dcl; 5760 } 5761 5762 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 5763 /// If T is the name of a class, then each of the following shall have a 5764 /// name different from T: 5765 /// - every static data member of class T; 5766 /// - every member function of class T 5767 /// - every member of class T that is itself a type; 5768 /// \returns true if the declaration name violates these rules. 5769 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 5770 DeclarationNameInfo NameInfo) { 5771 DeclarationName Name = NameInfo.getName(); 5772 5773 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 5774 while (Record && Record->isAnonymousStructOrUnion()) 5775 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 5776 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 5777 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 5778 return true; 5779 } 5780 5781 return false; 5782 } 5783 5784 /// Diagnose a declaration whose declarator-id has the given 5785 /// nested-name-specifier. 5786 /// 5787 /// \param SS The nested-name-specifier of the declarator-id. 5788 /// 5789 /// \param DC The declaration context to which the nested-name-specifier 5790 /// resolves. 5791 /// 5792 /// \param Name The name of the entity being declared. 5793 /// 5794 /// \param Loc The location of the name of the entity being declared. 5795 /// 5796 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus 5797 /// we're declaring an explicit / partial specialization / instantiation. 5798 /// 5799 /// \returns true if we cannot safely recover from this error, false otherwise. 5800 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 5801 DeclarationName Name, 5802 SourceLocation Loc, bool IsTemplateId) { 5803 DeclContext *Cur = CurContext; 5804 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 5805 Cur = Cur->getParent(); 5806 5807 // If the user provided a superfluous scope specifier that refers back to the 5808 // class in which the entity is already declared, diagnose and ignore it. 5809 // 5810 // class X { 5811 // void X::f(); 5812 // }; 5813 // 5814 // Note, it was once ill-formed to give redundant qualification in all 5815 // contexts, but that rule was removed by DR482. 5816 if (Cur->Equals(DC)) { 5817 if (Cur->isRecord()) { 5818 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 5819 : diag::err_member_extra_qualification) 5820 << Name << FixItHint::CreateRemoval(SS.getRange()); 5821 SS.clear(); 5822 } else { 5823 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 5824 } 5825 return false; 5826 } 5827 5828 // Check whether the qualifying scope encloses the scope of the original 5829 // declaration. For a template-id, we perform the checks in 5830 // CheckTemplateSpecializationScope. 5831 if (!Cur->Encloses(DC) && !IsTemplateId) { 5832 if (Cur->isRecord()) 5833 Diag(Loc, diag::err_member_qualification) 5834 << Name << SS.getRange(); 5835 else if (isa<TranslationUnitDecl>(DC)) 5836 Diag(Loc, diag::err_invalid_declarator_global_scope) 5837 << Name << SS.getRange(); 5838 else if (isa<FunctionDecl>(Cur)) 5839 Diag(Loc, diag::err_invalid_declarator_in_function) 5840 << Name << SS.getRange(); 5841 else if (isa<BlockDecl>(Cur)) 5842 Diag(Loc, diag::err_invalid_declarator_in_block) 5843 << Name << SS.getRange(); 5844 else if (isa<ExportDecl>(Cur)) { 5845 if (!isa<NamespaceDecl>(DC)) 5846 Diag(Loc, diag::err_export_non_namespace_scope_name) 5847 << Name << SS.getRange(); 5848 else 5849 // The cases that DC is not NamespaceDecl should be handled in 5850 // CheckRedeclarationExported. 5851 return false; 5852 } else 5853 Diag(Loc, diag::err_invalid_declarator_scope) 5854 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 5855 5856 return true; 5857 } 5858 5859 if (Cur->isRecord()) { 5860 // Cannot qualify members within a class. 5861 Diag(Loc, diag::err_member_qualification) 5862 << Name << SS.getRange(); 5863 SS.clear(); 5864 5865 // C++ constructors and destructors with incorrect scopes can break 5866 // our AST invariants by having the wrong underlying types. If 5867 // that's the case, then drop this declaration entirely. 5868 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 5869 Name.getNameKind() == DeclarationName::CXXDestructorName) && 5870 !Context.hasSameType(Name.getCXXNameType(), 5871 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 5872 return true; 5873 5874 return false; 5875 } 5876 5877 // C++11 [dcl.meaning]p1: 5878 // [...] "The nested-name-specifier of the qualified declarator-id shall 5879 // not begin with a decltype-specifer" 5880 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 5881 while (SpecLoc.getPrefix()) 5882 SpecLoc = SpecLoc.getPrefix(); 5883 if (isa_and_nonnull<DecltypeType>( 5884 SpecLoc.getNestedNameSpecifier()->getAsType())) 5885 Diag(Loc, diag::err_decltype_in_declarator) 5886 << SpecLoc.getTypeLoc().getSourceRange(); 5887 5888 return false; 5889 } 5890 5891 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 5892 MultiTemplateParamsArg TemplateParamLists) { 5893 // TODO: consider using NameInfo for diagnostic. 5894 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5895 DeclarationName Name = NameInfo.getName(); 5896 5897 // All of these full declarators require an identifier. If it doesn't have 5898 // one, the ParsedFreeStandingDeclSpec action should be used. 5899 if (D.isDecompositionDeclarator()) { 5900 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 5901 } else if (!Name) { 5902 if (!D.isInvalidType()) // Reject this if we think it is valid. 5903 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident) 5904 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 5905 return nullptr; 5906 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 5907 return nullptr; 5908 5909 // The scope passed in may not be a decl scope. Zip up the scope tree until 5910 // we find one that is. 5911 while ((S->getFlags() & Scope::DeclScope) == 0 || 5912 (S->getFlags() & Scope::TemplateParamScope) != 0) 5913 S = S->getParent(); 5914 5915 DeclContext *DC = CurContext; 5916 if (D.getCXXScopeSpec().isInvalid()) 5917 D.setInvalidType(); 5918 else if (D.getCXXScopeSpec().isSet()) { 5919 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 5920 UPPC_DeclarationQualifier)) 5921 return nullptr; 5922 5923 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 5924 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 5925 if (!DC || isa<EnumDecl>(DC)) { 5926 // If we could not compute the declaration context, it's because the 5927 // declaration context is dependent but does not refer to a class, 5928 // class template, or class template partial specialization. Complain 5929 // and return early, to avoid the coming semantic disaster. 5930 Diag(D.getIdentifierLoc(), 5931 diag::err_template_qualified_declarator_no_match) 5932 << D.getCXXScopeSpec().getScopeRep() 5933 << D.getCXXScopeSpec().getRange(); 5934 return nullptr; 5935 } 5936 bool IsDependentContext = DC->isDependentContext(); 5937 5938 if (!IsDependentContext && 5939 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 5940 return nullptr; 5941 5942 // If a class is incomplete, do not parse entities inside it. 5943 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 5944 Diag(D.getIdentifierLoc(), 5945 diag::err_member_def_undefined_record) 5946 << Name << DC << D.getCXXScopeSpec().getRange(); 5947 return nullptr; 5948 } 5949 if (!D.getDeclSpec().isFriendSpecified()) { 5950 if (diagnoseQualifiedDeclaration( 5951 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(), 5952 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) { 5953 if (DC->isRecord()) 5954 return nullptr; 5955 5956 D.setInvalidType(); 5957 } 5958 } 5959 5960 // Check whether we need to rebuild the type of the given 5961 // declaration in the current instantiation. 5962 if (EnteringContext && IsDependentContext && 5963 TemplateParamLists.size() != 0) { 5964 ContextRAII SavedContext(*this, DC); 5965 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 5966 D.setInvalidType(); 5967 } 5968 } 5969 5970 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5971 QualType R = TInfo->getType(); 5972 5973 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 5974 UPPC_DeclarationType)) 5975 D.setInvalidType(); 5976 5977 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5978 forRedeclarationInCurContext()); 5979 5980 // See if this is a redefinition of a variable in the same scope. 5981 if (!D.getCXXScopeSpec().isSet()) { 5982 bool IsLinkageLookup = false; 5983 bool CreateBuiltins = false; 5984 5985 // If the declaration we're planning to build will be a function 5986 // or object with linkage, then look for another declaration with 5987 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 5988 // 5989 // If the declaration we're planning to build will be declared with 5990 // external linkage in the translation unit, create any builtin with 5991 // the same name. 5992 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5993 /* Do nothing*/; 5994 else if (CurContext->isFunctionOrMethod() && 5995 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 5996 R->isFunctionType())) { 5997 IsLinkageLookup = true; 5998 CreateBuiltins = 5999 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 6000 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 6001 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 6002 CreateBuiltins = true; 6003 6004 if (IsLinkageLookup) { 6005 Previous.clear(LookupRedeclarationWithLinkage); 6006 Previous.setRedeclarationKind(ForExternalRedeclaration); 6007 } 6008 6009 LookupName(Previous, S, CreateBuiltins); 6010 } else { // Something like "int foo::x;" 6011 LookupQualifiedName(Previous, DC); 6012 6013 // C++ [dcl.meaning]p1: 6014 // When the declarator-id is qualified, the declaration shall refer to a 6015 // previously declared member of the class or namespace to which the 6016 // qualifier refers (or, in the case of a namespace, of an element of the 6017 // inline namespace set of that namespace (7.3.1)) or to a specialization 6018 // thereof; [...] 6019 // 6020 // Note that we already checked the context above, and that we do not have 6021 // enough information to make sure that Previous contains the declaration 6022 // we want to match. For example, given: 6023 // 6024 // class X { 6025 // void f(); 6026 // void f(float); 6027 // }; 6028 // 6029 // void X::f(int) { } // ill-formed 6030 // 6031 // In this case, Previous will point to the overload set 6032 // containing the two f's declared in X, but neither of them 6033 // matches. 6034 6035 // C++ [dcl.meaning]p1: 6036 // [...] the member shall not merely have been introduced by a 6037 // using-declaration in the scope of the class or namespace nominated by 6038 // the nested-name-specifier of the declarator-id. 6039 RemoveUsingDecls(Previous); 6040 } 6041 6042 if (Previous.isSingleResult() && 6043 Previous.getFoundDecl()->isTemplateParameter()) { 6044 // Maybe we will complain about the shadowed template parameter. 6045 if (!D.isInvalidType()) 6046 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 6047 Previous.getFoundDecl()); 6048 6049 // Just pretend that we didn't see the previous declaration. 6050 Previous.clear(); 6051 } 6052 6053 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 6054 // Forget that the previous declaration is the injected-class-name. 6055 Previous.clear(); 6056 6057 // In C++, the previous declaration we find might be a tag type 6058 // (class or enum). In this case, the new declaration will hide the 6059 // tag type. Note that this applies to functions, function templates, and 6060 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. 6061 if (Previous.isSingleTagDecl() && 6062 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 6063 (TemplateParamLists.size() == 0 || R->isFunctionType())) 6064 Previous.clear(); 6065 6066 // Check that there are no default arguments other than in the parameters 6067 // of a function declaration (C++ only). 6068 if (getLangOpts().CPlusPlus) 6069 CheckExtraCXXDefaultArguments(D); 6070 6071 NamedDecl *New; 6072 6073 bool AddToScope = true; 6074 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 6075 if (TemplateParamLists.size()) { 6076 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 6077 return nullptr; 6078 } 6079 6080 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 6081 } else if (R->isFunctionType()) { 6082 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 6083 TemplateParamLists, 6084 AddToScope); 6085 } else { 6086 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 6087 AddToScope); 6088 } 6089 6090 if (!New) 6091 return nullptr; 6092 6093 // If this has an identifier and is not a function template specialization, 6094 // add it to the scope stack. 6095 if (New->getDeclName() && AddToScope) 6096 PushOnScopeChains(New, S); 6097 6098 if (isInOpenMPDeclareTargetContext()) 6099 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 6100 6101 return New; 6102 } 6103 6104 /// Helper method to turn variable array types into constant array 6105 /// types in certain situations which would otherwise be errors (for 6106 /// GCC compatibility). 6107 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 6108 ASTContext &Context, 6109 bool &SizeIsNegative, 6110 llvm::APSInt &Oversized) { 6111 // This method tries to turn a variable array into a constant 6112 // array even when the size isn't an ICE. This is necessary 6113 // for compatibility with code that depends on gcc's buggy 6114 // constant expression folding, like struct {char x[(int)(char*)2];} 6115 SizeIsNegative = false; 6116 Oversized = 0; 6117 6118 if (T->isDependentType()) 6119 return QualType(); 6120 6121 QualifierCollector Qs; 6122 const Type *Ty = Qs.strip(T); 6123 6124 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 6125 QualType Pointee = PTy->getPointeeType(); 6126 QualType FixedType = 6127 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 6128 Oversized); 6129 if (FixedType.isNull()) return FixedType; 6130 FixedType = Context.getPointerType(FixedType); 6131 return Qs.apply(Context, FixedType); 6132 } 6133 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 6134 QualType Inner = PTy->getInnerType(); 6135 QualType FixedType = 6136 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 6137 Oversized); 6138 if (FixedType.isNull()) return FixedType; 6139 FixedType = Context.getParenType(FixedType); 6140 return Qs.apply(Context, FixedType); 6141 } 6142 6143 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 6144 if (!VLATy) 6145 return QualType(); 6146 6147 QualType ElemTy = VLATy->getElementType(); 6148 if (ElemTy->isVariablyModifiedType()) { 6149 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context, 6150 SizeIsNegative, Oversized); 6151 if (ElemTy.isNull()) 6152 return QualType(); 6153 } 6154 6155 Expr::EvalResult Result; 6156 if (!VLATy->getSizeExpr() || 6157 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context)) 6158 return QualType(); 6159 6160 llvm::APSInt Res = Result.Val.getInt(); 6161 6162 // Check whether the array size is negative. 6163 if (Res.isSigned() && Res.isNegative()) { 6164 SizeIsNegative = true; 6165 return QualType(); 6166 } 6167 6168 // Check whether the array is too large to be addressed. 6169 unsigned ActiveSizeBits = 6170 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() && 6171 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType()) 6172 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res) 6173 : Res.getActiveBits(); 6174 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 6175 Oversized = Res; 6176 return QualType(); 6177 } 6178 6179 QualType FoldedArrayType = Context.getConstantArrayType( 6180 ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0); 6181 return Qs.apply(Context, FoldedArrayType); 6182 } 6183 6184 static void 6185 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 6186 SrcTL = SrcTL.getUnqualifiedLoc(); 6187 DstTL = DstTL.getUnqualifiedLoc(); 6188 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 6189 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 6190 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 6191 DstPTL.getPointeeLoc()); 6192 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 6193 return; 6194 } 6195 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 6196 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 6197 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 6198 DstPTL.getInnerLoc()); 6199 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 6200 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 6201 return; 6202 } 6203 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 6204 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 6205 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 6206 TypeLoc DstElemTL = DstATL.getElementLoc(); 6207 if (VariableArrayTypeLoc SrcElemATL = 6208 SrcElemTL.getAs<VariableArrayTypeLoc>()) { 6209 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>(); 6210 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL); 6211 } else { 6212 DstElemTL.initializeFullCopy(SrcElemTL); 6213 } 6214 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 6215 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 6216 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 6217 } 6218 6219 /// Helper method to turn variable array types into constant array 6220 /// types in certain situations which would otherwise be errors (for 6221 /// GCC compatibility). 6222 static TypeSourceInfo* 6223 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 6224 ASTContext &Context, 6225 bool &SizeIsNegative, 6226 llvm::APSInt &Oversized) { 6227 QualType FixedTy 6228 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 6229 SizeIsNegative, Oversized); 6230 if (FixedTy.isNull()) 6231 return nullptr; 6232 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 6233 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 6234 FixedTInfo->getTypeLoc()); 6235 return FixedTInfo; 6236 } 6237 6238 /// Attempt to fold a variable-sized type to a constant-sized type, returning 6239 /// true if we were successful. 6240 bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, 6241 QualType &T, SourceLocation Loc, 6242 unsigned FailedFoldDiagID) { 6243 bool SizeIsNegative; 6244 llvm::APSInt Oversized; 6245 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 6246 TInfo, Context, SizeIsNegative, Oversized); 6247 if (FixedTInfo) { 6248 Diag(Loc, diag::ext_vla_folded_to_constant); 6249 TInfo = FixedTInfo; 6250 T = FixedTInfo->getType(); 6251 return true; 6252 } 6253 6254 if (SizeIsNegative) 6255 Diag(Loc, diag::err_typecheck_negative_array_size); 6256 else if (Oversized.getBoolValue()) 6257 Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10); 6258 else if (FailedFoldDiagID) 6259 Diag(Loc, FailedFoldDiagID); 6260 return false; 6261 } 6262 6263 /// Register the given locally-scoped extern "C" declaration so 6264 /// that it can be found later for redeclarations. We include any extern "C" 6265 /// declaration that is not visible in the translation unit here, not just 6266 /// function-scope declarations. 6267 void 6268 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 6269 if (!getLangOpts().CPlusPlus && 6270 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 6271 // Don't need to track declarations in the TU in C. 6272 return; 6273 6274 // Note that we have a locally-scoped external with this name. 6275 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 6276 } 6277 6278 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 6279 // FIXME: We can have multiple results via __attribute__((overloadable)). 6280 auto Result = Context.getExternCContextDecl()->lookup(Name); 6281 return Result.empty() ? nullptr : *Result.begin(); 6282 } 6283 6284 /// Diagnose function specifiers on a declaration of an identifier that 6285 /// does not identify a function. 6286 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 6287 // FIXME: We should probably indicate the identifier in question to avoid 6288 // confusion for constructs like "virtual int a(), b;" 6289 if (DS.isVirtualSpecified()) 6290 Diag(DS.getVirtualSpecLoc(), 6291 diag::err_virtual_non_function); 6292 6293 if (DS.hasExplicitSpecifier()) 6294 Diag(DS.getExplicitSpecLoc(), 6295 diag::err_explicit_non_function); 6296 6297 if (DS.isNoreturnSpecified()) 6298 Diag(DS.getNoreturnSpecLoc(), 6299 diag::err_noreturn_non_function); 6300 } 6301 6302 NamedDecl* 6303 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 6304 TypeSourceInfo *TInfo, LookupResult &Previous) { 6305 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 6306 if (D.getCXXScopeSpec().isSet()) { 6307 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 6308 << D.getCXXScopeSpec().getRange(); 6309 D.setInvalidType(); 6310 // Pretend we didn't see the scope specifier. 6311 DC = CurContext; 6312 Previous.clear(); 6313 } 6314 6315 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6316 6317 if (D.getDeclSpec().isInlineSpecified()) 6318 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6319 << getLangOpts().CPlusPlus17; 6320 if (D.getDeclSpec().hasConstexprSpecifier()) 6321 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 6322 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 6323 6324 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) { 6325 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName) 6326 Diag(D.getName().StartLocation, 6327 diag::err_deduction_guide_invalid_specifier) 6328 << "typedef"; 6329 else 6330 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 6331 << D.getName().getSourceRange(); 6332 return nullptr; 6333 } 6334 6335 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 6336 if (!NewTD) return nullptr; 6337 6338 // Handle attributes prior to checking for duplicates in MergeVarDecl 6339 ProcessDeclAttributes(S, NewTD, D); 6340 6341 CheckTypedefForVariablyModifiedType(S, NewTD); 6342 6343 bool Redeclaration = D.isRedeclaration(); 6344 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 6345 D.setRedeclaration(Redeclaration); 6346 return ND; 6347 } 6348 6349 void 6350 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 6351 // C99 6.7.7p2: If a typedef name specifies a variably modified type 6352 // then it shall have block scope. 6353 // Note that variably modified types must be fixed before merging the decl so 6354 // that redeclarations will match. 6355 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 6356 QualType T = TInfo->getType(); 6357 if (T->isVariablyModifiedType()) { 6358 setFunctionHasBranchProtectedScope(); 6359 6360 if (S->getFnParent() == nullptr) { 6361 bool SizeIsNegative; 6362 llvm::APSInt Oversized; 6363 TypeSourceInfo *FixedTInfo = 6364 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 6365 SizeIsNegative, 6366 Oversized); 6367 if (FixedTInfo) { 6368 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant); 6369 NewTD->setTypeSourceInfo(FixedTInfo); 6370 } else { 6371 if (SizeIsNegative) 6372 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 6373 else if (T->isVariableArrayType()) 6374 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 6375 else if (Oversized.getBoolValue()) 6376 Diag(NewTD->getLocation(), diag::err_array_too_large) 6377 << toString(Oversized, 10); 6378 else 6379 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 6380 NewTD->setInvalidDecl(); 6381 } 6382 } 6383 } 6384 } 6385 6386 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 6387 /// declares a typedef-name, either using the 'typedef' type specifier or via 6388 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 6389 NamedDecl* 6390 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 6391 LookupResult &Previous, bool &Redeclaration) { 6392 6393 // Find the shadowed declaration before filtering for scope. 6394 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); 6395 6396 // Merge the decl with the existing one if appropriate. If the decl is 6397 // in an outer scope, it isn't the same thing. 6398 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 6399 /*AllowInlineNamespace*/false); 6400 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 6401 if (!Previous.empty()) { 6402 Redeclaration = true; 6403 MergeTypedefNameDecl(S, NewTD, Previous); 6404 } else { 6405 inferGslPointerAttribute(NewTD); 6406 } 6407 6408 if (ShadowedDecl && !Redeclaration) 6409 CheckShadow(NewTD, ShadowedDecl, Previous); 6410 6411 // If this is the C FILE type, notify the AST context. 6412 if (IdentifierInfo *II = NewTD->getIdentifier()) 6413 if (!NewTD->isInvalidDecl() && 6414 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 6415 if (II->isStr("FILE")) 6416 Context.setFILEDecl(NewTD); 6417 else if (II->isStr("jmp_buf")) 6418 Context.setjmp_bufDecl(NewTD); 6419 else if (II->isStr("sigjmp_buf")) 6420 Context.setsigjmp_bufDecl(NewTD); 6421 else if (II->isStr("ucontext_t")) 6422 Context.setucontext_tDecl(NewTD); 6423 } 6424 6425 return NewTD; 6426 } 6427 6428 /// Determines whether the given declaration is an out-of-scope 6429 /// previous declaration. 6430 /// 6431 /// This routine should be invoked when name lookup has found a 6432 /// previous declaration (PrevDecl) that is not in the scope where a 6433 /// new declaration by the same name is being introduced. If the new 6434 /// declaration occurs in a local scope, previous declarations with 6435 /// linkage may still be considered previous declarations (C99 6436 /// 6.2.2p4-5, C++ [basic.link]p6). 6437 /// 6438 /// \param PrevDecl the previous declaration found by name 6439 /// lookup 6440 /// 6441 /// \param DC the context in which the new declaration is being 6442 /// declared. 6443 /// 6444 /// \returns true if PrevDecl is an out-of-scope previous declaration 6445 /// for a new delcaration with the same name. 6446 static bool 6447 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 6448 ASTContext &Context) { 6449 if (!PrevDecl) 6450 return false; 6451 6452 if (!PrevDecl->hasLinkage()) 6453 return false; 6454 6455 if (Context.getLangOpts().CPlusPlus) { 6456 // C++ [basic.link]p6: 6457 // If there is a visible declaration of an entity with linkage 6458 // having the same name and type, ignoring entities declared 6459 // outside the innermost enclosing namespace scope, the block 6460 // scope declaration declares that same entity and receives the 6461 // linkage of the previous declaration. 6462 DeclContext *OuterContext = DC->getRedeclContext(); 6463 if (!OuterContext->isFunctionOrMethod()) 6464 // This rule only applies to block-scope declarations. 6465 return false; 6466 6467 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 6468 if (PrevOuterContext->isRecord()) 6469 // We found a member function: ignore it. 6470 return false; 6471 6472 // Find the innermost enclosing namespace for the new and 6473 // previous declarations. 6474 OuterContext = OuterContext->getEnclosingNamespaceContext(); 6475 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 6476 6477 // The previous declaration is in a different namespace, so it 6478 // isn't the same function. 6479 if (!OuterContext->Equals(PrevOuterContext)) 6480 return false; 6481 } 6482 6483 return true; 6484 } 6485 6486 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) { 6487 CXXScopeSpec &SS = D.getCXXScopeSpec(); 6488 if (!SS.isSet()) return; 6489 DD->setQualifierInfo(SS.getWithLocInContext(S.Context)); 6490 } 6491 6492 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 6493 QualType type = decl->getType(); 6494 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 6495 if (lifetime == Qualifiers::OCL_Autoreleasing) { 6496 // Various kinds of declaration aren't allowed to be __autoreleasing. 6497 unsigned kind = -1U; 6498 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6499 if (var->hasAttr<BlocksAttr>()) 6500 kind = 0; // __block 6501 else if (!var->hasLocalStorage()) 6502 kind = 1; // global 6503 } else if (isa<ObjCIvarDecl>(decl)) { 6504 kind = 3; // ivar 6505 } else if (isa<FieldDecl>(decl)) { 6506 kind = 2; // field 6507 } 6508 6509 if (kind != -1U) { 6510 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 6511 << kind; 6512 } 6513 } else if (lifetime == Qualifiers::OCL_None) { 6514 // Try to infer lifetime. 6515 if (!type->isObjCLifetimeType()) 6516 return false; 6517 6518 lifetime = type->getObjCARCImplicitLifetime(); 6519 type = Context.getLifetimeQualifiedType(type, lifetime); 6520 decl->setType(type); 6521 } 6522 6523 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6524 // Thread-local variables cannot have lifetime. 6525 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 6526 var->getTLSKind()) { 6527 Diag(var->getLocation(), diag::err_arc_thread_ownership) 6528 << var->getType(); 6529 return true; 6530 } 6531 } 6532 6533 return false; 6534 } 6535 6536 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) { 6537 if (Decl->getType().hasAddressSpace()) 6538 return; 6539 if (Decl->getType()->isDependentType()) 6540 return; 6541 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) { 6542 QualType Type = Var->getType(); 6543 if (Type->isSamplerT() || Type->isVoidType()) 6544 return; 6545 LangAS ImplAS = LangAS::opencl_private; 6546 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the 6547 // __opencl_c_program_scope_global_variables feature, the address space 6548 // for a variable at program scope or a static or extern variable inside 6549 // a function are inferred to be __global. 6550 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) && 6551 Var->hasGlobalStorage()) 6552 ImplAS = LangAS::opencl_global; 6553 // If the original type from a decayed type is an array type and that array 6554 // type has no address space yet, deduce it now. 6555 if (auto DT = dyn_cast<DecayedType>(Type)) { 6556 auto OrigTy = DT->getOriginalType(); 6557 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) { 6558 // Add the address space to the original array type and then propagate 6559 // that to the element type through `getAsArrayType`. 6560 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS); 6561 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0); 6562 // Re-generate the decayed type. 6563 Type = Context.getDecayedType(OrigTy); 6564 } 6565 } 6566 Type = Context.getAddrSpaceQualType(Type, ImplAS); 6567 // Apply any qualifiers (including address space) from the array type to 6568 // the element type. This implements C99 6.7.3p8: "If the specification of 6569 // an array type includes any type qualifiers, the element type is so 6570 // qualified, not the array type." 6571 if (Type->isArrayType()) 6572 Type = QualType(Context.getAsArrayType(Type), 0); 6573 Decl->setType(Type); 6574 } 6575 } 6576 6577 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 6578 // Ensure that an auto decl is deduced otherwise the checks below might cache 6579 // the wrong linkage. 6580 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 6581 6582 // 'weak' only applies to declarations with external linkage. 6583 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 6584 if (!ND.isExternallyVisible()) { 6585 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 6586 ND.dropAttr<WeakAttr>(); 6587 } 6588 } 6589 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 6590 if (ND.isExternallyVisible()) { 6591 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 6592 ND.dropAttr<WeakRefAttr>(); 6593 ND.dropAttr<AliasAttr>(); 6594 } 6595 } 6596 6597 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 6598 if (VD->hasInit()) { 6599 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 6600 assert(VD->isThisDeclarationADefinition() && 6601 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 6602 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 6603 VD->dropAttr<AliasAttr>(); 6604 } 6605 } 6606 } 6607 6608 // 'selectany' only applies to externally visible variable declarations. 6609 // It does not apply to functions. 6610 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 6611 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 6612 S.Diag(Attr->getLocation(), 6613 diag::err_attribute_selectany_non_extern_data); 6614 ND.dropAttr<SelectAnyAttr>(); 6615 } 6616 } 6617 6618 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 6619 auto *VD = dyn_cast<VarDecl>(&ND); 6620 bool IsAnonymousNS = false; 6621 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6622 if (VD) { 6623 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext()); 6624 while (NS && !IsAnonymousNS) { 6625 IsAnonymousNS = NS->isAnonymousNamespace(); 6626 NS = dyn_cast<NamespaceDecl>(NS->getParent()); 6627 } 6628 } 6629 // dll attributes require external linkage. Static locals may have external 6630 // linkage but still cannot be explicitly imported or exported. 6631 // In Microsoft mode, a variable defined in anonymous namespace must have 6632 // external linkage in order to be exported. 6633 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft; 6634 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) || 6635 (!AnonNSInMicrosoftMode && 6636 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) { 6637 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 6638 << &ND << Attr; 6639 ND.setInvalidDecl(); 6640 } 6641 } 6642 6643 // Check the attributes on the function type, if any. 6644 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) { 6645 // Don't declare this variable in the second operand of the for-statement; 6646 // GCC miscompiles that by ending its lifetime before evaluating the 6647 // third operand. See gcc.gnu.org/PR86769. 6648 AttributedTypeLoc ATL; 6649 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc(); 6650 (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); 6651 TL = ATL.getModifiedLoc()) { 6652 // The [[lifetimebound]] attribute can be applied to the implicit object 6653 // parameter of a non-static member function (other than a ctor or dtor) 6654 // by applying it to the function type. 6655 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) { 6656 const auto *MD = dyn_cast<CXXMethodDecl>(FD); 6657 if (!MD || MD->isStatic()) { 6658 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param) 6659 << !MD << A->getRange(); 6660 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) { 6661 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor) 6662 << isa<CXXDestructorDecl>(MD) << A->getRange(); 6663 } 6664 } 6665 } 6666 } 6667 } 6668 6669 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 6670 NamedDecl *NewDecl, 6671 bool IsSpecialization, 6672 bool IsDefinition) { 6673 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl()) 6674 return; 6675 6676 bool IsTemplate = false; 6677 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 6678 OldDecl = OldTD->getTemplatedDecl(); 6679 IsTemplate = true; 6680 if (!IsSpecialization) 6681 IsDefinition = false; 6682 } 6683 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { 6684 NewDecl = NewTD->getTemplatedDecl(); 6685 IsTemplate = true; 6686 } 6687 6688 if (!OldDecl || !NewDecl) 6689 return; 6690 6691 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 6692 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 6693 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 6694 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 6695 6696 // dllimport and dllexport are inheritable attributes so we have to exclude 6697 // inherited attribute instances. 6698 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 6699 (NewExportAttr && !NewExportAttr->isInherited()); 6700 6701 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 6702 // the only exception being explicit specializations. 6703 // Implicitly generated declarations are also excluded for now because there 6704 // is no other way to switch these to use dllimport or dllexport. 6705 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 6706 6707 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 6708 // Allow with a warning for free functions and global variables. 6709 bool JustWarn = false; 6710 if (!OldDecl->isCXXClassMember()) { 6711 auto *VD = dyn_cast<VarDecl>(OldDecl); 6712 if (VD && !VD->getDescribedVarTemplate()) 6713 JustWarn = true; 6714 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 6715 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 6716 JustWarn = true; 6717 } 6718 6719 // We cannot change a declaration that's been used because IR has already 6720 // been emitted. Dllimported functions will still work though (modulo 6721 // address equality) as they can use the thunk. 6722 if (OldDecl->isUsed()) 6723 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 6724 JustWarn = false; 6725 6726 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 6727 : diag::err_attribute_dll_redeclaration; 6728 S.Diag(NewDecl->getLocation(), DiagID) 6729 << NewDecl 6730 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 6731 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6732 if (!JustWarn) { 6733 NewDecl->setInvalidDecl(); 6734 return; 6735 } 6736 } 6737 6738 // A redeclaration is not allowed to drop a dllimport attribute, the only 6739 // exceptions being inline function definitions (except for function 6740 // templates), local extern declarations, qualified friend declarations or 6741 // special MSVC extension: in the last case, the declaration is treated as if 6742 // it were marked dllexport. 6743 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 6744 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols(); 6745 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 6746 // Ignore static data because out-of-line definitions are diagnosed 6747 // separately. 6748 IsStaticDataMember = VD->isStaticDataMember(); 6749 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 6750 VarDecl::DeclarationOnly; 6751 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 6752 IsInline = FD->isInlined(); 6753 IsQualifiedFriend = FD->getQualifier() && 6754 FD->getFriendObjectKind() == Decl::FOK_Declared; 6755 } 6756 6757 if (OldImportAttr && !HasNewAttr && 6758 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember && 6759 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 6760 if (IsMicrosoftABI && IsDefinition) { 6761 S.Diag(NewDecl->getLocation(), 6762 diag::warn_redeclaration_without_import_attribute) 6763 << NewDecl; 6764 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6765 NewDecl->dropAttr<DLLImportAttr>(); 6766 NewDecl->addAttr( 6767 DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange())); 6768 } else { 6769 S.Diag(NewDecl->getLocation(), 6770 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 6771 << NewDecl << OldImportAttr; 6772 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6773 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 6774 OldDecl->dropAttr<DLLImportAttr>(); 6775 NewDecl->dropAttr<DLLImportAttr>(); 6776 } 6777 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) { 6778 // In MinGW, seeing a function declared inline drops the dllimport 6779 // attribute. 6780 OldDecl->dropAttr<DLLImportAttr>(); 6781 NewDecl->dropAttr<DLLImportAttr>(); 6782 S.Diag(NewDecl->getLocation(), 6783 diag::warn_dllimport_dropped_from_inline_function) 6784 << NewDecl << OldImportAttr; 6785 } 6786 6787 // A specialization of a class template member function is processed here 6788 // since it's a redeclaration. If the parent class is dllexport, the 6789 // specialization inherits that attribute. This doesn't happen automatically 6790 // since the parent class isn't instantiated until later. 6791 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) { 6792 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && 6793 !NewImportAttr && !NewExportAttr) { 6794 if (const DLLExportAttr *ParentExportAttr = 6795 MD->getParent()->getAttr<DLLExportAttr>()) { 6796 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context); 6797 NewAttr->setInherited(true); 6798 NewDecl->addAttr(NewAttr); 6799 } 6800 } 6801 } 6802 } 6803 6804 /// Given that we are within the definition of the given function, 6805 /// will that definition behave like C99's 'inline', where the 6806 /// definition is discarded except for optimization purposes? 6807 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 6808 // Try to avoid calling GetGVALinkageForFunction. 6809 6810 // All cases of this require the 'inline' keyword. 6811 if (!FD->isInlined()) return false; 6812 6813 // This is only possible in C++ with the gnu_inline attribute. 6814 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 6815 return false; 6816 6817 // Okay, go ahead and call the relatively-more-expensive function. 6818 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 6819 } 6820 6821 /// Determine whether a variable is extern "C" prior to attaching 6822 /// an initializer. We can't just call isExternC() here, because that 6823 /// will also compute and cache whether the declaration is externally 6824 /// visible, which might change when we attach the initializer. 6825 /// 6826 /// This can only be used if the declaration is known to not be a 6827 /// redeclaration of an internal linkage declaration. 6828 /// 6829 /// For instance: 6830 /// 6831 /// auto x = []{}; 6832 /// 6833 /// Attaching the initializer here makes this declaration not externally 6834 /// visible, because its type has internal linkage. 6835 /// 6836 /// FIXME: This is a hack. 6837 template<typename T> 6838 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 6839 if (S.getLangOpts().CPlusPlus) { 6840 // In C++, the overloadable attribute negates the effects of extern "C". 6841 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 6842 return false; 6843 6844 // So do CUDA's host/device attributes. 6845 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 6846 D->template hasAttr<CUDAHostAttr>())) 6847 return false; 6848 } 6849 return D->isExternC(); 6850 } 6851 6852 static bool shouldConsiderLinkage(const VarDecl *VD) { 6853 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 6854 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) || 6855 isa<OMPDeclareMapperDecl>(DC)) 6856 return VD->hasExternalStorage(); 6857 if (DC->isFileContext()) 6858 return true; 6859 if (DC->isRecord()) 6860 return false; 6861 if (isa<RequiresExprBodyDecl>(DC)) 6862 return false; 6863 llvm_unreachable("Unexpected context"); 6864 } 6865 6866 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 6867 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 6868 if (DC->isFileContext() || DC->isFunctionOrMethod() || 6869 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC)) 6870 return true; 6871 if (DC->isRecord()) 6872 return false; 6873 llvm_unreachable("Unexpected context"); 6874 } 6875 6876 static bool hasParsedAttr(Scope *S, const Declarator &PD, 6877 ParsedAttr::Kind Kind) { 6878 // Check decl attributes on the DeclSpec. 6879 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind)) 6880 return true; 6881 6882 // Walk the declarator structure, checking decl attributes that were in a type 6883 // position to the decl itself. 6884 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 6885 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind)) 6886 return true; 6887 } 6888 6889 // Finally, check attributes on the decl itself. 6890 return PD.getAttributes().hasAttribute(Kind); 6891 } 6892 6893 /// Adjust the \c DeclContext for a function or variable that might be a 6894 /// function-local external declaration. 6895 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 6896 if (!DC->isFunctionOrMethod()) 6897 return false; 6898 6899 // If this is a local extern function or variable declared within a function 6900 // template, don't add it into the enclosing namespace scope until it is 6901 // instantiated; it might have a dependent type right now. 6902 if (DC->isDependentContext()) 6903 return true; 6904 6905 // C++11 [basic.link]p7: 6906 // When a block scope declaration of an entity with linkage is not found to 6907 // refer to some other declaration, then that entity is a member of the 6908 // innermost enclosing namespace. 6909 // 6910 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 6911 // semantically-enclosing namespace, not a lexically-enclosing one. 6912 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 6913 DC = DC->getParent(); 6914 return true; 6915 } 6916 6917 /// Returns true if given declaration has external C language linkage. 6918 static bool isDeclExternC(const Decl *D) { 6919 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 6920 return FD->isExternC(); 6921 if (const auto *VD = dyn_cast<VarDecl>(D)) 6922 return VD->isExternC(); 6923 6924 llvm_unreachable("Unknown type of decl!"); 6925 } 6926 6927 /// Returns true if there hasn't been any invalid type diagnosed. 6928 static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) { 6929 DeclContext *DC = NewVD->getDeclContext(); 6930 QualType R = NewVD->getType(); 6931 6932 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 6933 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 6934 // argument. 6935 if (R->isImageType() || R->isPipeType()) { 6936 Se.Diag(NewVD->getLocation(), 6937 diag::err_opencl_type_can_only_be_used_as_function_parameter) 6938 << R; 6939 NewVD->setInvalidDecl(); 6940 return false; 6941 } 6942 6943 // OpenCL v1.2 s6.9.r: 6944 // The event type cannot be used to declare a program scope variable. 6945 // OpenCL v2.0 s6.9.q: 6946 // The clk_event_t and reserve_id_t types cannot be declared in program 6947 // scope. 6948 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) { 6949 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 6950 Se.Diag(NewVD->getLocation(), 6951 diag::err_invalid_type_for_program_scope_var) 6952 << R; 6953 NewVD->setInvalidDecl(); 6954 return false; 6955 } 6956 } 6957 6958 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 6959 if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers", 6960 Se.getLangOpts())) { 6961 QualType NR = R.getCanonicalType(); 6962 while (NR->isPointerType() || NR->isMemberFunctionPointerType() || 6963 NR->isReferenceType()) { 6964 if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() || 6965 NR->isFunctionReferenceType()) { 6966 Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer) 6967 << NR->isReferenceType(); 6968 NewVD->setInvalidDecl(); 6969 return false; 6970 } 6971 NR = NR->getPointeeType(); 6972 } 6973 } 6974 6975 if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16", 6976 Se.getLangOpts())) { 6977 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 6978 // half array type (unless the cl_khr_fp16 extension is enabled). 6979 if (Se.Context.getBaseElementType(R)->isHalfType()) { 6980 Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R; 6981 NewVD->setInvalidDecl(); 6982 return false; 6983 } 6984 } 6985 6986 // OpenCL v1.2 s6.9.r: 6987 // The event type cannot be used with the __local, __constant and __global 6988 // address space qualifiers. 6989 if (R->isEventT()) { 6990 if (R.getAddressSpace() != LangAS::opencl_private) { 6991 Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual); 6992 NewVD->setInvalidDecl(); 6993 return false; 6994 } 6995 } 6996 6997 if (R->isSamplerT()) { 6998 // OpenCL v1.2 s6.9.b p4: 6999 // The sampler type cannot be used with the __local and __global address 7000 // space qualifiers. 7001 if (R.getAddressSpace() == LangAS::opencl_local || 7002 R.getAddressSpace() == LangAS::opencl_global) { 7003 Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace); 7004 NewVD->setInvalidDecl(); 7005 } 7006 7007 // OpenCL v1.2 s6.12.14.1: 7008 // A global sampler must be declared with either the constant address 7009 // space qualifier or with the const qualifier. 7010 if (DC->isTranslationUnit() && 7011 !(R.getAddressSpace() == LangAS::opencl_constant || 7012 R.isConstQualified())) { 7013 Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler); 7014 NewVD->setInvalidDecl(); 7015 } 7016 if (NewVD->isInvalidDecl()) 7017 return false; 7018 } 7019 7020 return true; 7021 } 7022 7023 template <typename AttrTy> 7024 static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) { 7025 const TypedefNameDecl *TND = TT->getDecl(); 7026 if (const auto *Attribute = TND->getAttr<AttrTy>()) { 7027 AttrTy *Clone = Attribute->clone(S.Context); 7028 Clone->setInherited(true); 7029 D->addAttr(Clone); 7030 } 7031 } 7032 7033 NamedDecl *Sema::ActOnVariableDeclarator( 7034 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 7035 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 7036 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 7037 QualType R = TInfo->getType(); 7038 DeclarationName Name = GetNameForDeclarator(D).getName(); 7039 7040 IdentifierInfo *II = Name.getAsIdentifierInfo(); 7041 7042 if (D.isDecompositionDeclarator()) { 7043 // Take the name of the first declarator as our name for diagnostic 7044 // purposes. 7045 auto &Decomp = D.getDecompositionDeclarator(); 7046 if (!Decomp.bindings().empty()) { 7047 II = Decomp.bindings()[0].Name; 7048 Name = II; 7049 } 7050 } else if (!II) { 7051 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; 7052 return nullptr; 7053 } 7054 7055 7056 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 7057 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 7058 7059 // dllimport globals without explicit storage class are treated as extern. We 7060 // have to change the storage class this early to get the right DeclContext. 7061 if (SC == SC_None && !DC->isRecord() && 7062 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) && 7063 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport)) 7064 SC = SC_Extern; 7065 7066 DeclContext *OriginalDC = DC; 7067 bool IsLocalExternDecl = SC == SC_Extern && 7068 adjustContextForLocalExternDecl(DC); 7069 7070 if (SCSpec == DeclSpec::SCS_mutable) { 7071 // mutable can only appear on non-static class members, so it's always 7072 // an error here 7073 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 7074 D.setInvalidType(); 7075 SC = SC_None; 7076 } 7077 7078 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 7079 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 7080 D.getDeclSpec().getStorageClassSpecLoc())) { 7081 // In C++11, the 'register' storage class specifier is deprecated. 7082 // Suppress the warning in system macros, it's used in macros in some 7083 // popular C system headers, such as in glibc's htonl() macro. 7084 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7085 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 7086 : diag::warn_deprecated_register) 7087 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7088 } 7089 7090 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 7091 7092 if (!DC->isRecord() && S->getFnParent() == nullptr) { 7093 // C99 6.9p2: The storage-class specifiers auto and register shall not 7094 // appear in the declaration specifiers in an external declaration. 7095 // Global Register+Asm is a GNU extension we support. 7096 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 7097 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 7098 D.setInvalidType(); 7099 } 7100 } 7101 7102 // If this variable has a VLA type and an initializer, try to 7103 // fold to a constant-sized type. This is otherwise invalid. 7104 if (D.hasInitializer() && R->isVariableArrayType()) 7105 tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(), 7106 /*DiagID=*/0); 7107 7108 bool IsMemberSpecialization = false; 7109 bool IsVariableTemplateSpecialization = false; 7110 bool IsPartialSpecialization = false; 7111 bool IsVariableTemplate = false; 7112 VarDecl *NewVD = nullptr; 7113 VarTemplateDecl *NewTemplate = nullptr; 7114 TemplateParameterList *TemplateParams = nullptr; 7115 if (!getLangOpts().CPlusPlus) { 7116 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), 7117 II, R, TInfo, SC); 7118 7119 if (R->getContainedDeducedType()) 7120 ParsingInitForAutoVars.insert(NewVD); 7121 7122 if (D.isInvalidType()) 7123 NewVD->setInvalidDecl(); 7124 7125 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() && 7126 NewVD->hasLocalStorage()) 7127 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(), 7128 NTCUC_AutoVar, NTCUK_Destruct); 7129 } else { 7130 bool Invalid = false; 7131 7132 if (DC->isRecord() && !CurContext->isRecord()) { 7133 // This is an out-of-line definition of a static data member. 7134 switch (SC) { 7135 case SC_None: 7136 break; 7137 case SC_Static: 7138 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7139 diag::err_static_out_of_line) 7140 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7141 break; 7142 case SC_Auto: 7143 case SC_Register: 7144 case SC_Extern: 7145 // [dcl.stc] p2: The auto or register specifiers shall be applied only 7146 // to names of variables declared in a block or to function parameters. 7147 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 7148 // of class members 7149 7150 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7151 diag::err_storage_class_for_static_member) 7152 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7153 break; 7154 case SC_PrivateExtern: 7155 llvm_unreachable("C storage class in c++!"); 7156 } 7157 } 7158 7159 if (SC == SC_Static && CurContext->isRecord()) { 7160 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 7161 // Walk up the enclosing DeclContexts to check for any that are 7162 // incompatible with static data members. 7163 const DeclContext *FunctionOrMethod = nullptr; 7164 const CXXRecordDecl *AnonStruct = nullptr; 7165 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) { 7166 if (Ctxt->isFunctionOrMethod()) { 7167 FunctionOrMethod = Ctxt; 7168 break; 7169 } 7170 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt); 7171 if (ParentDecl && !ParentDecl->getDeclName()) { 7172 AnonStruct = ParentDecl; 7173 break; 7174 } 7175 } 7176 if (FunctionOrMethod) { 7177 // C++ [class.static.data]p5: A local class shall not have static data 7178 // members. 7179 Diag(D.getIdentifierLoc(), 7180 diag::err_static_data_member_not_allowed_in_local_class) 7181 << Name << RD->getDeclName() << RD->getTagKind(); 7182 } else if (AnonStruct) { 7183 // C++ [class.static.data]p4: Unnamed classes and classes contained 7184 // directly or indirectly within unnamed classes shall not contain 7185 // static data members. 7186 Diag(D.getIdentifierLoc(), 7187 diag::err_static_data_member_not_allowed_in_anon_struct) 7188 << Name << AnonStruct->getTagKind(); 7189 Invalid = true; 7190 } else if (RD->isUnion()) { 7191 // C++98 [class.union]p1: If a union contains a static data member, 7192 // the program is ill-formed. C++11 drops this restriction. 7193 Diag(D.getIdentifierLoc(), 7194 getLangOpts().CPlusPlus11 7195 ? diag::warn_cxx98_compat_static_data_member_in_union 7196 : diag::ext_static_data_member_in_union) << Name; 7197 } 7198 } 7199 } 7200 7201 // Match up the template parameter lists with the scope specifier, then 7202 // determine whether we have a template or a template specialization. 7203 bool InvalidScope = false; 7204 TemplateParams = MatchTemplateParametersToScopeSpecifier( 7205 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 7206 D.getCXXScopeSpec(), 7207 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 7208 ? D.getName().TemplateId 7209 : nullptr, 7210 TemplateParamLists, 7211 /*never a friend*/ false, IsMemberSpecialization, InvalidScope); 7212 Invalid |= InvalidScope; 7213 7214 if (TemplateParams) { 7215 if (!TemplateParams->size() && 7216 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 7217 // There is an extraneous 'template<>' for this variable. Complain 7218 // about it, but allow the declaration of the variable. 7219 Diag(TemplateParams->getTemplateLoc(), 7220 diag::err_template_variable_noparams) 7221 << II 7222 << SourceRange(TemplateParams->getTemplateLoc(), 7223 TemplateParams->getRAngleLoc()); 7224 TemplateParams = nullptr; 7225 } else { 7226 // Check that we can declare a template here. 7227 if (CheckTemplateDeclScope(S, TemplateParams)) 7228 return nullptr; 7229 7230 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 7231 // This is an explicit specialization or a partial specialization. 7232 IsVariableTemplateSpecialization = true; 7233 IsPartialSpecialization = TemplateParams->size() > 0; 7234 } else { // if (TemplateParams->size() > 0) 7235 // This is a template declaration. 7236 IsVariableTemplate = true; 7237 7238 // Only C++1y supports variable templates (N3651). 7239 Diag(D.getIdentifierLoc(), 7240 getLangOpts().CPlusPlus14 7241 ? diag::warn_cxx11_compat_variable_template 7242 : diag::ext_variable_template); 7243 } 7244 } 7245 } else { 7246 // Check that we can declare a member specialization here. 7247 if (!TemplateParamLists.empty() && IsMemberSpecialization && 7248 CheckTemplateDeclScope(S, TemplateParamLists.back())) 7249 return nullptr; 7250 assert((Invalid || 7251 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && 7252 "should have a 'template<>' for this decl"); 7253 } 7254 7255 if (IsVariableTemplateSpecialization) { 7256 SourceLocation TemplateKWLoc = 7257 TemplateParamLists.size() > 0 7258 ? TemplateParamLists[0]->getTemplateLoc() 7259 : SourceLocation(); 7260 DeclResult Res = ActOnVarTemplateSpecialization( 7261 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 7262 IsPartialSpecialization); 7263 if (Res.isInvalid()) 7264 return nullptr; 7265 NewVD = cast<VarDecl>(Res.get()); 7266 AddToScope = false; 7267 } else if (D.isDecompositionDeclarator()) { 7268 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(), 7269 D.getIdentifierLoc(), R, TInfo, SC, 7270 Bindings); 7271 } else 7272 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), 7273 D.getIdentifierLoc(), II, R, TInfo, SC); 7274 7275 // If this is supposed to be a variable template, create it as such. 7276 if (IsVariableTemplate) { 7277 NewTemplate = 7278 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 7279 TemplateParams, NewVD); 7280 NewVD->setDescribedVarTemplate(NewTemplate); 7281 } 7282 7283 // If this decl has an auto type in need of deduction, make a note of the 7284 // Decl so we can diagnose uses of it in its own initializer. 7285 if (R->getContainedDeducedType()) 7286 ParsingInitForAutoVars.insert(NewVD); 7287 7288 if (D.isInvalidType() || Invalid) { 7289 NewVD->setInvalidDecl(); 7290 if (NewTemplate) 7291 NewTemplate->setInvalidDecl(); 7292 } 7293 7294 SetNestedNameSpecifier(*this, NewVD, D); 7295 7296 // If we have any template parameter lists that don't directly belong to 7297 // the variable (matching the scope specifier), store them. 7298 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 7299 if (TemplateParamLists.size() > VDTemplateParamLists) 7300 NewVD->setTemplateParameterListsInfo( 7301 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 7302 } 7303 7304 if (D.getDeclSpec().isInlineSpecified()) { 7305 if (!getLangOpts().CPlusPlus) { 7306 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 7307 << 0; 7308 } else if (CurContext->isFunctionOrMethod()) { 7309 // 'inline' is not allowed on block scope variable declaration. 7310 Diag(D.getDeclSpec().getInlineSpecLoc(), 7311 diag::err_inline_declaration_block_scope) << Name 7312 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 7313 } else { 7314 Diag(D.getDeclSpec().getInlineSpecLoc(), 7315 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable 7316 : diag::ext_inline_variable); 7317 NewVD->setInlineSpecified(); 7318 } 7319 } 7320 7321 // Set the lexical context. If the declarator has a C++ scope specifier, the 7322 // lexical context will be different from the semantic context. 7323 NewVD->setLexicalDeclContext(CurContext); 7324 if (NewTemplate) 7325 NewTemplate->setLexicalDeclContext(CurContext); 7326 7327 if (IsLocalExternDecl) { 7328 if (D.isDecompositionDeclarator()) 7329 for (auto *B : Bindings) 7330 B->setLocalExternDecl(); 7331 else 7332 NewVD->setLocalExternDecl(); 7333 } 7334 7335 bool EmitTLSUnsupportedError = false; 7336 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 7337 // C++11 [dcl.stc]p4: 7338 // When thread_local is applied to a variable of block scope the 7339 // storage-class-specifier static is implied if it does not appear 7340 // explicitly. 7341 // Core issue: 'static' is not implied if the variable is declared 7342 // 'extern'. 7343 if (NewVD->hasLocalStorage() && 7344 (SCSpec != DeclSpec::SCS_unspecified || 7345 TSCS != DeclSpec::TSCS_thread_local || 7346 !DC->isFunctionOrMethod())) 7347 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7348 diag::err_thread_non_global) 7349 << DeclSpec::getSpecifierName(TSCS); 7350 else if (!Context.getTargetInfo().isTLSSupported()) { 7351 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || 7352 getLangOpts().SYCLIsDevice) { 7353 // Postpone error emission until we've collected attributes required to 7354 // figure out whether it's a host or device variable and whether the 7355 // error should be ignored. 7356 EmitTLSUnsupportedError = true; 7357 // We still need to mark the variable as TLS so it shows up in AST with 7358 // proper storage class for other tools to use even if we're not going 7359 // to emit any code for it. 7360 NewVD->setTSCSpec(TSCS); 7361 } else 7362 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7363 diag::err_thread_unsupported); 7364 } else 7365 NewVD->setTSCSpec(TSCS); 7366 } 7367 7368 switch (D.getDeclSpec().getConstexprSpecifier()) { 7369 case ConstexprSpecKind::Unspecified: 7370 break; 7371 7372 case ConstexprSpecKind::Consteval: 7373 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7374 diag::err_constexpr_wrong_decl_kind) 7375 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 7376 LLVM_FALLTHROUGH; 7377 7378 case ConstexprSpecKind::Constexpr: 7379 NewVD->setConstexpr(true); 7380 // C++1z [dcl.spec.constexpr]p1: 7381 // A static data member declared with the constexpr specifier is 7382 // implicitly an inline variable. 7383 if (NewVD->isStaticDataMember() && 7384 (getLangOpts().CPlusPlus17 || 7385 Context.getTargetInfo().getCXXABI().isMicrosoft())) 7386 NewVD->setImplicitlyInline(); 7387 break; 7388 7389 case ConstexprSpecKind::Constinit: 7390 if (!NewVD->hasGlobalStorage()) 7391 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7392 diag::err_constinit_local_variable); 7393 else 7394 NewVD->addAttr(ConstInitAttr::Create( 7395 Context, D.getDeclSpec().getConstexprSpecLoc(), 7396 AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit)); 7397 break; 7398 } 7399 7400 // C99 6.7.4p3 7401 // An inline definition of a function with external linkage shall 7402 // not contain a definition of a modifiable object with static or 7403 // thread storage duration... 7404 // We only apply this when the function is required to be defined 7405 // elsewhere, i.e. when the function is not 'extern inline'. Note 7406 // that a local variable with thread storage duration still has to 7407 // be marked 'static'. Also note that it's possible to get these 7408 // semantics in C++ using __attribute__((gnu_inline)). 7409 if (SC == SC_Static && S->getFnParent() != nullptr && 7410 !NewVD->getType().isConstQualified()) { 7411 FunctionDecl *CurFD = getCurFunctionDecl(); 7412 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 7413 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7414 diag::warn_static_local_in_extern_inline); 7415 MaybeSuggestAddingStaticToDecl(CurFD); 7416 } 7417 } 7418 7419 if (D.getDeclSpec().isModulePrivateSpecified()) { 7420 if (IsVariableTemplateSpecialization) 7421 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7422 << (IsPartialSpecialization ? 1 : 0) 7423 << FixItHint::CreateRemoval( 7424 D.getDeclSpec().getModulePrivateSpecLoc()); 7425 else if (IsMemberSpecialization) 7426 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7427 << 2 7428 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 7429 else if (NewVD->hasLocalStorage()) 7430 Diag(NewVD->getLocation(), diag::err_module_private_local) 7431 << 0 << NewVD 7432 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 7433 << FixItHint::CreateRemoval( 7434 D.getDeclSpec().getModulePrivateSpecLoc()); 7435 else { 7436 NewVD->setModulePrivate(); 7437 if (NewTemplate) 7438 NewTemplate->setModulePrivate(); 7439 for (auto *B : Bindings) 7440 B->setModulePrivate(); 7441 } 7442 } 7443 7444 if (getLangOpts().OpenCL) { 7445 deduceOpenCLAddressSpace(NewVD); 7446 7447 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec(); 7448 if (TSC != TSCS_unspecified) { 7449 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7450 diag::err_opencl_unknown_type_specifier) 7451 << getLangOpts().getOpenCLVersionString() 7452 << DeclSpec::getSpecifierName(TSC) << 1; 7453 NewVD->setInvalidDecl(); 7454 } 7455 } 7456 7457 // Handle attributes prior to checking for duplicates in MergeVarDecl 7458 ProcessDeclAttributes(S, NewVD, D); 7459 7460 // FIXME: This is probably the wrong location to be doing this and we should 7461 // probably be doing this for more attributes (especially for function 7462 // pointer attributes such as format, warn_unused_result, etc.). Ideally 7463 // the code to copy attributes would be generated by TableGen. 7464 if (R->isFunctionPointerType()) 7465 if (const auto *TT = R->getAs<TypedefType>()) 7466 copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT); 7467 7468 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || 7469 getLangOpts().SYCLIsDevice) { 7470 if (EmitTLSUnsupportedError && 7471 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || 7472 (getLangOpts().OpenMPIsDevice && 7473 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD)))) 7474 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7475 diag::err_thread_unsupported); 7476 7477 if (EmitTLSUnsupportedError && 7478 (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice))) 7479 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported); 7480 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 7481 // storage [duration]." 7482 if (SC == SC_None && S->getFnParent() != nullptr && 7483 (NewVD->hasAttr<CUDASharedAttr>() || 7484 NewVD->hasAttr<CUDAConstantAttr>())) { 7485 NewVD->setStorageClass(SC_Static); 7486 } 7487 } 7488 7489 // Ensure that dllimport globals without explicit storage class are treated as 7490 // extern. The storage class is set above using parsed attributes. Now we can 7491 // check the VarDecl itself. 7492 assert(!NewVD->hasAttr<DLLImportAttr>() || 7493 NewVD->getAttr<DLLImportAttr>()->isInherited() || 7494 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 7495 7496 // In auto-retain/release, infer strong retension for variables of 7497 // retainable type. 7498 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 7499 NewVD->setInvalidDecl(); 7500 7501 // Handle GNU asm-label extension (encoded as an attribute). 7502 if (Expr *E = (Expr*)D.getAsmLabel()) { 7503 // The parser guarantees this is a string. 7504 StringLiteral *SE = cast<StringLiteral>(E); 7505 StringRef Label = SE->getString(); 7506 if (S->getFnParent() != nullptr) { 7507 switch (SC) { 7508 case SC_None: 7509 case SC_Auto: 7510 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 7511 break; 7512 case SC_Register: 7513 // Local Named register 7514 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 7515 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 7516 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7517 break; 7518 case SC_Static: 7519 case SC_Extern: 7520 case SC_PrivateExtern: 7521 break; 7522 } 7523 } else if (SC == SC_Register) { 7524 // Global Named register 7525 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 7526 const auto &TI = Context.getTargetInfo(); 7527 bool HasSizeMismatch; 7528 7529 if (!TI.isValidGCCRegisterName(Label)) 7530 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7531 else if (!TI.validateGlobalRegisterVariable(Label, 7532 Context.getTypeSize(R), 7533 HasSizeMismatch)) 7534 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 7535 else if (HasSizeMismatch) 7536 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 7537 } 7538 7539 if (!R->isIntegralType(Context) && !R->isPointerType()) { 7540 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type); 7541 NewVD->setInvalidDecl(true); 7542 } 7543 } 7544 7545 NewVD->addAttr(AsmLabelAttr::Create(Context, Label, 7546 /*IsLiteralLabel=*/true, 7547 SE->getStrTokenLoc(0))); 7548 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 7549 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 7550 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 7551 if (I != ExtnameUndeclaredIdentifiers.end()) { 7552 if (isDeclExternC(NewVD)) { 7553 NewVD->addAttr(I->second); 7554 ExtnameUndeclaredIdentifiers.erase(I); 7555 } else 7556 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 7557 << /*Variable*/1 << NewVD; 7558 } 7559 } 7560 7561 // Find the shadowed declaration before filtering for scope. 7562 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 7563 ? getShadowedDeclaration(NewVD, Previous) 7564 : nullptr; 7565 7566 // Don't consider existing declarations that are in a different 7567 // scope and are out-of-semantic-context declarations (if the new 7568 // declaration has linkage). 7569 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 7570 D.getCXXScopeSpec().isNotEmpty() || 7571 IsMemberSpecialization || 7572 IsVariableTemplateSpecialization); 7573 7574 // Check whether the previous declaration is in the same block scope. This 7575 // affects whether we merge types with it, per C++11 [dcl.array]p3. 7576 if (getLangOpts().CPlusPlus && 7577 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 7578 NewVD->setPreviousDeclInSameBlockScope( 7579 Previous.isSingleResult() && !Previous.isShadowed() && 7580 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 7581 7582 if (!getLangOpts().CPlusPlus) { 7583 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7584 } else { 7585 // If this is an explicit specialization of a static data member, check it. 7586 if (IsMemberSpecialization && !NewVD->isInvalidDecl() && 7587 CheckMemberSpecialization(NewVD, Previous)) 7588 NewVD->setInvalidDecl(); 7589 7590 // Merge the decl with the existing one if appropriate. 7591 if (!Previous.empty()) { 7592 if (Previous.isSingleResult() && 7593 isa<FieldDecl>(Previous.getFoundDecl()) && 7594 D.getCXXScopeSpec().isSet()) { 7595 // The user tried to define a non-static data member 7596 // out-of-line (C++ [dcl.meaning]p1). 7597 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 7598 << D.getCXXScopeSpec().getRange(); 7599 Previous.clear(); 7600 NewVD->setInvalidDecl(); 7601 } 7602 } else if (D.getCXXScopeSpec().isSet()) { 7603 // No previous declaration in the qualifying scope. 7604 Diag(D.getIdentifierLoc(), diag::err_no_member) 7605 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 7606 << D.getCXXScopeSpec().getRange(); 7607 NewVD->setInvalidDecl(); 7608 } 7609 7610 if (!IsVariableTemplateSpecialization) 7611 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7612 7613 if (NewTemplate) { 7614 VarTemplateDecl *PrevVarTemplate = 7615 NewVD->getPreviousDecl() 7616 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 7617 : nullptr; 7618 7619 // Check the template parameter list of this declaration, possibly 7620 // merging in the template parameter list from the previous variable 7621 // template declaration. 7622 if (CheckTemplateParameterList( 7623 TemplateParams, 7624 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 7625 : nullptr, 7626 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 7627 DC->isDependentContext()) 7628 ? TPC_ClassTemplateMember 7629 : TPC_VarTemplate)) 7630 NewVD->setInvalidDecl(); 7631 7632 // If we are providing an explicit specialization of a static variable 7633 // template, make a note of that. 7634 if (PrevVarTemplate && 7635 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 7636 PrevVarTemplate->setMemberSpecialization(); 7637 } 7638 } 7639 7640 // Diagnose shadowed variables iff this isn't a redeclaration. 7641 if (ShadowedDecl && !D.isRedeclaration()) 7642 CheckShadow(NewVD, ShadowedDecl, Previous); 7643 7644 ProcessPragmaWeak(S, NewVD); 7645 7646 // If this is the first declaration of an extern C variable, update 7647 // the map of such variables. 7648 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 7649 isIncompleteDeclExternC(*this, NewVD)) 7650 RegisterLocallyScopedExternCDecl(NewVD, S); 7651 7652 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 7653 MangleNumberingContext *MCtx; 7654 Decl *ManglingContextDecl; 7655 std::tie(MCtx, ManglingContextDecl) = 7656 getCurrentMangleNumberContext(NewVD->getDeclContext()); 7657 if (MCtx) { 7658 Context.setManglingNumber( 7659 NewVD, MCtx->getManglingNumber( 7660 NewVD, getMSManglingNumber(getLangOpts(), S))); 7661 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 7662 } 7663 } 7664 7665 // Special handling of variable named 'main'. 7666 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 7667 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 7668 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 7669 7670 // C++ [basic.start.main]p3 7671 // A program that declares a variable main at global scope is ill-formed. 7672 if (getLangOpts().CPlusPlus) 7673 Diag(D.getBeginLoc(), diag::err_main_global_variable); 7674 7675 // In C, and external-linkage variable named main results in undefined 7676 // behavior. 7677 else if (NewVD->hasExternalFormalLinkage()) 7678 Diag(D.getBeginLoc(), diag::warn_main_redefined); 7679 } 7680 7681 if (D.isRedeclaration() && !Previous.empty()) { 7682 NamedDecl *Prev = Previous.getRepresentativeDecl(); 7683 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization, 7684 D.isFunctionDefinition()); 7685 } 7686 7687 if (NewTemplate) { 7688 if (NewVD->isInvalidDecl()) 7689 NewTemplate->setInvalidDecl(); 7690 ActOnDocumentableDecl(NewTemplate); 7691 return NewTemplate; 7692 } 7693 7694 if (IsMemberSpecialization && !NewVD->isInvalidDecl()) 7695 CompleteMemberSpecialization(NewVD, Previous); 7696 7697 return NewVD; 7698 } 7699 7700 /// Enum describing the %select options in diag::warn_decl_shadow. 7701 enum ShadowedDeclKind { 7702 SDK_Local, 7703 SDK_Global, 7704 SDK_StaticMember, 7705 SDK_Field, 7706 SDK_Typedef, 7707 SDK_Using, 7708 SDK_StructuredBinding 7709 }; 7710 7711 /// Determine what kind of declaration we're shadowing. 7712 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 7713 const DeclContext *OldDC) { 7714 if (isa<TypeAliasDecl>(ShadowedDecl)) 7715 return SDK_Using; 7716 else if (isa<TypedefDecl>(ShadowedDecl)) 7717 return SDK_Typedef; 7718 else if (isa<BindingDecl>(ShadowedDecl)) 7719 return SDK_StructuredBinding; 7720 else if (isa<RecordDecl>(OldDC)) 7721 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 7722 7723 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 7724 } 7725 7726 /// Return the location of the capture if the given lambda captures the given 7727 /// variable \p VD, or an invalid source location otherwise. 7728 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 7729 const VarDecl *VD) { 7730 for (const Capture &Capture : LSI->Captures) { 7731 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 7732 return Capture.getLocation(); 7733 } 7734 return SourceLocation(); 7735 } 7736 7737 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, 7738 const LookupResult &R) { 7739 // Only diagnose if we're shadowing an unambiguous field or variable. 7740 if (R.getResultKind() != LookupResult::Found) 7741 return false; 7742 7743 // Return false if warning is ignored. 7744 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); 7745 } 7746 7747 /// Return the declaration shadowed by the given variable \p D, or null 7748 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7749 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 7750 const LookupResult &R) { 7751 if (!shouldWarnIfShadowedDecl(Diags, R)) 7752 return nullptr; 7753 7754 // Don't diagnose declarations at file scope. 7755 if (D->hasGlobalStorage()) 7756 return nullptr; 7757 7758 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7759 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl 7760 : nullptr; 7761 } 7762 7763 /// Return the declaration shadowed by the given typedef \p D, or null 7764 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7765 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, 7766 const LookupResult &R) { 7767 // Don't warn if typedef declaration is part of a class 7768 if (D->getDeclContext()->isRecord()) 7769 return nullptr; 7770 7771 if (!shouldWarnIfShadowedDecl(Diags, R)) 7772 return nullptr; 7773 7774 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7775 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; 7776 } 7777 7778 /// Return the declaration shadowed by the given variable \p D, or null 7779 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7780 NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D, 7781 const LookupResult &R) { 7782 if (!shouldWarnIfShadowedDecl(Diags, R)) 7783 return nullptr; 7784 7785 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7786 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl 7787 : nullptr; 7788 } 7789 7790 /// Diagnose variable or built-in function shadowing. Implements 7791 /// -Wshadow. 7792 /// 7793 /// This method is called whenever a VarDecl is added to a "useful" 7794 /// scope. 7795 /// 7796 /// \param ShadowedDecl the declaration that is shadowed by the given variable 7797 /// \param R the lookup of the name 7798 /// 7799 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 7800 const LookupResult &R) { 7801 DeclContext *NewDC = D->getDeclContext(); 7802 7803 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 7804 // Fields are not shadowed by variables in C++ static methods. 7805 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 7806 if (MD->isStatic()) 7807 return; 7808 7809 // Fields shadowed by constructor parameters are a special case. Usually 7810 // the constructor initializes the field with the parameter. 7811 if (isa<CXXConstructorDecl>(NewDC)) 7812 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { 7813 // Remember that this was shadowed so we can either warn about its 7814 // modification or its existence depending on warning settings. 7815 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); 7816 return; 7817 } 7818 } 7819 7820 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 7821 if (shadowedVar->isExternC()) { 7822 // For shadowing external vars, make sure that we point to the global 7823 // declaration, not a locally scoped extern declaration. 7824 for (auto I : shadowedVar->redecls()) 7825 if (I->isFileVarDecl()) { 7826 ShadowedDecl = I; 7827 break; 7828 } 7829 } 7830 7831 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); 7832 7833 unsigned WarningDiag = diag::warn_decl_shadow; 7834 SourceLocation CaptureLoc; 7835 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && 7836 isa<CXXMethodDecl>(NewDC)) { 7837 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 7838 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 7839 if (RD->getLambdaCaptureDefault() == LCD_None) { 7840 // Try to avoid warnings for lambdas with an explicit capture list. 7841 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 7842 // Warn only when the lambda captures the shadowed decl explicitly. 7843 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 7844 if (CaptureLoc.isInvalid()) 7845 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 7846 } else { 7847 // Remember that this was shadowed so we can avoid the warning if the 7848 // shadowed decl isn't captured and the warning settings allow it. 7849 cast<LambdaScopeInfo>(getCurFunction()) 7850 ->ShadowingDecls.push_back( 7851 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); 7852 return; 7853 } 7854 } 7855 7856 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { 7857 // A variable can't shadow a local variable in an enclosing scope, if 7858 // they are separated by a non-capturing declaration context. 7859 for (DeclContext *ParentDC = NewDC; 7860 ParentDC && !ParentDC->Equals(OldDC); 7861 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { 7862 // Only block literals, captured statements, and lambda expressions 7863 // can capture; other scopes don't. 7864 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && 7865 !isLambdaCallOperator(ParentDC)) { 7866 return; 7867 } 7868 } 7869 } 7870 } 7871 } 7872 7873 // Only warn about certain kinds of shadowing for class members. 7874 if (NewDC && NewDC->isRecord()) { 7875 // In particular, don't warn about shadowing non-class members. 7876 if (!OldDC->isRecord()) 7877 return; 7878 7879 // TODO: should we warn about static data members shadowing 7880 // static data members from base classes? 7881 7882 // TODO: don't diagnose for inaccessible shadowed members. 7883 // This is hard to do perfectly because we might friend the 7884 // shadowing context, but that's just a false negative. 7885 } 7886 7887 7888 DeclarationName Name = R.getLookupName(); 7889 7890 // Emit warning and note. 7891 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 7892 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 7893 if (!CaptureLoc.isInvalid()) 7894 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7895 << Name << /*explicitly*/ 1; 7896 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7897 } 7898 7899 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 7900 /// when these variables are captured by the lambda. 7901 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 7902 for (const auto &Shadow : LSI->ShadowingDecls) { 7903 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 7904 // Try to avoid the warning when the shadowed decl isn't captured. 7905 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 7906 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7907 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 7908 ? diag::warn_decl_shadow_uncaptured_local 7909 : diag::warn_decl_shadow) 7910 << Shadow.VD->getDeclName() 7911 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 7912 if (!CaptureLoc.isInvalid()) 7913 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7914 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 7915 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7916 } 7917 } 7918 7919 /// Check -Wshadow without the advantage of a previous lookup. 7920 void Sema::CheckShadow(Scope *S, VarDecl *D) { 7921 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 7922 return; 7923 7924 LookupResult R(*this, D->getDeclName(), D->getLocation(), 7925 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); 7926 LookupName(R, S); 7927 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 7928 CheckShadow(D, ShadowedDecl, R); 7929 } 7930 7931 /// Check if 'E', which is an expression that is about to be modified, refers 7932 /// to a constructor parameter that shadows a field. 7933 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 7934 // Quickly ignore expressions that can't be shadowing ctor parameters. 7935 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 7936 return; 7937 E = E->IgnoreParenImpCasts(); 7938 auto *DRE = dyn_cast<DeclRefExpr>(E); 7939 if (!DRE) 7940 return; 7941 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 7942 auto I = ShadowingDecls.find(D); 7943 if (I == ShadowingDecls.end()) 7944 return; 7945 const NamedDecl *ShadowedDecl = I->second; 7946 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7947 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 7948 Diag(D->getLocation(), diag::note_var_declared_here) << D; 7949 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7950 7951 // Avoid issuing multiple warnings about the same decl. 7952 ShadowingDecls.erase(I); 7953 } 7954 7955 /// Check for conflict between this global or extern "C" declaration and 7956 /// previous global or extern "C" declarations. This is only used in C++. 7957 template<typename T> 7958 static bool checkGlobalOrExternCConflict( 7959 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 7960 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 7961 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 7962 7963 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 7964 // The common case: this global doesn't conflict with any extern "C" 7965 // declaration. 7966 return false; 7967 } 7968 7969 if (Prev) { 7970 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 7971 // Both the old and new declarations have C language linkage. This is a 7972 // redeclaration. 7973 Previous.clear(); 7974 Previous.addDecl(Prev); 7975 return true; 7976 } 7977 7978 // This is a global, non-extern "C" declaration, and there is a previous 7979 // non-global extern "C" declaration. Diagnose if this is a variable 7980 // declaration. 7981 if (!isa<VarDecl>(ND)) 7982 return false; 7983 } else { 7984 // The declaration is extern "C". Check for any declaration in the 7985 // translation unit which might conflict. 7986 if (IsGlobal) { 7987 // We have already performed the lookup into the translation unit. 7988 IsGlobal = false; 7989 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7990 I != E; ++I) { 7991 if (isa<VarDecl>(*I)) { 7992 Prev = *I; 7993 break; 7994 } 7995 } 7996 } else { 7997 DeclContext::lookup_result R = 7998 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 7999 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 8000 I != E; ++I) { 8001 if (isa<VarDecl>(*I)) { 8002 Prev = *I; 8003 break; 8004 } 8005 // FIXME: If we have any other entity with this name in global scope, 8006 // the declaration is ill-formed, but that is a defect: it breaks the 8007 // 'stat' hack, for instance. Only variables can have mangled name 8008 // clashes with extern "C" declarations, so only they deserve a 8009 // diagnostic. 8010 } 8011 } 8012 8013 if (!Prev) 8014 return false; 8015 } 8016 8017 // Use the first declaration's location to ensure we point at something which 8018 // is lexically inside an extern "C" linkage-spec. 8019 assert(Prev && "should have found a previous declaration to diagnose"); 8020 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 8021 Prev = FD->getFirstDecl(); 8022 else 8023 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 8024 8025 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 8026 << IsGlobal << ND; 8027 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 8028 << IsGlobal; 8029 return false; 8030 } 8031 8032 /// Apply special rules for handling extern "C" declarations. Returns \c true 8033 /// if we have found that this is a redeclaration of some prior entity. 8034 /// 8035 /// Per C++ [dcl.link]p6: 8036 /// Two declarations [for a function or variable] with C language linkage 8037 /// with the same name that appear in different scopes refer to the same 8038 /// [entity]. An entity with C language linkage shall not be declared with 8039 /// the same name as an entity in global scope. 8040 template<typename T> 8041 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 8042 LookupResult &Previous) { 8043 if (!S.getLangOpts().CPlusPlus) { 8044 // In C, when declaring a global variable, look for a corresponding 'extern' 8045 // variable declared in function scope. We don't need this in C++, because 8046 // we find local extern decls in the surrounding file-scope DeclContext. 8047 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 8048 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 8049 Previous.clear(); 8050 Previous.addDecl(Prev); 8051 return true; 8052 } 8053 } 8054 return false; 8055 } 8056 8057 // A declaration in the translation unit can conflict with an extern "C" 8058 // declaration. 8059 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 8060 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 8061 8062 // An extern "C" declaration can conflict with a declaration in the 8063 // translation unit or can be a redeclaration of an extern "C" declaration 8064 // in another scope. 8065 if (isIncompleteDeclExternC(S,ND)) 8066 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 8067 8068 // Neither global nor extern "C": nothing to do. 8069 return false; 8070 } 8071 8072 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 8073 // If the decl is already known invalid, don't check it. 8074 if (NewVD->isInvalidDecl()) 8075 return; 8076 8077 QualType T = NewVD->getType(); 8078 8079 // Defer checking an 'auto' type until its initializer is attached. 8080 if (T->isUndeducedType()) 8081 return; 8082 8083 if (NewVD->hasAttrs()) 8084 CheckAlignasUnderalignment(NewVD); 8085 8086 if (T->isObjCObjectType()) { 8087 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 8088 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 8089 T = Context.getObjCObjectPointerType(T); 8090 NewVD->setType(T); 8091 } 8092 8093 // Emit an error if an address space was applied to decl with local storage. 8094 // This includes arrays of objects with address space qualifiers, but not 8095 // automatic variables that point to other address spaces. 8096 // ISO/IEC TR 18037 S5.1.2 8097 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && 8098 T.getAddressSpace() != LangAS::Default) { 8099 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; 8100 NewVD->setInvalidDecl(); 8101 return; 8102 } 8103 8104 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 8105 // scope. 8106 if (getLangOpts().OpenCLVersion == 120 && 8107 !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers", 8108 getLangOpts()) && 8109 NewVD->isStaticLocal()) { 8110 Diag(NewVD->getLocation(), diag::err_static_function_scope); 8111 NewVD->setInvalidDecl(); 8112 return; 8113 } 8114 8115 if (getLangOpts().OpenCL) { 8116 if (!diagnoseOpenCLTypes(*this, NewVD)) 8117 return; 8118 8119 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 8120 if (NewVD->hasAttr<BlocksAttr>()) { 8121 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 8122 return; 8123 } 8124 8125 if (T->isBlockPointerType()) { 8126 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 8127 // can't use 'extern' storage class. 8128 if (!T.isConstQualified()) { 8129 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 8130 << 0 /*const*/; 8131 NewVD->setInvalidDecl(); 8132 return; 8133 } 8134 if (NewVD->hasExternalStorage()) { 8135 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 8136 NewVD->setInvalidDecl(); 8137 return; 8138 } 8139 } 8140 8141 // FIXME: Adding local AS in C++ for OpenCL might make sense. 8142 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 8143 NewVD->hasExternalStorage()) { 8144 if (!T->isSamplerT() && !T->isDependentType() && 8145 !(T.getAddressSpace() == LangAS::opencl_constant || 8146 (T.getAddressSpace() == LangAS::opencl_global && 8147 getOpenCLOptions().areProgramScopeVariablesSupported( 8148 getLangOpts())))) { 8149 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 8150 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts())) 8151 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 8152 << Scope << "global or constant"; 8153 else 8154 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 8155 << Scope << "constant"; 8156 NewVD->setInvalidDecl(); 8157 return; 8158 } 8159 } else { 8160 if (T.getAddressSpace() == LangAS::opencl_global) { 8161 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 8162 << 1 /*is any function*/ << "global"; 8163 NewVD->setInvalidDecl(); 8164 return; 8165 } 8166 if (T.getAddressSpace() == LangAS::opencl_constant || 8167 T.getAddressSpace() == LangAS::opencl_local) { 8168 FunctionDecl *FD = getCurFunctionDecl(); 8169 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables 8170 // in functions. 8171 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 8172 if (T.getAddressSpace() == LangAS::opencl_constant) 8173 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 8174 << 0 /*non-kernel only*/ << "constant"; 8175 else 8176 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 8177 << 0 /*non-kernel only*/ << "local"; 8178 NewVD->setInvalidDecl(); 8179 return; 8180 } 8181 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be 8182 // in the outermost scope of a kernel function. 8183 if (FD && FD->hasAttr<OpenCLKernelAttr>()) { 8184 if (!getCurScope()->isFunctionScope()) { 8185 if (T.getAddressSpace() == LangAS::opencl_constant) 8186 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 8187 << "constant"; 8188 else 8189 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 8190 << "local"; 8191 NewVD->setInvalidDecl(); 8192 return; 8193 } 8194 } 8195 } else if (T.getAddressSpace() != LangAS::opencl_private && 8196 // If we are parsing a template we didn't deduce an addr 8197 // space yet. 8198 T.getAddressSpace() != LangAS::Default) { 8199 // Do not allow other address spaces on automatic variable. 8200 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; 8201 NewVD->setInvalidDecl(); 8202 return; 8203 } 8204 } 8205 } 8206 8207 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 8208 && !NewVD->hasAttr<BlocksAttr>()) { 8209 if (getLangOpts().getGC() != LangOptions::NonGC) 8210 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 8211 else { 8212 assert(!getLangOpts().ObjCAutoRefCount); 8213 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 8214 } 8215 } 8216 8217 bool isVM = T->isVariablyModifiedType(); 8218 if (isVM || NewVD->hasAttr<CleanupAttr>() || 8219 NewVD->hasAttr<BlocksAttr>()) 8220 setFunctionHasBranchProtectedScope(); 8221 8222 if ((isVM && NewVD->hasLinkage()) || 8223 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 8224 bool SizeIsNegative; 8225 llvm::APSInt Oversized; 8226 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 8227 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized); 8228 QualType FixedT; 8229 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType()) 8230 FixedT = FixedTInfo->getType(); 8231 else if (FixedTInfo) { 8232 // Type and type-as-written are canonically different. We need to fix up 8233 // both types separately. 8234 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 8235 Oversized); 8236 } 8237 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) { 8238 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 8239 // FIXME: This won't give the correct result for 8240 // int a[10][n]; 8241 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 8242 8243 if (NewVD->isFileVarDecl()) 8244 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 8245 << SizeRange; 8246 else if (NewVD->isStaticLocal()) 8247 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 8248 << SizeRange; 8249 else 8250 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 8251 << SizeRange; 8252 NewVD->setInvalidDecl(); 8253 return; 8254 } 8255 8256 if (!FixedTInfo) { 8257 if (NewVD->isFileVarDecl()) 8258 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 8259 else 8260 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 8261 NewVD->setInvalidDecl(); 8262 return; 8263 } 8264 8265 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant); 8266 NewVD->setType(FixedT); 8267 NewVD->setTypeSourceInfo(FixedTInfo); 8268 } 8269 8270 if (T->isVoidType()) { 8271 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 8272 // of objects and functions. 8273 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 8274 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 8275 << T; 8276 NewVD->setInvalidDecl(); 8277 return; 8278 } 8279 } 8280 8281 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 8282 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 8283 NewVD->setInvalidDecl(); 8284 return; 8285 } 8286 8287 if (!NewVD->hasLocalStorage() && T->isSizelessType()) { 8288 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T; 8289 NewVD->setInvalidDecl(); 8290 return; 8291 } 8292 8293 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 8294 Diag(NewVD->getLocation(), diag::err_block_on_vm); 8295 NewVD->setInvalidDecl(); 8296 return; 8297 } 8298 8299 if (NewVD->isConstexpr() && !T->isDependentType() && 8300 RequireLiteralType(NewVD->getLocation(), T, 8301 diag::err_constexpr_var_non_literal)) { 8302 NewVD->setInvalidDecl(); 8303 return; 8304 } 8305 8306 // PPC MMA non-pointer types are not allowed as non-local variable types. 8307 if (Context.getTargetInfo().getTriple().isPPC64() && 8308 !NewVD->isLocalVarDecl() && 8309 CheckPPCMMAType(T, NewVD->getLocation())) { 8310 NewVD->setInvalidDecl(); 8311 return; 8312 } 8313 } 8314 8315 /// Perform semantic checking on a newly-created variable 8316 /// declaration. 8317 /// 8318 /// This routine performs all of the type-checking required for a 8319 /// variable declaration once it has been built. It is used both to 8320 /// check variables after they have been parsed and their declarators 8321 /// have been translated into a declaration, and to check variables 8322 /// that have been instantiated from a template. 8323 /// 8324 /// Sets NewVD->isInvalidDecl() if an error was encountered. 8325 /// 8326 /// Returns true if the variable declaration is a redeclaration. 8327 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 8328 CheckVariableDeclarationType(NewVD); 8329 8330 // If the decl is already known invalid, don't check it. 8331 if (NewVD->isInvalidDecl()) 8332 return false; 8333 8334 // If we did not find anything by this name, look for a non-visible 8335 // extern "C" declaration with the same name. 8336 if (Previous.empty() && 8337 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 8338 Previous.setShadowed(); 8339 8340 if (!Previous.empty()) { 8341 MergeVarDecl(NewVD, Previous); 8342 return true; 8343 } 8344 return false; 8345 } 8346 8347 /// AddOverriddenMethods - See if a method overrides any in the base classes, 8348 /// and if so, check that it's a valid override and remember it. 8349 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 8350 llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden; 8351 8352 // Look for methods in base classes that this method might override. 8353 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false, 8354 /*DetectVirtual=*/false); 8355 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 8356 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl(); 8357 DeclarationName Name = MD->getDeclName(); 8358 8359 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8360 // We really want to find the base class destructor here. 8361 QualType T = Context.getTypeDeclType(BaseRecord); 8362 CanQualType CT = Context.getCanonicalType(T); 8363 Name = Context.DeclarationNames.getCXXDestructorName(CT); 8364 } 8365 8366 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) { 8367 CXXMethodDecl *BaseMD = 8368 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl()); 8369 if (!BaseMD || !BaseMD->isVirtual() || 8370 IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false, 8371 /*ConsiderCudaAttrs=*/true, 8372 // C++2a [class.virtual]p2 does not consider requires 8373 // clauses when overriding. 8374 /*ConsiderRequiresClauses=*/false)) 8375 continue; 8376 8377 if (Overridden.insert(BaseMD).second) { 8378 MD->addOverriddenMethod(BaseMD); 8379 CheckOverridingFunctionReturnType(MD, BaseMD); 8380 CheckOverridingFunctionAttributes(MD, BaseMD); 8381 CheckOverridingFunctionExceptionSpec(MD, BaseMD); 8382 CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD); 8383 } 8384 8385 // A method can only override one function from each base class. We 8386 // don't track indirectly overridden methods from bases of bases. 8387 return true; 8388 } 8389 8390 return false; 8391 }; 8392 8393 DC->lookupInBases(VisitBase, Paths); 8394 return !Overridden.empty(); 8395 } 8396 8397 namespace { 8398 // Struct for holding all of the extra arguments needed by 8399 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 8400 struct ActOnFDArgs { 8401 Scope *S; 8402 Declarator &D; 8403 MultiTemplateParamsArg TemplateParamLists; 8404 bool AddToScope; 8405 }; 8406 } // end anonymous namespace 8407 8408 namespace { 8409 8410 // Callback to only accept typo corrections that have a non-zero edit distance. 8411 // Also only accept corrections that have the same parent decl. 8412 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback { 8413 public: 8414 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 8415 CXXRecordDecl *Parent) 8416 : Context(Context), OriginalFD(TypoFD), 8417 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 8418 8419 bool ValidateCandidate(const TypoCorrection &candidate) override { 8420 if (candidate.getEditDistance() == 0) 8421 return false; 8422 8423 SmallVector<unsigned, 1> MismatchedParams; 8424 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 8425 CDeclEnd = candidate.end(); 8426 CDecl != CDeclEnd; ++CDecl) { 8427 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8428 8429 if (FD && !FD->hasBody() && 8430 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 8431 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 8432 CXXRecordDecl *Parent = MD->getParent(); 8433 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 8434 return true; 8435 } else if (!ExpectedParent) { 8436 return true; 8437 } 8438 } 8439 } 8440 8441 return false; 8442 } 8443 8444 std::unique_ptr<CorrectionCandidateCallback> clone() override { 8445 return std::make_unique<DifferentNameValidatorCCC>(*this); 8446 } 8447 8448 private: 8449 ASTContext &Context; 8450 FunctionDecl *OriginalFD; 8451 CXXRecordDecl *ExpectedParent; 8452 }; 8453 8454 } // end anonymous namespace 8455 8456 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { 8457 TypoCorrectedFunctionDefinitions.insert(F); 8458 } 8459 8460 /// Generate diagnostics for an invalid function redeclaration. 8461 /// 8462 /// This routine handles generating the diagnostic messages for an invalid 8463 /// function redeclaration, including finding possible similar declarations 8464 /// or performing typo correction if there are no previous declarations with 8465 /// the same name. 8466 /// 8467 /// Returns a NamedDecl iff typo correction was performed and substituting in 8468 /// the new declaration name does not cause new errors. 8469 static NamedDecl *DiagnoseInvalidRedeclaration( 8470 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 8471 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 8472 DeclarationName Name = NewFD->getDeclName(); 8473 DeclContext *NewDC = NewFD->getDeclContext(); 8474 SmallVector<unsigned, 1> MismatchedParams; 8475 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 8476 TypoCorrection Correction; 8477 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 8478 unsigned DiagMsg = 8479 IsLocalFriend ? diag::err_no_matching_local_friend : 8480 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match : 8481 diag::err_member_decl_does_not_match; 8482 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 8483 IsLocalFriend ? Sema::LookupLocalFriendName 8484 : Sema::LookupOrdinaryName, 8485 Sema::ForVisibleRedeclaration); 8486 8487 NewFD->setInvalidDecl(); 8488 if (IsLocalFriend) 8489 SemaRef.LookupName(Prev, S); 8490 else 8491 SemaRef.LookupQualifiedName(Prev, NewDC); 8492 assert(!Prev.isAmbiguous() && 8493 "Cannot have an ambiguity in previous-declaration lookup"); 8494 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 8495 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD, 8496 MD ? MD->getParent() : nullptr); 8497 if (!Prev.empty()) { 8498 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 8499 Func != FuncEnd; ++Func) { 8500 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 8501 if (FD && 8502 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8503 // Add 1 to the index so that 0 can mean the mismatch didn't 8504 // involve a parameter 8505 unsigned ParamNum = 8506 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 8507 NearMatches.push_back(std::make_pair(FD, ParamNum)); 8508 } 8509 } 8510 // If the qualified name lookup yielded nothing, try typo correction 8511 } else if ((Correction = SemaRef.CorrectTypo( 8512 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 8513 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery, 8514 IsLocalFriend ? nullptr : NewDC))) { 8515 // Set up everything for the call to ActOnFunctionDeclarator 8516 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 8517 ExtraArgs.D.getIdentifierLoc()); 8518 Previous.clear(); 8519 Previous.setLookupName(Correction.getCorrection()); 8520 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 8521 CDeclEnd = Correction.end(); 8522 CDecl != CDeclEnd; ++CDecl) { 8523 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8524 if (FD && !FD->hasBody() && 8525 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8526 Previous.addDecl(FD); 8527 } 8528 } 8529 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 8530 8531 NamedDecl *Result; 8532 // Retry building the function declaration with the new previous 8533 // declarations, and with errors suppressed. 8534 { 8535 // Trap errors. 8536 Sema::SFINAETrap Trap(SemaRef); 8537 8538 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 8539 // pieces need to verify the typo-corrected C++ declaration and hopefully 8540 // eliminate the need for the parameter pack ExtraArgs. 8541 Result = SemaRef.ActOnFunctionDeclarator( 8542 ExtraArgs.S, ExtraArgs.D, 8543 Correction.getCorrectionDecl()->getDeclContext(), 8544 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 8545 ExtraArgs.AddToScope); 8546 8547 if (Trap.hasErrorOccurred()) 8548 Result = nullptr; 8549 } 8550 8551 if (Result) { 8552 // Determine which correction we picked. 8553 Decl *Canonical = Result->getCanonicalDecl(); 8554 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 8555 I != E; ++I) 8556 if ((*I)->getCanonicalDecl() == Canonical) 8557 Correction.setCorrectionDecl(*I); 8558 8559 // Let Sema know about the correction. 8560 SemaRef.MarkTypoCorrectedFunctionDefinition(Result); 8561 SemaRef.diagnoseTypo( 8562 Correction, 8563 SemaRef.PDiag(IsLocalFriend 8564 ? diag::err_no_matching_local_friend_suggest 8565 : diag::err_member_decl_does_not_match_suggest) 8566 << Name << NewDC << IsDefinition); 8567 return Result; 8568 } 8569 8570 // Pretend the typo correction never occurred 8571 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 8572 ExtraArgs.D.getIdentifierLoc()); 8573 ExtraArgs.D.setRedeclaration(wasRedeclaration); 8574 Previous.clear(); 8575 Previous.setLookupName(Name); 8576 } 8577 8578 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 8579 << Name << NewDC << IsDefinition << NewFD->getLocation(); 8580 8581 bool NewFDisConst = false; 8582 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 8583 NewFDisConst = NewMD->isConst(); 8584 8585 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 8586 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 8587 NearMatch != NearMatchEnd; ++NearMatch) { 8588 FunctionDecl *FD = NearMatch->first; 8589 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 8590 bool FDisConst = MD && MD->isConst(); 8591 bool IsMember = MD || !IsLocalFriend; 8592 8593 // FIXME: These notes are poorly worded for the local friend case. 8594 if (unsigned Idx = NearMatch->second) { 8595 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 8596 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 8597 if (Loc.isInvalid()) Loc = FD->getLocation(); 8598 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 8599 : diag::note_local_decl_close_param_match) 8600 << Idx << FDParam->getType() 8601 << NewFD->getParamDecl(Idx - 1)->getType(); 8602 } else if (FDisConst != NewFDisConst) { 8603 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 8604 << NewFDisConst << FD->getSourceRange().getEnd() 8605 << (NewFDisConst 8606 ? FixItHint::CreateRemoval(ExtraArgs.D.getFunctionTypeInfo() 8607 .getConstQualifierLoc()) 8608 : FixItHint::CreateInsertion(ExtraArgs.D.getFunctionTypeInfo() 8609 .getRParenLoc() 8610 .getLocWithOffset(1), 8611 " const")); 8612 } else 8613 SemaRef.Diag(FD->getLocation(), 8614 IsMember ? diag::note_member_def_close_match 8615 : diag::note_local_decl_close_match); 8616 } 8617 return nullptr; 8618 } 8619 8620 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 8621 switch (D.getDeclSpec().getStorageClassSpec()) { 8622 default: llvm_unreachable("Unknown storage class!"); 8623 case DeclSpec::SCS_auto: 8624 case DeclSpec::SCS_register: 8625 case DeclSpec::SCS_mutable: 8626 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8627 diag::err_typecheck_sclass_func); 8628 D.getMutableDeclSpec().ClearStorageClassSpecs(); 8629 D.setInvalidType(); 8630 break; 8631 case DeclSpec::SCS_unspecified: break; 8632 case DeclSpec::SCS_extern: 8633 if (D.getDeclSpec().isExternInLinkageSpec()) 8634 return SC_None; 8635 return SC_Extern; 8636 case DeclSpec::SCS_static: { 8637 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 8638 // C99 6.7.1p5: 8639 // The declaration of an identifier for a function that has 8640 // block scope shall have no explicit storage-class specifier 8641 // other than extern 8642 // See also (C++ [dcl.stc]p4). 8643 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8644 diag::err_static_block_func); 8645 break; 8646 } else 8647 return SC_Static; 8648 } 8649 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 8650 } 8651 8652 // No explicit storage class has already been returned 8653 return SC_None; 8654 } 8655 8656 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 8657 DeclContext *DC, QualType &R, 8658 TypeSourceInfo *TInfo, 8659 StorageClass SC, 8660 bool &IsVirtualOkay) { 8661 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 8662 DeclarationName Name = NameInfo.getName(); 8663 8664 FunctionDecl *NewFD = nullptr; 8665 bool isInline = D.getDeclSpec().isInlineSpecified(); 8666 8667 if (!SemaRef.getLangOpts().CPlusPlus) { 8668 // Determine whether the function was written with a 8669 // prototype. This true when: 8670 // - there is a prototype in the declarator, or 8671 // - the type R of the function is some kind of typedef or other non- 8672 // attributed reference to a type name (which eventually refers to a 8673 // function type). 8674 bool HasPrototype = 8675 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 8676 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 8677 8678 NewFD = FunctionDecl::Create( 8679 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC, 8680 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype, 8681 ConstexprSpecKind::Unspecified, 8682 /*TrailingRequiresClause=*/nullptr); 8683 if (D.isInvalidType()) 8684 NewFD->setInvalidDecl(); 8685 8686 return NewFD; 8687 } 8688 8689 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier(); 8690 8691 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 8692 if (ConstexprKind == ConstexprSpecKind::Constinit) { 8693 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(), 8694 diag::err_constexpr_wrong_decl_kind) 8695 << static_cast<int>(ConstexprKind); 8696 ConstexprKind = ConstexprSpecKind::Unspecified; 8697 D.getMutableDeclSpec().ClearConstexprSpec(); 8698 } 8699 Expr *TrailingRequiresClause = D.getTrailingRequiresClause(); 8700 8701 // Check that the return type is not an abstract class type. 8702 // For record types, this is done by the AbstractClassUsageDiagnoser once 8703 // the class has been completely parsed. 8704 if (!DC->isRecord() && 8705 SemaRef.RequireNonAbstractType( 8706 D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(), 8707 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 8708 D.setInvalidType(); 8709 8710 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 8711 // This is a C++ constructor declaration. 8712 assert(DC->isRecord() && 8713 "Constructors can only be declared in a member context"); 8714 8715 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 8716 return CXXConstructorDecl::Create( 8717 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8718 TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(), 8719 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind, 8720 InheritedConstructor(), TrailingRequiresClause); 8721 8722 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8723 // This is a C++ destructor declaration. 8724 if (DC->isRecord()) { 8725 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 8726 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 8727 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 8728 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo, 8729 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 8730 /*isImplicitlyDeclared=*/false, ConstexprKind, 8731 TrailingRequiresClause); 8732 8733 // If the destructor needs an implicit exception specification, set it 8734 // now. FIXME: It'd be nice to be able to create the right type to start 8735 // with, but the type needs to reference the destructor declaration. 8736 if (SemaRef.getLangOpts().CPlusPlus11) 8737 SemaRef.AdjustDestructorExceptionSpec(NewDD); 8738 8739 IsVirtualOkay = true; 8740 return NewDD; 8741 8742 } else { 8743 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 8744 D.setInvalidType(); 8745 8746 // Create a FunctionDecl to satisfy the function definition parsing 8747 // code path. 8748 return FunctionDecl::Create( 8749 SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R, 8750 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 8751 /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause); 8752 } 8753 8754 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 8755 if (!DC->isRecord()) { 8756 SemaRef.Diag(D.getIdentifierLoc(), 8757 diag::err_conv_function_not_member); 8758 return nullptr; 8759 } 8760 8761 SemaRef.CheckConversionDeclarator(D, R, SC); 8762 if (D.isInvalidType()) 8763 return nullptr; 8764 8765 IsVirtualOkay = true; 8766 return CXXConversionDecl::Create( 8767 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8768 TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 8769 ExplicitSpecifier, ConstexprKind, SourceLocation(), 8770 TrailingRequiresClause); 8771 8772 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 8773 if (TrailingRequiresClause) 8774 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(), 8775 diag::err_trailing_requires_clause_on_deduction_guide) 8776 << TrailingRequiresClause->getSourceRange(); 8777 SemaRef.CheckDeductionGuideDeclarator(D, R, SC); 8778 8779 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8780 ExplicitSpecifier, NameInfo, R, TInfo, 8781 D.getEndLoc()); 8782 } else if (DC->isRecord()) { 8783 // If the name of the function is the same as the name of the record, 8784 // then this must be an invalid constructor that has a return type. 8785 // (The parser checks for a return type and makes the declarator a 8786 // constructor if it has no return type). 8787 if (Name.getAsIdentifierInfo() && 8788 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 8789 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 8790 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8791 << SourceRange(D.getIdentifierLoc()); 8792 return nullptr; 8793 } 8794 8795 // This is a C++ method declaration. 8796 CXXMethodDecl *Ret = CXXMethodDecl::Create( 8797 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8798 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 8799 ConstexprKind, SourceLocation(), TrailingRequiresClause); 8800 IsVirtualOkay = !Ret->isStatic(); 8801 return Ret; 8802 } else { 8803 bool isFriend = 8804 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 8805 if (!isFriend && SemaRef.CurContext->isRecord()) 8806 return nullptr; 8807 8808 // Determine whether the function was written with a 8809 // prototype. This true when: 8810 // - we're in C++ (where every function has a prototype), 8811 return FunctionDecl::Create( 8812 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC, 8813 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 8814 true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause); 8815 } 8816 } 8817 8818 enum OpenCLParamType { 8819 ValidKernelParam, 8820 PtrPtrKernelParam, 8821 PtrKernelParam, 8822 InvalidAddrSpacePtrKernelParam, 8823 InvalidKernelParam, 8824 RecordKernelParam 8825 }; 8826 8827 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) { 8828 // Size dependent types are just typedefs to normal integer types 8829 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to 8830 // integers other than by their names. 8831 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"}; 8832 8833 // Remove typedefs one by one until we reach a typedef 8834 // for a size dependent type. 8835 QualType DesugaredTy = Ty; 8836 do { 8837 ArrayRef<StringRef> Names(SizeTypeNames); 8838 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString()); 8839 if (Names.end() != Match) 8840 return true; 8841 8842 Ty = DesugaredTy; 8843 DesugaredTy = Ty.getSingleStepDesugaredType(C); 8844 } while (DesugaredTy != Ty); 8845 8846 return false; 8847 } 8848 8849 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 8850 if (PT->isDependentType()) 8851 return InvalidKernelParam; 8852 8853 if (PT->isPointerType() || PT->isReferenceType()) { 8854 QualType PointeeType = PT->getPointeeType(); 8855 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 8856 PointeeType.getAddressSpace() == LangAS::opencl_private || 8857 PointeeType.getAddressSpace() == LangAS::Default) 8858 return InvalidAddrSpacePtrKernelParam; 8859 8860 if (PointeeType->isPointerType()) { 8861 // This is a pointer to pointer parameter. 8862 // Recursively check inner type. 8863 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType); 8864 if (ParamKind == InvalidAddrSpacePtrKernelParam || 8865 ParamKind == InvalidKernelParam) 8866 return ParamKind; 8867 8868 return PtrPtrKernelParam; 8869 } 8870 8871 // C++ for OpenCL v1.0 s2.4: 8872 // Moreover the types used in parameters of the kernel functions must be: 8873 // Standard layout types for pointer parameters. The same applies to 8874 // reference if an implementation supports them in kernel parameters. 8875 if (S.getLangOpts().OpenCLCPlusPlus && 8876 !S.getOpenCLOptions().isAvailableOption( 8877 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) && 8878 !PointeeType->isAtomicType() && !PointeeType->isVoidType() && 8879 !PointeeType->isStandardLayoutType()) 8880 return InvalidKernelParam; 8881 8882 return PtrKernelParam; 8883 } 8884 8885 // OpenCL v1.2 s6.9.k: 8886 // Arguments to kernel functions in a program cannot be declared with the 8887 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8888 // uintptr_t or a struct and/or union that contain fields declared to be one 8889 // of these built-in scalar types. 8890 if (isOpenCLSizeDependentType(S.getASTContext(), PT)) 8891 return InvalidKernelParam; 8892 8893 if (PT->isImageType()) 8894 return PtrKernelParam; 8895 8896 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) 8897 return InvalidKernelParam; 8898 8899 // OpenCL extension spec v1.2 s9.5: 8900 // This extension adds support for half scalar and vector types as built-in 8901 // types that can be used for arithmetic operations, conversions etc. 8902 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) && 8903 PT->isHalfType()) 8904 return InvalidKernelParam; 8905 8906 // Look into an array argument to check if it has a forbidden type. 8907 if (PT->isArrayType()) { 8908 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType(); 8909 // Call ourself to check an underlying type of an array. Since the 8910 // getPointeeOrArrayElementType returns an innermost type which is not an 8911 // array, this recursive call only happens once. 8912 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0)); 8913 } 8914 8915 // C++ for OpenCL v1.0 s2.4: 8916 // Moreover the types used in parameters of the kernel functions must be: 8917 // Trivial and standard-layout types C++17 [basic.types] (plain old data 8918 // types) for parameters passed by value; 8919 if (S.getLangOpts().OpenCLCPlusPlus && 8920 !S.getOpenCLOptions().isAvailableOption( 8921 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) && 8922 !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context)) 8923 return InvalidKernelParam; 8924 8925 if (PT->isRecordType()) 8926 return RecordKernelParam; 8927 8928 return ValidKernelParam; 8929 } 8930 8931 static void checkIsValidOpenCLKernelParameter( 8932 Sema &S, 8933 Declarator &D, 8934 ParmVarDecl *Param, 8935 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 8936 QualType PT = Param->getType(); 8937 8938 // Cache the valid types we encounter to avoid rechecking structs that are 8939 // used again 8940 if (ValidTypes.count(PT.getTypePtr())) 8941 return; 8942 8943 switch (getOpenCLKernelParameterType(S, PT)) { 8944 case PtrPtrKernelParam: 8945 // OpenCL v3.0 s6.11.a: 8946 // A kernel function argument cannot be declared as a pointer to a pointer 8947 // type. [...] This restriction only applies to OpenCL C 1.2 or below. 8948 if (S.getLangOpts().getOpenCLCompatibleVersion() <= 120) { 8949 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 8950 D.setInvalidType(); 8951 return; 8952 } 8953 8954 ValidTypes.insert(PT.getTypePtr()); 8955 return; 8956 8957 case InvalidAddrSpacePtrKernelParam: 8958 // OpenCL v1.0 s6.5: 8959 // __kernel function arguments declared to be a pointer of a type can point 8960 // to one of the following address spaces only : __global, __local or 8961 // __constant. 8962 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 8963 D.setInvalidType(); 8964 return; 8965 8966 // OpenCL v1.2 s6.9.k: 8967 // Arguments to kernel functions in a program cannot be declared with the 8968 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8969 // uintptr_t or a struct and/or union that contain fields declared to be 8970 // one of these built-in scalar types. 8971 8972 case InvalidKernelParam: 8973 // OpenCL v1.2 s6.8 n: 8974 // A kernel function argument cannot be declared 8975 // of event_t type. 8976 // Do not diagnose half type since it is diagnosed as invalid argument 8977 // type for any function elsewhere. 8978 if (!PT->isHalfType()) { 8979 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8980 8981 // Explain what typedefs are involved. 8982 const TypedefType *Typedef = nullptr; 8983 while ((Typedef = PT->getAs<TypedefType>())) { 8984 SourceLocation Loc = Typedef->getDecl()->getLocation(); 8985 // SourceLocation may be invalid for a built-in type. 8986 if (Loc.isValid()) 8987 S.Diag(Loc, diag::note_entity_declared_at) << PT; 8988 PT = Typedef->desugar(); 8989 } 8990 } 8991 8992 D.setInvalidType(); 8993 return; 8994 8995 case PtrKernelParam: 8996 case ValidKernelParam: 8997 ValidTypes.insert(PT.getTypePtr()); 8998 return; 8999 9000 case RecordKernelParam: 9001 break; 9002 } 9003 9004 // Track nested structs we will inspect 9005 SmallVector<const Decl *, 4> VisitStack; 9006 9007 // Track where we are in the nested structs. Items will migrate from 9008 // VisitStack to HistoryStack as we do the DFS for bad field. 9009 SmallVector<const FieldDecl *, 4> HistoryStack; 9010 HistoryStack.push_back(nullptr); 9011 9012 // At this point we already handled everything except of a RecordType or 9013 // an ArrayType of a RecordType. 9014 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type."); 9015 const RecordType *RecTy = 9016 PT->getPointeeOrArrayElementType()->getAs<RecordType>(); 9017 const RecordDecl *OrigRecDecl = RecTy->getDecl(); 9018 9019 VisitStack.push_back(RecTy->getDecl()); 9020 assert(VisitStack.back() && "First decl null?"); 9021 9022 do { 9023 const Decl *Next = VisitStack.pop_back_val(); 9024 if (!Next) { 9025 assert(!HistoryStack.empty()); 9026 // Found a marker, we have gone up a level 9027 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 9028 ValidTypes.insert(Hist->getType().getTypePtr()); 9029 9030 continue; 9031 } 9032 9033 // Adds everything except the original parameter declaration (which is not a 9034 // field itself) to the history stack. 9035 const RecordDecl *RD; 9036 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 9037 HistoryStack.push_back(Field); 9038 9039 QualType FieldTy = Field->getType(); 9040 // Other field types (known to be valid or invalid) are handled while we 9041 // walk around RecordDecl::fields(). 9042 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) && 9043 "Unexpected type."); 9044 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType(); 9045 9046 RD = FieldRecTy->castAs<RecordType>()->getDecl(); 9047 } else { 9048 RD = cast<RecordDecl>(Next); 9049 } 9050 9051 // Add a null marker so we know when we've gone back up a level 9052 VisitStack.push_back(nullptr); 9053 9054 for (const auto *FD : RD->fields()) { 9055 QualType QT = FD->getType(); 9056 9057 if (ValidTypes.count(QT.getTypePtr())) 9058 continue; 9059 9060 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 9061 if (ParamType == ValidKernelParam) 9062 continue; 9063 9064 if (ParamType == RecordKernelParam) { 9065 VisitStack.push_back(FD); 9066 continue; 9067 } 9068 9069 // OpenCL v1.2 s6.9.p: 9070 // Arguments to kernel functions that are declared to be a struct or union 9071 // do not allow OpenCL objects to be passed as elements of the struct or 9072 // union. 9073 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 9074 ParamType == InvalidAddrSpacePtrKernelParam) { 9075 S.Diag(Param->getLocation(), 9076 diag::err_record_with_pointers_kernel_param) 9077 << PT->isUnionType() 9078 << PT; 9079 } else { 9080 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 9081 } 9082 9083 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type) 9084 << OrigRecDecl->getDeclName(); 9085 9086 // We have an error, now let's go back up through history and show where 9087 // the offending field came from 9088 for (ArrayRef<const FieldDecl *>::const_iterator 9089 I = HistoryStack.begin() + 1, 9090 E = HistoryStack.end(); 9091 I != E; ++I) { 9092 const FieldDecl *OuterField = *I; 9093 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 9094 << OuterField->getType(); 9095 } 9096 9097 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 9098 << QT->isPointerType() 9099 << QT; 9100 D.setInvalidType(); 9101 return; 9102 } 9103 } while (!VisitStack.empty()); 9104 } 9105 9106 /// Find the DeclContext in which a tag is implicitly declared if we see an 9107 /// elaborated type specifier in the specified context, and lookup finds 9108 /// nothing. 9109 static DeclContext *getTagInjectionContext(DeclContext *DC) { 9110 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 9111 DC = DC->getParent(); 9112 return DC; 9113 } 9114 9115 /// Find the Scope in which a tag is implicitly declared if we see an 9116 /// elaborated type specifier in the specified context, and lookup finds 9117 /// nothing. 9118 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 9119 while (S->isClassScope() || 9120 (LangOpts.CPlusPlus && 9121 S->isFunctionPrototypeScope()) || 9122 ((S->getFlags() & Scope::DeclScope) == 0) || 9123 (S->getEntity() && S->getEntity()->isTransparentContext())) 9124 S = S->getParent(); 9125 return S; 9126 } 9127 9128 NamedDecl* 9129 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 9130 TypeSourceInfo *TInfo, LookupResult &Previous, 9131 MultiTemplateParamsArg TemplateParamListsRef, 9132 bool &AddToScope) { 9133 QualType R = TInfo->getType(); 9134 9135 assert(R->isFunctionType()); 9136 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr()) 9137 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call); 9138 9139 SmallVector<TemplateParameterList *, 4> TemplateParamLists; 9140 llvm::append_range(TemplateParamLists, TemplateParamListsRef); 9141 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) { 9142 if (!TemplateParamLists.empty() && 9143 Invented->getDepth() == TemplateParamLists.back()->getDepth()) 9144 TemplateParamLists.back() = Invented; 9145 else 9146 TemplateParamLists.push_back(Invented); 9147 } 9148 9149 // TODO: consider using NameInfo for diagnostic. 9150 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 9151 DeclarationName Name = NameInfo.getName(); 9152 StorageClass SC = getFunctionStorageClass(*this, D); 9153 9154 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 9155 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 9156 diag::err_invalid_thread) 9157 << DeclSpec::getSpecifierName(TSCS); 9158 9159 if (D.isFirstDeclarationOfMember()) 9160 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 9161 D.getIdentifierLoc()); 9162 9163 bool isFriend = false; 9164 FunctionTemplateDecl *FunctionTemplate = nullptr; 9165 bool isMemberSpecialization = false; 9166 bool isFunctionTemplateSpecialization = false; 9167 9168 bool isDependentClassScopeExplicitSpecialization = false; 9169 bool HasExplicitTemplateArgs = false; 9170 TemplateArgumentListInfo TemplateArgs; 9171 9172 bool isVirtualOkay = false; 9173 9174 DeclContext *OriginalDC = DC; 9175 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 9176 9177 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 9178 isVirtualOkay); 9179 if (!NewFD) return nullptr; 9180 9181 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 9182 NewFD->setTopLevelDeclInObjCContainer(); 9183 9184 // Set the lexical context. If this is a function-scope declaration, or has a 9185 // C++ scope specifier, or is the object of a friend declaration, the lexical 9186 // context will be different from the semantic context. 9187 NewFD->setLexicalDeclContext(CurContext); 9188 9189 if (IsLocalExternDecl) 9190 NewFD->setLocalExternDecl(); 9191 9192 if (getLangOpts().CPlusPlus) { 9193 bool isInline = D.getDeclSpec().isInlineSpecified(); 9194 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 9195 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier(); 9196 isFriend = D.getDeclSpec().isFriendSpecified(); 9197 if (isFriend && !isInline && D.isFunctionDefinition()) { 9198 // C++ [class.friend]p5 9199 // A function can be defined in a friend declaration of a 9200 // class . . . . Such a function is implicitly inline. 9201 NewFD->setImplicitlyInline(); 9202 } 9203 9204 // If this is a method defined in an __interface, and is not a constructor 9205 // or an overloaded operator, then set the pure flag (isVirtual will already 9206 // return true). 9207 if (const CXXRecordDecl *Parent = 9208 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 9209 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 9210 NewFD->setPure(true); 9211 9212 // C++ [class.union]p2 9213 // A union can have member functions, but not virtual functions. 9214 if (isVirtual && Parent->isUnion()) { 9215 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 9216 NewFD->setInvalidDecl(); 9217 } 9218 if ((Parent->isClass() || Parent->isStruct()) && 9219 Parent->hasAttr<SYCLSpecialClassAttr>() && 9220 NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() && 9221 NewFD->getName() == "__init" && D.isFunctionDefinition()) { 9222 if (auto *Def = Parent->getDefinition()) 9223 Def->setInitMethod(true); 9224 } 9225 } 9226 9227 SetNestedNameSpecifier(*this, NewFD, D); 9228 isMemberSpecialization = false; 9229 isFunctionTemplateSpecialization = false; 9230 if (D.isInvalidType()) 9231 NewFD->setInvalidDecl(); 9232 9233 // Match up the template parameter lists with the scope specifier, then 9234 // determine whether we have a template or a template specialization. 9235 bool Invalid = false; 9236 TemplateParameterList *TemplateParams = 9237 MatchTemplateParametersToScopeSpecifier( 9238 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 9239 D.getCXXScopeSpec(), 9240 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 9241 ? D.getName().TemplateId 9242 : nullptr, 9243 TemplateParamLists, isFriend, isMemberSpecialization, 9244 Invalid); 9245 if (TemplateParams) { 9246 // Check that we can declare a template here. 9247 if (CheckTemplateDeclScope(S, TemplateParams)) 9248 NewFD->setInvalidDecl(); 9249 9250 if (TemplateParams->size() > 0) { 9251 // This is a function template 9252 9253 // A destructor cannot be a template. 9254 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 9255 Diag(NewFD->getLocation(), diag::err_destructor_template); 9256 NewFD->setInvalidDecl(); 9257 } 9258 9259 // If we're adding a template to a dependent context, we may need to 9260 // rebuilding some of the types used within the template parameter list, 9261 // now that we know what the current instantiation is. 9262 if (DC->isDependentContext()) { 9263 ContextRAII SavedContext(*this, DC); 9264 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 9265 Invalid = true; 9266 } 9267 9268 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 9269 NewFD->getLocation(), 9270 Name, TemplateParams, 9271 NewFD); 9272 FunctionTemplate->setLexicalDeclContext(CurContext); 9273 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 9274 9275 // For source fidelity, store the other template param lists. 9276 if (TemplateParamLists.size() > 1) { 9277 NewFD->setTemplateParameterListsInfo(Context, 9278 ArrayRef<TemplateParameterList *>(TemplateParamLists) 9279 .drop_back(1)); 9280 } 9281 } else { 9282 // This is a function template specialization. 9283 isFunctionTemplateSpecialization = true; 9284 // For source fidelity, store all the template param lists. 9285 if (TemplateParamLists.size() > 0) 9286 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 9287 9288 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 9289 if (isFriend) { 9290 // We want to remove the "template<>", found here. 9291 SourceRange RemoveRange = TemplateParams->getSourceRange(); 9292 9293 // If we remove the template<> and the name is not a 9294 // template-id, we're actually silently creating a problem: 9295 // the friend declaration will refer to an untemplated decl, 9296 // and clearly the user wants a template specialization. So 9297 // we need to insert '<>' after the name. 9298 SourceLocation InsertLoc; 9299 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 9300 InsertLoc = D.getName().getSourceRange().getEnd(); 9301 InsertLoc = getLocForEndOfToken(InsertLoc); 9302 } 9303 9304 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 9305 << Name << RemoveRange 9306 << FixItHint::CreateRemoval(RemoveRange) 9307 << FixItHint::CreateInsertion(InsertLoc, "<>"); 9308 Invalid = true; 9309 } 9310 } 9311 } else { 9312 // Check that we can declare a template here. 9313 if (!TemplateParamLists.empty() && isMemberSpecialization && 9314 CheckTemplateDeclScope(S, TemplateParamLists.back())) 9315 NewFD->setInvalidDecl(); 9316 9317 // All template param lists were matched against the scope specifier: 9318 // this is NOT (an explicit specialization of) a template. 9319 if (TemplateParamLists.size() > 0) 9320 // For source fidelity, store all the template param lists. 9321 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 9322 } 9323 9324 if (Invalid) { 9325 NewFD->setInvalidDecl(); 9326 if (FunctionTemplate) 9327 FunctionTemplate->setInvalidDecl(); 9328 } 9329 9330 // C++ [dcl.fct.spec]p5: 9331 // The virtual specifier shall only be used in declarations of 9332 // nonstatic class member functions that appear within a 9333 // member-specification of a class declaration; see 10.3. 9334 // 9335 if (isVirtual && !NewFD->isInvalidDecl()) { 9336 if (!isVirtualOkay) { 9337 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9338 diag::err_virtual_non_function); 9339 } else if (!CurContext->isRecord()) { 9340 // 'virtual' was specified outside of the class. 9341 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9342 diag::err_virtual_out_of_class) 9343 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 9344 } else if (NewFD->getDescribedFunctionTemplate()) { 9345 // C++ [temp.mem]p3: 9346 // A member function template shall not be virtual. 9347 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9348 diag::err_virtual_member_function_template) 9349 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 9350 } else { 9351 // Okay: Add virtual to the method. 9352 NewFD->setVirtualAsWritten(true); 9353 } 9354 9355 if (getLangOpts().CPlusPlus14 && 9356 NewFD->getReturnType()->isUndeducedType()) 9357 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 9358 } 9359 9360 if (getLangOpts().CPlusPlus14 && 9361 (NewFD->isDependentContext() || 9362 (isFriend && CurContext->isDependentContext())) && 9363 NewFD->getReturnType()->isUndeducedType()) { 9364 // If the function template is referenced directly (for instance, as a 9365 // member of the current instantiation), pretend it has a dependent type. 9366 // This is not really justified by the standard, but is the only sane 9367 // thing to do. 9368 // FIXME: For a friend function, we have not marked the function as being 9369 // a friend yet, so 'isDependentContext' on the FD doesn't work. 9370 const FunctionProtoType *FPT = 9371 NewFD->getType()->castAs<FunctionProtoType>(); 9372 QualType Result = SubstAutoTypeDependent(FPT->getReturnType()); 9373 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 9374 FPT->getExtProtoInfo())); 9375 } 9376 9377 // C++ [dcl.fct.spec]p3: 9378 // The inline specifier shall not appear on a block scope function 9379 // declaration. 9380 if (isInline && !NewFD->isInvalidDecl()) { 9381 if (CurContext->isFunctionOrMethod()) { 9382 // 'inline' is not allowed on block scope function declaration. 9383 Diag(D.getDeclSpec().getInlineSpecLoc(), 9384 diag::err_inline_declaration_block_scope) << Name 9385 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 9386 } 9387 } 9388 9389 // C++ [dcl.fct.spec]p6: 9390 // The explicit specifier shall be used only in the declaration of a 9391 // constructor or conversion function within its class definition; 9392 // see 12.3.1 and 12.3.2. 9393 if (hasExplicit && !NewFD->isInvalidDecl() && 9394 !isa<CXXDeductionGuideDecl>(NewFD)) { 9395 if (!CurContext->isRecord()) { 9396 // 'explicit' was specified outside of the class. 9397 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9398 diag::err_explicit_out_of_class) 9399 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9400 } else if (!isa<CXXConstructorDecl>(NewFD) && 9401 !isa<CXXConversionDecl>(NewFD)) { 9402 // 'explicit' was specified on a function that wasn't a constructor 9403 // or conversion function. 9404 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9405 diag::err_explicit_non_ctor_or_conv_function) 9406 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9407 } 9408 } 9409 9410 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 9411 if (ConstexprKind != ConstexprSpecKind::Unspecified) { 9412 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 9413 // are implicitly inline. 9414 NewFD->setImplicitlyInline(); 9415 9416 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 9417 // be either constructors or to return a literal type. Therefore, 9418 // destructors cannot be declared constexpr. 9419 if (isa<CXXDestructorDecl>(NewFD) && 9420 (!getLangOpts().CPlusPlus20 || 9421 ConstexprKind == ConstexprSpecKind::Consteval)) { 9422 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor) 9423 << static_cast<int>(ConstexprKind); 9424 NewFD->setConstexprKind(getLangOpts().CPlusPlus20 9425 ? ConstexprSpecKind::Unspecified 9426 : ConstexprSpecKind::Constexpr); 9427 } 9428 // C++20 [dcl.constexpr]p2: An allocation function, or a 9429 // deallocation function shall not be declared with the consteval 9430 // specifier. 9431 if (ConstexprKind == ConstexprSpecKind::Consteval && 9432 (NewFD->getOverloadedOperator() == OO_New || 9433 NewFD->getOverloadedOperator() == OO_Array_New || 9434 NewFD->getOverloadedOperator() == OO_Delete || 9435 NewFD->getOverloadedOperator() == OO_Array_Delete)) { 9436 Diag(D.getDeclSpec().getConstexprSpecLoc(), 9437 diag::err_invalid_consteval_decl_kind) 9438 << NewFD; 9439 NewFD->setConstexprKind(ConstexprSpecKind::Constexpr); 9440 } 9441 } 9442 9443 // If __module_private__ was specified, mark the function accordingly. 9444 if (D.getDeclSpec().isModulePrivateSpecified()) { 9445 if (isFunctionTemplateSpecialization) { 9446 SourceLocation ModulePrivateLoc 9447 = D.getDeclSpec().getModulePrivateSpecLoc(); 9448 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 9449 << 0 9450 << FixItHint::CreateRemoval(ModulePrivateLoc); 9451 } else { 9452 NewFD->setModulePrivate(); 9453 if (FunctionTemplate) 9454 FunctionTemplate->setModulePrivate(); 9455 } 9456 } 9457 9458 if (isFriend) { 9459 if (FunctionTemplate) { 9460 FunctionTemplate->setObjectOfFriendDecl(); 9461 FunctionTemplate->setAccess(AS_public); 9462 } 9463 NewFD->setObjectOfFriendDecl(); 9464 NewFD->setAccess(AS_public); 9465 } 9466 9467 // If a function is defined as defaulted or deleted, mark it as such now. 9468 // We'll do the relevant checks on defaulted / deleted functions later. 9469 switch (D.getFunctionDefinitionKind()) { 9470 case FunctionDefinitionKind::Declaration: 9471 case FunctionDefinitionKind::Definition: 9472 break; 9473 9474 case FunctionDefinitionKind::Defaulted: 9475 NewFD->setDefaulted(); 9476 break; 9477 9478 case FunctionDefinitionKind::Deleted: 9479 NewFD->setDeletedAsWritten(); 9480 break; 9481 } 9482 9483 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 9484 D.isFunctionDefinition()) { 9485 // C++ [class.mfct]p2: 9486 // A member function may be defined (8.4) in its class definition, in 9487 // which case it is an inline member function (7.1.2) 9488 NewFD->setImplicitlyInline(); 9489 } 9490 9491 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 9492 !CurContext->isRecord()) { 9493 // C++ [class.static]p1: 9494 // A data or function member of a class may be declared static 9495 // in a class definition, in which case it is a static member of 9496 // the class. 9497 9498 // Complain about the 'static' specifier if it's on an out-of-line 9499 // member function definition. 9500 9501 // MSVC permits the use of a 'static' storage specifier on an out-of-line 9502 // member function template declaration and class member template 9503 // declaration (MSVC versions before 2015), warn about this. 9504 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 9505 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 9506 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) || 9507 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate())) 9508 ? diag::ext_static_out_of_line : diag::err_static_out_of_line) 9509 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 9510 } 9511 9512 // C++11 [except.spec]p15: 9513 // A deallocation function with no exception-specification is treated 9514 // as if it were specified with noexcept(true). 9515 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 9516 if ((Name.getCXXOverloadedOperator() == OO_Delete || 9517 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 9518 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 9519 NewFD->setType(Context.getFunctionType( 9520 FPT->getReturnType(), FPT->getParamTypes(), 9521 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 9522 } 9523 9524 // Filter out previous declarations that don't match the scope. 9525 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 9526 D.getCXXScopeSpec().isNotEmpty() || 9527 isMemberSpecialization || 9528 isFunctionTemplateSpecialization); 9529 9530 // Handle GNU asm-label extension (encoded as an attribute). 9531 if (Expr *E = (Expr*) D.getAsmLabel()) { 9532 // The parser guarantees this is a string. 9533 StringLiteral *SE = cast<StringLiteral>(E); 9534 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(), 9535 /*IsLiteralLabel=*/true, 9536 SE->getStrTokenLoc(0))); 9537 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 9538 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 9539 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 9540 if (I != ExtnameUndeclaredIdentifiers.end()) { 9541 if (isDeclExternC(NewFD)) { 9542 NewFD->addAttr(I->second); 9543 ExtnameUndeclaredIdentifiers.erase(I); 9544 } else 9545 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 9546 << /*Variable*/0 << NewFD; 9547 } 9548 } 9549 9550 // Copy the parameter declarations from the declarator D to the function 9551 // declaration NewFD, if they are available. First scavenge them into Params. 9552 SmallVector<ParmVarDecl*, 16> Params; 9553 unsigned FTIIdx; 9554 if (D.isFunctionDeclarator(FTIIdx)) { 9555 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 9556 9557 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 9558 // function that takes no arguments, not a function that takes a 9559 // single void argument. 9560 // We let through "const void" here because Sema::GetTypeForDeclarator 9561 // already checks for that case. 9562 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 9563 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 9564 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 9565 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 9566 Param->setDeclContext(NewFD); 9567 Params.push_back(Param); 9568 9569 if (Param->isInvalidDecl()) 9570 NewFD->setInvalidDecl(); 9571 } 9572 } 9573 9574 if (!getLangOpts().CPlusPlus) { 9575 // In C, find all the tag declarations from the prototype and move them 9576 // into the function DeclContext. Remove them from the surrounding tag 9577 // injection context of the function, which is typically but not always 9578 // the TU. 9579 DeclContext *PrototypeTagContext = 9580 getTagInjectionContext(NewFD->getLexicalDeclContext()); 9581 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 9582 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 9583 9584 // We don't want to reparent enumerators. Look at their parent enum 9585 // instead. 9586 if (!TD) { 9587 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 9588 TD = cast<EnumDecl>(ECD->getDeclContext()); 9589 } 9590 if (!TD) 9591 continue; 9592 DeclContext *TagDC = TD->getLexicalDeclContext(); 9593 if (!TagDC->containsDecl(TD)) 9594 continue; 9595 TagDC->removeDecl(TD); 9596 TD->setDeclContext(NewFD); 9597 NewFD->addDecl(TD); 9598 9599 // Preserve the lexical DeclContext if it is not the surrounding tag 9600 // injection context of the FD. In this example, the semantic context of 9601 // E will be f and the lexical context will be S, while both the 9602 // semantic and lexical contexts of S will be f: 9603 // void f(struct S { enum E { a } f; } s); 9604 if (TagDC != PrototypeTagContext) 9605 TD->setLexicalDeclContext(TagDC); 9606 } 9607 } 9608 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 9609 // When we're declaring a function with a typedef, typeof, etc as in the 9610 // following example, we'll need to synthesize (unnamed) 9611 // parameters for use in the declaration. 9612 // 9613 // @code 9614 // typedef void fn(int); 9615 // fn f; 9616 // @endcode 9617 9618 // Synthesize a parameter for each argument type. 9619 for (const auto &AI : FT->param_types()) { 9620 ParmVarDecl *Param = 9621 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 9622 Param->setScopeInfo(0, Params.size()); 9623 Params.push_back(Param); 9624 } 9625 } else { 9626 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 9627 "Should not need args for typedef of non-prototype fn"); 9628 } 9629 9630 // Finally, we know we have the right number of parameters, install them. 9631 NewFD->setParams(Params); 9632 9633 if (D.getDeclSpec().isNoreturnSpecified()) 9634 NewFD->addAttr(C11NoReturnAttr::Create(Context, 9635 D.getDeclSpec().getNoreturnSpecLoc(), 9636 AttributeCommonInfo::AS_Keyword)); 9637 9638 // Functions returning a variably modified type violate C99 6.7.5.2p2 9639 // because all functions have linkage. 9640 if (!NewFD->isInvalidDecl() && 9641 NewFD->getReturnType()->isVariablyModifiedType()) { 9642 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 9643 NewFD->setInvalidDecl(); 9644 } 9645 9646 // Apply an implicit SectionAttr if '#pragma clang section text' is active 9647 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && 9648 !NewFD->hasAttr<SectionAttr>()) 9649 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit( 9650 Context, PragmaClangTextSection.SectionName, 9651 PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma)); 9652 9653 // Apply an implicit SectionAttr if #pragma code_seg is active. 9654 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 9655 !NewFD->hasAttr<SectionAttr>()) { 9656 NewFD->addAttr(SectionAttr::CreateImplicit( 9657 Context, CodeSegStack.CurrentValue->getString(), 9658 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 9659 SectionAttr::Declspec_allocate)); 9660 if (UnifySection(CodeSegStack.CurrentValue->getString(), 9661 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 9662 ASTContext::PSF_Read, 9663 NewFD)) 9664 NewFD->dropAttr<SectionAttr>(); 9665 } 9666 9667 // Apply an implicit CodeSegAttr from class declspec or 9668 // apply an implicit SectionAttr from #pragma code_seg if active. 9669 if (!NewFD->hasAttr<CodeSegAttr>()) { 9670 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD, 9671 D.isFunctionDefinition())) { 9672 NewFD->addAttr(SAttr); 9673 } 9674 } 9675 9676 // Handle attributes. 9677 ProcessDeclAttributes(S, NewFD, D); 9678 9679 if (getLangOpts().OpenCL) { 9680 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 9681 // type declaration will generate a compilation error. 9682 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); 9683 if (AddressSpace != LangAS::Default) { 9684 Diag(NewFD->getLocation(), 9685 diag::err_opencl_return_value_with_address_space); 9686 NewFD->setInvalidDecl(); 9687 } 9688 } 9689 9690 if (!getLangOpts().CPlusPlus) { 9691 // Perform semantic checking on the function declaration. 9692 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9693 CheckMain(NewFD, D.getDeclSpec()); 9694 9695 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9696 CheckMSVCRTEntryPoint(NewFD); 9697 9698 if (!NewFD->isInvalidDecl()) 9699 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9700 isMemberSpecialization)); 9701 else if (!Previous.empty()) 9702 // Recover gracefully from an invalid redeclaration. 9703 D.setRedeclaration(true); 9704 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9705 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9706 "previous declaration set still overloaded"); 9707 9708 // Diagnose no-prototype function declarations with calling conventions that 9709 // don't support variadic calls. Only do this in C and do it after merging 9710 // possibly prototyped redeclarations. 9711 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 9712 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 9713 CallingConv CC = FT->getExtInfo().getCC(); 9714 if (!supportsVariadicCall(CC)) { 9715 // Windows system headers sometimes accidentally use stdcall without 9716 // (void) parameters, so we relax this to a warning. 9717 int DiagID = 9718 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 9719 Diag(NewFD->getLocation(), DiagID) 9720 << FunctionType::getNameForCallConv(CC); 9721 } 9722 } 9723 9724 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() || 9725 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion()) 9726 checkNonTrivialCUnion(NewFD->getReturnType(), 9727 NewFD->getReturnTypeSourceRange().getBegin(), 9728 NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy); 9729 } else { 9730 // C++11 [replacement.functions]p3: 9731 // The program's definitions shall not be specified as inline. 9732 // 9733 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 9734 // 9735 // Suppress the diagnostic if the function is __attribute__((used)), since 9736 // that forces an external definition to be emitted. 9737 if (D.getDeclSpec().isInlineSpecified() && 9738 NewFD->isReplaceableGlobalAllocationFunction() && 9739 !NewFD->hasAttr<UsedAttr>()) 9740 Diag(D.getDeclSpec().getInlineSpecLoc(), 9741 diag::ext_operator_new_delete_declared_inline) 9742 << NewFD->getDeclName(); 9743 9744 // If the declarator is a template-id, translate the parser's template 9745 // argument list into our AST format. 9746 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 9747 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 9748 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 9749 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 9750 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 9751 TemplateId->NumArgs); 9752 translateTemplateArguments(TemplateArgsPtr, 9753 TemplateArgs); 9754 9755 HasExplicitTemplateArgs = true; 9756 9757 if (NewFD->isInvalidDecl()) { 9758 HasExplicitTemplateArgs = false; 9759 } else if (FunctionTemplate) { 9760 // Function template with explicit template arguments. 9761 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 9762 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 9763 9764 HasExplicitTemplateArgs = false; 9765 } else { 9766 assert((isFunctionTemplateSpecialization || 9767 D.getDeclSpec().isFriendSpecified()) && 9768 "should have a 'template<>' for this decl"); 9769 // "friend void foo<>(int);" is an implicit specialization decl. 9770 isFunctionTemplateSpecialization = true; 9771 } 9772 } else if (isFriend && isFunctionTemplateSpecialization) { 9773 // This combination is only possible in a recovery case; the user 9774 // wrote something like: 9775 // template <> friend void foo(int); 9776 // which we're recovering from as if the user had written: 9777 // friend void foo<>(int); 9778 // Go ahead and fake up a template id. 9779 HasExplicitTemplateArgs = true; 9780 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 9781 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 9782 } 9783 9784 // We do not add HD attributes to specializations here because 9785 // they may have different constexpr-ness compared to their 9786 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 9787 // may end up with different effective targets. Instead, a 9788 // specialization inherits its target attributes from its template 9789 // in the CheckFunctionTemplateSpecialization() call below. 9790 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization) 9791 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 9792 9793 // If it's a friend (and only if it's a friend), it's possible 9794 // that either the specialized function type or the specialized 9795 // template is dependent, and therefore matching will fail. In 9796 // this case, don't check the specialization yet. 9797 if (isFunctionTemplateSpecialization && isFriend && 9798 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 9799 TemplateSpecializationType::anyInstantiationDependentTemplateArguments( 9800 TemplateArgs.arguments()))) { 9801 assert(HasExplicitTemplateArgs && 9802 "friend function specialization without template args"); 9803 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 9804 Previous)) 9805 NewFD->setInvalidDecl(); 9806 } else if (isFunctionTemplateSpecialization) { 9807 if (CurContext->isDependentContext() && CurContext->isRecord() 9808 && !isFriend) { 9809 isDependentClassScopeExplicitSpecialization = true; 9810 } else if (!NewFD->isInvalidDecl() && 9811 CheckFunctionTemplateSpecialization( 9812 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), 9813 Previous)) 9814 NewFD->setInvalidDecl(); 9815 9816 // C++ [dcl.stc]p1: 9817 // A storage-class-specifier shall not be specified in an explicit 9818 // specialization (14.7.3) 9819 FunctionTemplateSpecializationInfo *Info = 9820 NewFD->getTemplateSpecializationInfo(); 9821 if (Info && SC != SC_None) { 9822 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 9823 Diag(NewFD->getLocation(), 9824 diag::err_explicit_specialization_inconsistent_storage_class) 9825 << SC 9826 << FixItHint::CreateRemoval( 9827 D.getDeclSpec().getStorageClassSpecLoc()); 9828 9829 else 9830 Diag(NewFD->getLocation(), 9831 diag::ext_explicit_specialization_storage_class) 9832 << FixItHint::CreateRemoval( 9833 D.getDeclSpec().getStorageClassSpecLoc()); 9834 } 9835 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 9836 if (CheckMemberSpecialization(NewFD, Previous)) 9837 NewFD->setInvalidDecl(); 9838 } 9839 9840 // Perform semantic checking on the function declaration. 9841 if (!isDependentClassScopeExplicitSpecialization) { 9842 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9843 CheckMain(NewFD, D.getDeclSpec()); 9844 9845 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9846 CheckMSVCRTEntryPoint(NewFD); 9847 9848 if (!NewFD->isInvalidDecl()) 9849 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9850 isMemberSpecialization)); 9851 else if (!Previous.empty()) 9852 // Recover gracefully from an invalid redeclaration. 9853 D.setRedeclaration(true); 9854 } 9855 9856 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9857 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9858 "previous declaration set still overloaded"); 9859 9860 NamedDecl *PrincipalDecl = (FunctionTemplate 9861 ? cast<NamedDecl>(FunctionTemplate) 9862 : NewFD); 9863 9864 if (isFriend && NewFD->getPreviousDecl()) { 9865 AccessSpecifier Access = AS_public; 9866 if (!NewFD->isInvalidDecl()) 9867 Access = NewFD->getPreviousDecl()->getAccess(); 9868 9869 NewFD->setAccess(Access); 9870 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 9871 } 9872 9873 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 9874 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 9875 PrincipalDecl->setNonMemberOperator(); 9876 9877 // If we have a function template, check the template parameter 9878 // list. This will check and merge default template arguments. 9879 if (FunctionTemplate) { 9880 FunctionTemplateDecl *PrevTemplate = 9881 FunctionTemplate->getPreviousDecl(); 9882 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 9883 PrevTemplate ? PrevTemplate->getTemplateParameters() 9884 : nullptr, 9885 D.getDeclSpec().isFriendSpecified() 9886 ? (D.isFunctionDefinition() 9887 ? TPC_FriendFunctionTemplateDefinition 9888 : TPC_FriendFunctionTemplate) 9889 : (D.getCXXScopeSpec().isSet() && 9890 DC && DC->isRecord() && 9891 DC->isDependentContext()) 9892 ? TPC_ClassTemplateMember 9893 : TPC_FunctionTemplate); 9894 } 9895 9896 if (NewFD->isInvalidDecl()) { 9897 // Ignore all the rest of this. 9898 } else if (!D.isRedeclaration()) { 9899 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 9900 AddToScope }; 9901 // Fake up an access specifier if it's supposed to be a class member. 9902 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 9903 NewFD->setAccess(AS_public); 9904 9905 // Qualified decls generally require a previous declaration. 9906 if (D.getCXXScopeSpec().isSet()) { 9907 // ...with the major exception of templated-scope or 9908 // dependent-scope friend declarations. 9909 9910 // TODO: we currently also suppress this check in dependent 9911 // contexts because (1) the parameter depth will be off when 9912 // matching friend templates and (2) we might actually be 9913 // selecting a friend based on a dependent factor. But there 9914 // are situations where these conditions don't apply and we 9915 // can actually do this check immediately. 9916 // 9917 // Unless the scope is dependent, it's always an error if qualified 9918 // redeclaration lookup found nothing at all. Diagnose that now; 9919 // nothing will diagnose that error later. 9920 if (isFriend && 9921 (D.getCXXScopeSpec().getScopeRep()->isDependent() || 9922 (!Previous.empty() && CurContext->isDependentContext()))) { 9923 // ignore these 9924 } else if (NewFD->isCPUDispatchMultiVersion() || 9925 NewFD->isCPUSpecificMultiVersion()) { 9926 // ignore this, we allow the redeclaration behavior here to create new 9927 // versions of the function. 9928 } else { 9929 // The user tried to provide an out-of-line definition for a 9930 // function that is a member of a class or namespace, but there 9931 // was no such member function declared (C++ [class.mfct]p2, 9932 // C++ [namespace.memdef]p2). For example: 9933 // 9934 // class X { 9935 // void f() const; 9936 // }; 9937 // 9938 // void X::f() { } // ill-formed 9939 // 9940 // Complain about this problem, and attempt to suggest close 9941 // matches (e.g., those that differ only in cv-qualifiers and 9942 // whether the parameter types are references). 9943 9944 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9945 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 9946 AddToScope = ExtraArgs.AddToScope; 9947 return Result; 9948 } 9949 } 9950 9951 // Unqualified local friend declarations are required to resolve 9952 // to something. 9953 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 9954 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9955 *this, Previous, NewFD, ExtraArgs, true, S)) { 9956 AddToScope = ExtraArgs.AddToScope; 9957 return Result; 9958 } 9959 } 9960 } else if (!D.isFunctionDefinition() && 9961 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 9962 !isFriend && !isFunctionTemplateSpecialization && 9963 !isMemberSpecialization) { 9964 // An out-of-line member function declaration must also be a 9965 // definition (C++ [class.mfct]p2). 9966 // Note that this is not the case for explicit specializations of 9967 // function templates or member functions of class templates, per 9968 // C++ [temp.expl.spec]p2. We also allow these declarations as an 9969 // extension for compatibility with old SWIG code which likes to 9970 // generate them. 9971 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 9972 << D.getCXXScopeSpec().getRange(); 9973 } 9974 } 9975 9976 // If this is the first declaration of a library builtin function, add 9977 // attributes as appropriate. 9978 if (!D.isRedeclaration() && 9979 NewFD->getDeclContext()->getRedeclContext()->isFileContext()) { 9980 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) { 9981 if (unsigned BuiltinID = II->getBuiltinID()) { 9982 if (NewFD->getLanguageLinkage() == CLanguageLinkage) { 9983 // Validate the type matches unless this builtin is specified as 9984 // matching regardless of its declared type. 9985 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) { 9986 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 9987 } else { 9988 ASTContext::GetBuiltinTypeError Error; 9989 LookupNecessaryTypesForBuiltin(S, BuiltinID); 9990 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error); 9991 9992 if (!Error && !BuiltinType.isNull() && 9993 Context.hasSameFunctionTypeIgnoringExceptionSpec( 9994 NewFD->getType(), BuiltinType)) 9995 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 9996 } 9997 } else if (BuiltinID == Builtin::BI__GetExceptionInfo && 9998 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 9999 // FIXME: We should consider this a builtin only in the std namespace. 10000 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 10001 } 10002 } 10003 } 10004 } 10005 10006 ProcessPragmaWeak(S, NewFD); 10007 checkAttributesAfterMerging(*this, *NewFD); 10008 10009 AddKnownFunctionAttributes(NewFD); 10010 10011 if (NewFD->hasAttr<OverloadableAttr>() && 10012 !NewFD->getType()->getAs<FunctionProtoType>()) { 10013 Diag(NewFD->getLocation(), 10014 diag::err_attribute_overloadable_no_prototype) 10015 << NewFD; 10016 10017 // Turn this into a variadic function with no parameters. 10018 const auto *FT = NewFD->getType()->castAs<FunctionType>(); 10019 FunctionProtoType::ExtProtoInfo EPI( 10020 Context.getDefaultCallingConvention(true, false)); 10021 EPI.Variadic = true; 10022 EPI.ExtInfo = FT->getExtInfo(); 10023 10024 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 10025 NewFD->setType(R); 10026 } 10027 10028 // If there's a #pragma GCC visibility in scope, and this isn't a class 10029 // member, set the visibility of this function. 10030 if (!DC->isRecord() && NewFD->isExternallyVisible()) 10031 AddPushedVisibilityAttribute(NewFD); 10032 10033 // If there's a #pragma clang arc_cf_code_audited in scope, consider 10034 // marking the function. 10035 AddCFAuditedAttribute(NewFD); 10036 10037 // If this is a function definition, check if we have to apply optnone due to 10038 // a pragma. 10039 if(D.isFunctionDefinition()) 10040 AddRangeBasedOptnone(NewFD); 10041 10042 // If this is the first declaration of an extern C variable, update 10043 // the map of such variables. 10044 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 10045 isIncompleteDeclExternC(*this, NewFD)) 10046 RegisterLocallyScopedExternCDecl(NewFD, S); 10047 10048 // Set this FunctionDecl's range up to the right paren. 10049 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 10050 10051 if (D.isRedeclaration() && !Previous.empty()) { 10052 NamedDecl *Prev = Previous.getRepresentativeDecl(); 10053 checkDLLAttributeRedeclaration(*this, Prev, NewFD, 10054 isMemberSpecialization || 10055 isFunctionTemplateSpecialization, 10056 D.isFunctionDefinition()); 10057 } 10058 10059 if (getLangOpts().CUDA) { 10060 IdentifierInfo *II = NewFD->getIdentifier(); 10061 if (II && II->isStr(getCudaConfigureFuncName()) && 10062 !NewFD->isInvalidDecl() && 10063 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 10064 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType()) 10065 Diag(NewFD->getLocation(), diag::err_config_scalar_return) 10066 << getCudaConfigureFuncName(); 10067 Context.setcudaConfigureCallDecl(NewFD); 10068 } 10069 10070 // Variadic functions, other than a *declaration* of printf, are not allowed 10071 // in device-side CUDA code, unless someone passed 10072 // -fcuda-allow-variadic-functions. 10073 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 10074 (NewFD->hasAttr<CUDADeviceAttr>() || 10075 NewFD->hasAttr<CUDAGlobalAttr>()) && 10076 !(II && II->isStr("printf") && NewFD->isExternC() && 10077 !D.isFunctionDefinition())) { 10078 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 10079 } 10080 } 10081 10082 MarkUnusedFileScopedDecl(NewFD); 10083 10084 10085 10086 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) { 10087 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 10088 if (SC == SC_Static) { 10089 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 10090 D.setInvalidType(); 10091 } 10092 10093 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 10094 if (!NewFD->getReturnType()->isVoidType()) { 10095 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 10096 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 10097 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 10098 : FixItHint()); 10099 D.setInvalidType(); 10100 } 10101 10102 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 10103 for (auto Param : NewFD->parameters()) 10104 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 10105 10106 if (getLangOpts().OpenCLCPlusPlus) { 10107 if (DC->isRecord()) { 10108 Diag(D.getIdentifierLoc(), diag::err_method_kernel); 10109 D.setInvalidType(); 10110 } 10111 if (FunctionTemplate) { 10112 Diag(D.getIdentifierLoc(), diag::err_template_kernel); 10113 D.setInvalidType(); 10114 } 10115 } 10116 } 10117 10118 if (getLangOpts().CPlusPlus) { 10119 if (FunctionTemplate) { 10120 if (NewFD->isInvalidDecl()) 10121 FunctionTemplate->setInvalidDecl(); 10122 return FunctionTemplate; 10123 } 10124 10125 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 10126 CompleteMemberSpecialization(NewFD, Previous); 10127 } 10128 10129 for (const ParmVarDecl *Param : NewFD->parameters()) { 10130 QualType PT = Param->getType(); 10131 10132 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 10133 // types. 10134 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) { 10135 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 10136 QualType ElemTy = PipeTy->getElementType(); 10137 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 10138 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 10139 D.setInvalidType(); 10140 } 10141 } 10142 } 10143 } 10144 10145 // Here we have an function template explicit specialization at class scope. 10146 // The actual specialization will be postponed to template instatiation 10147 // time via the ClassScopeFunctionSpecializationDecl node. 10148 if (isDependentClassScopeExplicitSpecialization) { 10149 ClassScopeFunctionSpecializationDecl *NewSpec = 10150 ClassScopeFunctionSpecializationDecl::Create( 10151 Context, CurContext, NewFD->getLocation(), 10152 cast<CXXMethodDecl>(NewFD), 10153 HasExplicitTemplateArgs, TemplateArgs); 10154 CurContext->addDecl(NewSpec); 10155 AddToScope = false; 10156 } 10157 10158 // Diagnose availability attributes. Availability cannot be used on functions 10159 // that are run during load/unload. 10160 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { 10161 if (NewFD->hasAttr<ConstructorAttr>()) { 10162 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 10163 << 1; 10164 NewFD->dropAttr<AvailabilityAttr>(); 10165 } 10166 if (NewFD->hasAttr<DestructorAttr>()) { 10167 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 10168 << 2; 10169 NewFD->dropAttr<AvailabilityAttr>(); 10170 } 10171 } 10172 10173 // Diagnose no_builtin attribute on function declaration that are not a 10174 // definition. 10175 // FIXME: We should really be doing this in 10176 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to 10177 // the FunctionDecl and at this point of the code 10178 // FunctionDecl::isThisDeclarationADefinition() which always returns `false` 10179 // because Sema::ActOnStartOfFunctionDef has not been called yet. 10180 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>()) 10181 switch (D.getFunctionDefinitionKind()) { 10182 case FunctionDefinitionKind::Defaulted: 10183 case FunctionDefinitionKind::Deleted: 10184 Diag(NBA->getLocation(), 10185 diag::err_attribute_no_builtin_on_defaulted_deleted_function) 10186 << NBA->getSpelling(); 10187 break; 10188 case FunctionDefinitionKind::Declaration: 10189 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition) 10190 << NBA->getSpelling(); 10191 break; 10192 case FunctionDefinitionKind::Definition: 10193 break; 10194 } 10195 10196 return NewFD; 10197 } 10198 10199 /// Return a CodeSegAttr from a containing class. The Microsoft docs say 10200 /// when __declspec(code_seg) "is applied to a class, all member functions of 10201 /// the class and nested classes -- this includes compiler-generated special 10202 /// member functions -- are put in the specified segment." 10203 /// The actual behavior is a little more complicated. The Microsoft compiler 10204 /// won't check outer classes if there is an active value from #pragma code_seg. 10205 /// The CodeSeg is always applied from the direct parent but only from outer 10206 /// classes when the #pragma code_seg stack is empty. See: 10207 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer 10208 /// available since MS has removed the page. 10209 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) { 10210 const auto *Method = dyn_cast<CXXMethodDecl>(FD); 10211 if (!Method) 10212 return nullptr; 10213 const CXXRecordDecl *Parent = Method->getParent(); 10214 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 10215 Attr *NewAttr = SAttr->clone(S.getASTContext()); 10216 NewAttr->setImplicit(true); 10217 return NewAttr; 10218 } 10219 10220 // The Microsoft compiler won't check outer classes for the CodeSeg 10221 // when the #pragma code_seg stack is active. 10222 if (S.CodeSegStack.CurrentValue) 10223 return nullptr; 10224 10225 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) { 10226 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 10227 Attr *NewAttr = SAttr->clone(S.getASTContext()); 10228 NewAttr->setImplicit(true); 10229 return NewAttr; 10230 } 10231 } 10232 return nullptr; 10233 } 10234 10235 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a 10236 /// containing class. Otherwise it will return implicit SectionAttr if the 10237 /// function is a definition and there is an active value on CodeSegStack 10238 /// (from the current #pragma code-seg value). 10239 /// 10240 /// \param FD Function being declared. 10241 /// \param IsDefinition Whether it is a definition or just a declarartion. 10242 /// \returns A CodeSegAttr or SectionAttr to apply to the function or 10243 /// nullptr if no attribute should be added. 10244 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, 10245 bool IsDefinition) { 10246 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD)) 10247 return A; 10248 if (!FD->hasAttr<SectionAttr>() && IsDefinition && 10249 CodeSegStack.CurrentValue) 10250 return SectionAttr::CreateImplicit( 10251 getASTContext(), CodeSegStack.CurrentValue->getString(), 10252 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 10253 SectionAttr::Declspec_allocate); 10254 return nullptr; 10255 } 10256 10257 /// Determines if we can perform a correct type check for \p D as a 10258 /// redeclaration of \p PrevDecl. If not, we can generally still perform a 10259 /// best-effort check. 10260 /// 10261 /// \param NewD The new declaration. 10262 /// \param OldD The old declaration. 10263 /// \param NewT The portion of the type of the new declaration to check. 10264 /// \param OldT The portion of the type of the old declaration to check. 10265 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, 10266 QualType NewT, QualType OldT) { 10267 if (!NewD->getLexicalDeclContext()->isDependentContext()) 10268 return true; 10269 10270 // For dependently-typed local extern declarations and friends, we can't 10271 // perform a correct type check in general until instantiation: 10272 // 10273 // int f(); 10274 // template<typename T> void g() { T f(); } 10275 // 10276 // (valid if g() is only instantiated with T = int). 10277 if (NewT->isDependentType() && 10278 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind())) 10279 return false; 10280 10281 // Similarly, if the previous declaration was a dependent local extern 10282 // declaration, we don't really know its type yet. 10283 if (OldT->isDependentType() && OldD->isLocalExternDecl()) 10284 return false; 10285 10286 return true; 10287 } 10288 10289 /// Checks if the new declaration declared in dependent context must be 10290 /// put in the same redeclaration chain as the specified declaration. 10291 /// 10292 /// \param D Declaration that is checked. 10293 /// \param PrevDecl Previous declaration found with proper lookup method for the 10294 /// same declaration name. 10295 /// \returns True if D must be added to the redeclaration chain which PrevDecl 10296 /// belongs to. 10297 /// 10298 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 10299 if (!D->getLexicalDeclContext()->isDependentContext()) 10300 return true; 10301 10302 // Don't chain dependent friend function definitions until instantiation, to 10303 // permit cases like 10304 // 10305 // void func(); 10306 // template<typename T> class C1 { friend void func() {} }; 10307 // template<typename T> class C2 { friend void func() {} }; 10308 // 10309 // ... which is valid if only one of C1 and C2 is ever instantiated. 10310 // 10311 // FIXME: This need only apply to function definitions. For now, we proxy 10312 // this by checking for a file-scope function. We do not want this to apply 10313 // to friend declarations nominating member functions, because that gets in 10314 // the way of access checks. 10315 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext()) 10316 return false; 10317 10318 auto *VD = dyn_cast<ValueDecl>(D); 10319 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl); 10320 return !VD || !PrevVD || 10321 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(), 10322 PrevVD->getType()); 10323 } 10324 10325 /// Check the target attribute of the function for MultiVersion 10326 /// validity. 10327 /// 10328 /// Returns true if there was an error, false otherwise. 10329 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { 10330 const auto *TA = FD->getAttr<TargetAttr>(); 10331 assert(TA && "MultiVersion Candidate requires a target attribute"); 10332 ParsedTargetAttr ParseInfo = TA->parse(); 10333 const TargetInfo &TargetInfo = S.Context.getTargetInfo(); 10334 enum ErrType { Feature = 0, Architecture = 1 }; 10335 10336 if (!ParseInfo.Architecture.empty() && 10337 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) { 10338 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10339 << Architecture << ParseInfo.Architecture; 10340 return true; 10341 } 10342 10343 for (const auto &Feat : ParseInfo.Features) { 10344 auto BareFeat = StringRef{Feat}.substr(1); 10345 if (Feat[0] == '-') { 10346 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10347 << Feature << ("no-" + BareFeat).str(); 10348 return true; 10349 } 10350 10351 if (!TargetInfo.validateCpuSupports(BareFeat) || 10352 !TargetInfo.isValidFeatureName(BareFeat)) { 10353 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10354 << Feature << BareFeat; 10355 return true; 10356 } 10357 } 10358 return false; 10359 } 10360 10361 // Provide a white-list of attributes that are allowed to be combined with 10362 // multiversion functions. 10363 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, 10364 MultiVersionKind MVKind) { 10365 // Note: this list/diagnosis must match the list in 10366 // checkMultiversionAttributesAllSame. 10367 switch (Kind) { 10368 default: 10369 return false; 10370 case attr::Used: 10371 return MVKind == MultiVersionKind::Target; 10372 case attr::NonNull: 10373 case attr::NoThrow: 10374 return true; 10375 } 10376 } 10377 10378 static bool checkNonMultiVersionCompatAttributes(Sema &S, 10379 const FunctionDecl *FD, 10380 const FunctionDecl *CausedFD, 10381 MultiVersionKind MVKind) { 10382 const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) { 10383 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr) 10384 << static_cast<unsigned>(MVKind) << A; 10385 if (CausedFD) 10386 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here); 10387 return true; 10388 }; 10389 10390 for (const Attr *A : FD->attrs()) { 10391 switch (A->getKind()) { 10392 case attr::CPUDispatch: 10393 case attr::CPUSpecific: 10394 if (MVKind != MultiVersionKind::CPUDispatch && 10395 MVKind != MultiVersionKind::CPUSpecific) 10396 return Diagnose(S, A); 10397 break; 10398 case attr::Target: 10399 if (MVKind != MultiVersionKind::Target) 10400 return Diagnose(S, A); 10401 break; 10402 case attr::TargetClones: 10403 if (MVKind != MultiVersionKind::TargetClones) 10404 return Diagnose(S, A); 10405 break; 10406 default: 10407 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind)) 10408 return Diagnose(S, A); 10409 break; 10410 } 10411 } 10412 return false; 10413 } 10414 10415 bool Sema::areMultiversionVariantFunctionsCompatible( 10416 const FunctionDecl *OldFD, const FunctionDecl *NewFD, 10417 const PartialDiagnostic &NoProtoDiagID, 10418 const PartialDiagnosticAt &NoteCausedDiagIDAt, 10419 const PartialDiagnosticAt &NoSupportDiagIDAt, 10420 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, 10421 bool ConstexprSupported, bool CLinkageMayDiffer) { 10422 enum DoesntSupport { 10423 FuncTemplates = 0, 10424 VirtFuncs = 1, 10425 DeducedReturn = 2, 10426 Constructors = 3, 10427 Destructors = 4, 10428 DeletedFuncs = 5, 10429 DefaultedFuncs = 6, 10430 ConstexprFuncs = 7, 10431 ConstevalFuncs = 8, 10432 Lambda = 9, 10433 }; 10434 enum Different { 10435 CallingConv = 0, 10436 ReturnType = 1, 10437 ConstexprSpec = 2, 10438 InlineSpec = 3, 10439 Linkage = 4, 10440 LanguageLinkage = 5, 10441 }; 10442 10443 if (NoProtoDiagID.getDiagID() != 0 && OldFD && 10444 !OldFD->getType()->getAs<FunctionProtoType>()) { 10445 Diag(OldFD->getLocation(), NoProtoDiagID); 10446 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second); 10447 return true; 10448 } 10449 10450 if (NoProtoDiagID.getDiagID() != 0 && 10451 !NewFD->getType()->getAs<FunctionProtoType>()) 10452 return Diag(NewFD->getLocation(), NoProtoDiagID); 10453 10454 if (!TemplatesSupported && 10455 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 10456 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10457 << FuncTemplates; 10458 10459 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { 10460 if (NewCXXFD->isVirtual()) 10461 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10462 << VirtFuncs; 10463 10464 if (isa<CXXConstructorDecl>(NewCXXFD)) 10465 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10466 << Constructors; 10467 10468 if (isa<CXXDestructorDecl>(NewCXXFD)) 10469 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10470 << Destructors; 10471 } 10472 10473 if (NewFD->isDeleted()) 10474 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10475 << DeletedFuncs; 10476 10477 if (NewFD->isDefaulted()) 10478 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10479 << DefaultedFuncs; 10480 10481 if (!ConstexprSupported && NewFD->isConstexpr()) 10482 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10483 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs); 10484 10485 QualType NewQType = Context.getCanonicalType(NewFD->getType()); 10486 const auto *NewType = cast<FunctionType>(NewQType); 10487 QualType NewReturnType = NewType->getReturnType(); 10488 10489 if (NewReturnType->isUndeducedType()) 10490 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10491 << DeducedReturn; 10492 10493 // Ensure the return type is identical. 10494 if (OldFD) { 10495 QualType OldQType = Context.getCanonicalType(OldFD->getType()); 10496 const auto *OldType = cast<FunctionType>(OldQType); 10497 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 10498 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 10499 10500 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) 10501 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv; 10502 10503 QualType OldReturnType = OldType->getReturnType(); 10504 10505 if (OldReturnType != NewReturnType) 10506 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType; 10507 10508 if (OldFD->getConstexprKind() != NewFD->getConstexprKind()) 10509 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec; 10510 10511 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) 10512 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec; 10513 10514 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage()) 10515 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage; 10516 10517 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC()) 10518 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage; 10519 10520 if (CheckEquivalentExceptionSpec( 10521 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), 10522 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) 10523 return true; 10524 } 10525 return false; 10526 } 10527 10528 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, 10529 const FunctionDecl *NewFD, 10530 bool CausesMV, 10531 MultiVersionKind MVKind) { 10532 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10533 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10534 if (OldFD) 10535 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10536 return true; 10537 } 10538 10539 bool IsCPUSpecificCPUDispatchMVKind = 10540 MVKind == MultiVersionKind::CPUDispatch || 10541 MVKind == MultiVersionKind::CPUSpecific; 10542 10543 if (CausesMV && OldFD && 10544 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind)) 10545 return true; 10546 10547 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind)) 10548 return true; 10549 10550 // Only allow transition to MultiVersion if it hasn't been used. 10551 if (OldFD && CausesMV && OldFD->isUsed(false)) 10552 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 10553 10554 return S.areMultiversionVariantFunctionsCompatible( 10555 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto), 10556 PartialDiagnosticAt(NewFD->getLocation(), 10557 S.PDiag(diag::note_multiversioning_caused_here)), 10558 PartialDiagnosticAt(NewFD->getLocation(), 10559 S.PDiag(diag::err_multiversion_doesnt_support) 10560 << static_cast<unsigned>(MVKind)), 10561 PartialDiagnosticAt(NewFD->getLocation(), 10562 S.PDiag(diag::err_multiversion_diff)), 10563 /*TemplatesSupported=*/false, 10564 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind, 10565 /*CLinkageMayDiffer=*/false); 10566 } 10567 10568 /// Check the validity of a multiversion function declaration that is the 10569 /// first of its kind. Also sets the multiversion'ness' of the function itself. 10570 /// 10571 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10572 /// 10573 /// Returns true if there was an error, false otherwise. 10574 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD, 10575 MultiVersionKind MVKind, 10576 const TargetAttr *TA) { 10577 assert(MVKind != MultiVersionKind::None && 10578 "Function lacks multiversion attribute"); 10579 10580 // Target only causes MV if it is default, otherwise this is a normal 10581 // function. 10582 if (MVKind == MultiVersionKind::Target && !TA->isDefaultVersion()) 10583 return false; 10584 10585 if (MVKind == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) { 10586 FD->setInvalidDecl(); 10587 return true; 10588 } 10589 10590 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) { 10591 FD->setInvalidDecl(); 10592 return true; 10593 } 10594 10595 FD->setIsMultiVersion(); 10596 return false; 10597 } 10598 10599 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) { 10600 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) { 10601 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None) 10602 return true; 10603 } 10604 10605 return false; 10606 } 10607 10608 static bool CheckTargetCausesMultiVersioning( 10609 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA, 10610 bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous) { 10611 const auto *OldTA = OldFD->getAttr<TargetAttr>(); 10612 ParsedTargetAttr NewParsed = NewTA->parse(); 10613 // Sort order doesn't matter, it just needs to be consistent. 10614 llvm::sort(NewParsed.Features); 10615 10616 // If the old decl is NOT MultiVersioned yet, and we don't cause that 10617 // to change, this is a simple redeclaration. 10618 if (!NewTA->isDefaultVersion() && 10619 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) 10620 return false; 10621 10622 // Otherwise, this decl causes MultiVersioning. 10623 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true, 10624 MultiVersionKind::Target)) { 10625 NewFD->setInvalidDecl(); 10626 return true; 10627 } 10628 10629 if (CheckMultiVersionValue(S, NewFD)) { 10630 NewFD->setInvalidDecl(); 10631 return true; 10632 } 10633 10634 // If this is 'default', permit the forward declaration. 10635 if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) { 10636 Redeclaration = true; 10637 OldDecl = OldFD; 10638 OldFD->setIsMultiVersion(); 10639 NewFD->setIsMultiVersion(); 10640 return false; 10641 } 10642 10643 if (CheckMultiVersionValue(S, OldFD)) { 10644 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10645 NewFD->setInvalidDecl(); 10646 return true; 10647 } 10648 10649 ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>()); 10650 10651 if (OldParsed == NewParsed) { 10652 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10653 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10654 NewFD->setInvalidDecl(); 10655 return true; 10656 } 10657 10658 for (const auto *FD : OldFD->redecls()) { 10659 const auto *CurTA = FD->getAttr<TargetAttr>(); 10660 // We allow forward declarations before ANY multiversioning attributes, but 10661 // nothing after the fact. 10662 if (PreviousDeclsHaveMultiVersionAttribute(FD) && 10663 (!CurTA || CurTA->isInherited())) { 10664 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl) 10665 << 0; 10666 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10667 NewFD->setInvalidDecl(); 10668 return true; 10669 } 10670 } 10671 10672 OldFD->setIsMultiVersion(); 10673 NewFD->setIsMultiVersion(); 10674 Redeclaration = false; 10675 OldDecl = nullptr; 10676 Previous.clear(); 10677 return false; 10678 } 10679 10680 static bool MultiVersionTypesCompatible(MultiVersionKind Old, 10681 MultiVersionKind New) { 10682 if (Old == New || Old == MultiVersionKind::None || 10683 New == MultiVersionKind::None) 10684 return true; 10685 10686 return (Old == MultiVersionKind::CPUDispatch && 10687 New == MultiVersionKind::CPUSpecific) || 10688 (Old == MultiVersionKind::CPUSpecific && 10689 New == MultiVersionKind::CPUDispatch); 10690 } 10691 10692 /// Check the validity of a new function declaration being added to an existing 10693 /// multiversioned declaration collection. 10694 static bool CheckMultiVersionAdditionalDecl( 10695 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, 10696 MultiVersionKind NewMVKind, const TargetAttr *NewTA, 10697 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, 10698 const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl, 10699 LookupResult &Previous) { 10700 10701 MultiVersionKind OldMVKind = OldFD->getMultiVersionKind(); 10702 // Disallow mixing of multiversioning types. 10703 if (!MultiVersionTypesCompatible(OldMVKind, NewMVKind)) { 10704 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10705 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10706 NewFD->setInvalidDecl(); 10707 return true; 10708 } 10709 10710 ParsedTargetAttr NewParsed; 10711 if (NewTA) { 10712 NewParsed = NewTA->parse(); 10713 llvm::sort(NewParsed.Features); 10714 } 10715 10716 bool UseMemberUsingDeclRules = 10717 S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); 10718 10719 bool MayNeedOverloadableChecks = 10720 AllowOverloadingOfFunction(Previous, S.Context, NewFD); 10721 10722 // Next, check ALL non-overloads to see if this is a redeclaration of a 10723 // previous member of the MultiVersion set. 10724 for (NamedDecl *ND : Previous) { 10725 FunctionDecl *CurFD = ND->getAsFunction(); 10726 if (!CurFD) 10727 continue; 10728 if (MayNeedOverloadableChecks && 10729 S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) 10730 continue; 10731 10732 switch (NewMVKind) { 10733 case MultiVersionKind::None: 10734 assert(OldMVKind == MultiVersionKind::TargetClones && 10735 "Only target_clones can be omitted in subsequent declarations"); 10736 break; 10737 case MultiVersionKind::Target: { 10738 const auto *CurTA = CurFD->getAttr<TargetAttr>(); 10739 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { 10740 NewFD->setIsMultiVersion(); 10741 Redeclaration = true; 10742 OldDecl = ND; 10743 return false; 10744 } 10745 10746 ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>()); 10747 if (CurParsed == NewParsed) { 10748 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10749 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10750 NewFD->setInvalidDecl(); 10751 return true; 10752 } 10753 break; 10754 } 10755 case MultiVersionKind::TargetClones: { 10756 const auto *CurClones = CurFD->getAttr<TargetClonesAttr>(); 10757 Redeclaration = true; 10758 OldDecl = CurFD; 10759 NewFD->setIsMultiVersion(); 10760 10761 if (CurClones && NewClones && 10762 (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() || 10763 !std::equal(CurClones->featuresStrs_begin(), 10764 CurClones->featuresStrs_end(), 10765 NewClones->featuresStrs_begin()))) { 10766 S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match); 10767 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10768 NewFD->setInvalidDecl(); 10769 return true; 10770 } 10771 10772 return false; 10773 } 10774 case MultiVersionKind::CPUSpecific: 10775 case MultiVersionKind::CPUDispatch: { 10776 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>(); 10777 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>(); 10778 // Handle CPUDispatch/CPUSpecific versions. 10779 // Only 1 CPUDispatch function is allowed, this will make it go through 10780 // the redeclaration errors. 10781 if (NewMVKind == MultiVersionKind::CPUDispatch && 10782 CurFD->hasAttr<CPUDispatchAttr>()) { 10783 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() && 10784 std::equal( 10785 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(), 10786 NewCPUDisp->cpus_begin(), 10787 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10788 return Cur->getName() == New->getName(); 10789 })) { 10790 NewFD->setIsMultiVersion(); 10791 Redeclaration = true; 10792 OldDecl = ND; 10793 return false; 10794 } 10795 10796 // If the declarations don't match, this is an error condition. 10797 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch); 10798 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10799 NewFD->setInvalidDecl(); 10800 return true; 10801 } 10802 if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) { 10803 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() && 10804 std::equal( 10805 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(), 10806 NewCPUSpec->cpus_begin(), 10807 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10808 return Cur->getName() == New->getName(); 10809 })) { 10810 NewFD->setIsMultiVersion(); 10811 Redeclaration = true; 10812 OldDecl = ND; 10813 return false; 10814 } 10815 10816 // Only 1 version of CPUSpecific is allowed for each CPU. 10817 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) { 10818 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) { 10819 if (CurII == NewII) { 10820 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs) 10821 << NewII; 10822 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10823 NewFD->setInvalidDecl(); 10824 return true; 10825 } 10826 } 10827 } 10828 } 10829 break; 10830 } 10831 } 10832 } 10833 10834 // Else, this is simply a non-redecl case. Checking the 'value' is only 10835 // necessary in the Target case, since The CPUSpecific/Dispatch cases are 10836 // handled in the attribute adding step. 10837 if (NewMVKind == MultiVersionKind::Target && 10838 CheckMultiVersionValue(S, NewFD)) { 10839 NewFD->setInvalidDecl(); 10840 return true; 10841 } 10842 10843 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, 10844 !OldFD->isMultiVersion(), NewMVKind)) { 10845 NewFD->setInvalidDecl(); 10846 return true; 10847 } 10848 10849 // Permit forward declarations in the case where these two are compatible. 10850 if (!OldFD->isMultiVersion()) { 10851 OldFD->setIsMultiVersion(); 10852 NewFD->setIsMultiVersion(); 10853 Redeclaration = true; 10854 OldDecl = OldFD; 10855 return false; 10856 } 10857 10858 NewFD->setIsMultiVersion(); 10859 Redeclaration = false; 10860 OldDecl = nullptr; 10861 Previous.clear(); 10862 return false; 10863 } 10864 10865 /// Check the validity of a mulitversion function declaration. 10866 /// Also sets the multiversion'ness' of the function itself. 10867 /// 10868 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10869 /// 10870 /// Returns true if there was an error, false otherwise. 10871 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, 10872 bool &Redeclaration, NamedDecl *&OldDecl, 10873 LookupResult &Previous) { 10874 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 10875 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>(); 10876 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>(); 10877 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>(); 10878 MultiVersionKind MVKind = NewFD->getMultiVersionKind(); 10879 10880 // Main isn't allowed to become a multiversion function, however it IS 10881 // permitted to have 'main' be marked with the 'target' optimization hint. 10882 if (NewFD->isMain()) { 10883 if (MVKind != MultiVersionKind::None && 10884 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion())) { 10885 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); 10886 NewFD->setInvalidDecl(); 10887 return true; 10888 } 10889 return false; 10890 } 10891 10892 if (!OldDecl || !OldDecl->getAsFunction() || 10893 OldDecl->getDeclContext()->getRedeclContext() != 10894 NewFD->getDeclContext()->getRedeclContext()) { 10895 // If there's no previous declaration, AND this isn't attempting to cause 10896 // multiversioning, this isn't an error condition. 10897 if (MVKind == MultiVersionKind::None) 10898 return false; 10899 return CheckMultiVersionFirstFunction(S, NewFD, MVKind, NewTA); 10900 } 10901 10902 FunctionDecl *OldFD = OldDecl->getAsFunction(); 10903 10904 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None) 10905 return false; 10906 10907 // Multiversioned redeclarations aren't allowed to omit the attribute, except 10908 // for target_clones. 10909 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None && 10910 OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones) { 10911 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl) 10912 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target); 10913 NewFD->setInvalidDecl(); 10914 return true; 10915 } 10916 10917 if (!OldFD->isMultiVersion()) { 10918 switch (MVKind) { 10919 case MultiVersionKind::Target: 10920 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA, 10921 Redeclaration, OldDecl, Previous); 10922 case MultiVersionKind::TargetClones: 10923 if (OldFD->isUsed(false)) { 10924 NewFD->setInvalidDecl(); 10925 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 10926 } 10927 OldFD->setIsMultiVersion(); 10928 break; 10929 case MultiVersionKind::CPUDispatch: 10930 case MultiVersionKind::CPUSpecific: 10931 case MultiVersionKind::None: 10932 break; 10933 } 10934 } 10935 10936 // At this point, we have a multiversion function decl (in OldFD) AND an 10937 // appropriate attribute in the current function decl. Resolve that these are 10938 // still compatible with previous declarations. 10939 return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, MVKind, NewTA, 10940 NewCPUDisp, NewCPUSpec, NewClones, 10941 Redeclaration, OldDecl, Previous); 10942 } 10943 10944 /// Perform semantic checking of a new function declaration. 10945 /// 10946 /// Performs semantic analysis of the new function declaration 10947 /// NewFD. This routine performs all semantic checking that does not 10948 /// require the actual declarator involved in the declaration, and is 10949 /// used both for the declaration of functions as they are parsed 10950 /// (called via ActOnDeclarator) and for the declaration of functions 10951 /// that have been instantiated via C++ template instantiation (called 10952 /// via InstantiateDecl). 10953 /// 10954 /// \param IsMemberSpecialization whether this new function declaration is 10955 /// a member specialization (that replaces any definition provided by the 10956 /// previous declaration). 10957 /// 10958 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10959 /// 10960 /// \returns true if the function declaration is a redeclaration. 10961 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 10962 LookupResult &Previous, 10963 bool IsMemberSpecialization) { 10964 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 10965 "Variably modified return types are not handled here"); 10966 10967 // Determine whether the type of this function should be merged with 10968 // a previous visible declaration. This never happens for functions in C++, 10969 // and always happens in C if the previous declaration was visible. 10970 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 10971 !Previous.isShadowed(); 10972 10973 bool Redeclaration = false; 10974 NamedDecl *OldDecl = nullptr; 10975 bool MayNeedOverloadableChecks = false; 10976 10977 // Merge or overload the declaration with an existing declaration of 10978 // the same name, if appropriate. 10979 if (!Previous.empty()) { 10980 // Determine whether NewFD is an overload of PrevDecl or 10981 // a declaration that requires merging. If it's an overload, 10982 // there's no more work to do here; we'll just add the new 10983 // function to the scope. 10984 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { 10985 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 10986 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 10987 Redeclaration = true; 10988 OldDecl = Candidate; 10989 } 10990 } else { 10991 MayNeedOverloadableChecks = true; 10992 switch (CheckOverload(S, NewFD, Previous, OldDecl, 10993 /*NewIsUsingDecl*/ false)) { 10994 case Ovl_Match: 10995 Redeclaration = true; 10996 break; 10997 10998 case Ovl_NonFunction: 10999 Redeclaration = true; 11000 break; 11001 11002 case Ovl_Overload: 11003 Redeclaration = false; 11004 break; 11005 } 11006 } 11007 } 11008 11009 // Check for a previous extern "C" declaration with this name. 11010 if (!Redeclaration && 11011 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 11012 if (!Previous.empty()) { 11013 // This is an extern "C" declaration with the same name as a previous 11014 // declaration, and thus redeclares that entity... 11015 Redeclaration = true; 11016 OldDecl = Previous.getFoundDecl(); 11017 MergeTypeWithPrevious = false; 11018 11019 // ... except in the presence of __attribute__((overloadable)). 11020 if (OldDecl->hasAttr<OverloadableAttr>() || 11021 NewFD->hasAttr<OverloadableAttr>()) { 11022 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 11023 MayNeedOverloadableChecks = true; 11024 Redeclaration = false; 11025 OldDecl = nullptr; 11026 } 11027 } 11028 } 11029 } 11030 11031 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous)) 11032 return Redeclaration; 11033 11034 // PPC MMA non-pointer types are not allowed as function return types. 11035 if (Context.getTargetInfo().getTriple().isPPC64() && 11036 CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) { 11037 NewFD->setInvalidDecl(); 11038 } 11039 11040 // C++11 [dcl.constexpr]p8: 11041 // A constexpr specifier for a non-static member function that is not 11042 // a constructor declares that member function to be const. 11043 // 11044 // This needs to be delayed until we know whether this is an out-of-line 11045 // definition of a static member function. 11046 // 11047 // This rule is not present in C++1y, so we produce a backwards 11048 // compatibility warning whenever it happens in C++11. 11049 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 11050 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 11051 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 11052 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) { 11053 CXXMethodDecl *OldMD = nullptr; 11054 if (OldDecl) 11055 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 11056 if (!OldMD || !OldMD->isStatic()) { 11057 const FunctionProtoType *FPT = 11058 MD->getType()->castAs<FunctionProtoType>(); 11059 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 11060 EPI.TypeQuals.addConst(); 11061 MD->setType(Context.getFunctionType(FPT->getReturnType(), 11062 FPT->getParamTypes(), EPI)); 11063 11064 // Warn that we did this, if we're not performing template instantiation. 11065 // In that case, we'll have warned already when the template was defined. 11066 if (!inTemplateInstantiation()) { 11067 SourceLocation AddConstLoc; 11068 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 11069 .IgnoreParens().getAs<FunctionTypeLoc>()) 11070 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 11071 11072 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 11073 << FixItHint::CreateInsertion(AddConstLoc, " const"); 11074 } 11075 } 11076 } 11077 11078 if (Redeclaration) { 11079 // NewFD and OldDecl represent declarations that need to be 11080 // merged. 11081 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 11082 NewFD->setInvalidDecl(); 11083 return Redeclaration; 11084 } 11085 11086 Previous.clear(); 11087 Previous.addDecl(OldDecl); 11088 11089 if (FunctionTemplateDecl *OldTemplateDecl = 11090 dyn_cast<FunctionTemplateDecl>(OldDecl)) { 11091 auto *OldFD = OldTemplateDecl->getTemplatedDecl(); 11092 FunctionTemplateDecl *NewTemplateDecl 11093 = NewFD->getDescribedFunctionTemplate(); 11094 assert(NewTemplateDecl && "Template/non-template mismatch"); 11095 11096 // The call to MergeFunctionDecl above may have created some state in 11097 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we 11098 // can add it as a redeclaration. 11099 NewTemplateDecl->mergePrevDecl(OldTemplateDecl); 11100 11101 NewFD->setPreviousDeclaration(OldFD); 11102 if (NewFD->isCXXClassMember()) { 11103 NewFD->setAccess(OldTemplateDecl->getAccess()); 11104 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 11105 } 11106 11107 // If this is an explicit specialization of a member that is a function 11108 // template, mark it as a member specialization. 11109 if (IsMemberSpecialization && 11110 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 11111 NewTemplateDecl->setMemberSpecialization(); 11112 assert(OldTemplateDecl->isMemberSpecialization()); 11113 // Explicit specializations of a member template do not inherit deleted 11114 // status from the parent member template that they are specializing. 11115 if (OldFD->isDeleted()) { 11116 // FIXME: This assert will not hold in the presence of modules. 11117 assert(OldFD->getCanonicalDecl() == OldFD); 11118 // FIXME: We need an update record for this AST mutation. 11119 OldFD->setDeletedAsWritten(false); 11120 } 11121 } 11122 11123 } else { 11124 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 11125 auto *OldFD = cast<FunctionDecl>(OldDecl); 11126 // This needs to happen first so that 'inline' propagates. 11127 NewFD->setPreviousDeclaration(OldFD); 11128 if (NewFD->isCXXClassMember()) 11129 NewFD->setAccess(OldFD->getAccess()); 11130 } 11131 } 11132 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && 11133 !NewFD->getAttr<OverloadableAttr>()) { 11134 assert((Previous.empty() || 11135 llvm::any_of(Previous, 11136 [](const NamedDecl *ND) { 11137 return ND->hasAttr<OverloadableAttr>(); 11138 })) && 11139 "Non-redecls shouldn't happen without overloadable present"); 11140 11141 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { 11142 const auto *FD = dyn_cast<FunctionDecl>(ND); 11143 return FD && !FD->hasAttr<OverloadableAttr>(); 11144 }); 11145 11146 if (OtherUnmarkedIter != Previous.end()) { 11147 Diag(NewFD->getLocation(), 11148 diag::err_attribute_overloadable_multiple_unmarked_overloads); 11149 Diag((*OtherUnmarkedIter)->getLocation(), 11150 diag::note_attribute_overloadable_prev_overload) 11151 << false; 11152 11153 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 11154 } 11155 } 11156 11157 if (LangOpts.OpenMP) 11158 ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD); 11159 11160 // Semantic checking for this function declaration (in isolation). 11161 11162 if (getLangOpts().CPlusPlus) { 11163 // C++-specific checks. 11164 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 11165 CheckConstructor(Constructor); 11166 } else if (CXXDestructorDecl *Destructor = 11167 dyn_cast<CXXDestructorDecl>(NewFD)) { 11168 CXXRecordDecl *Record = Destructor->getParent(); 11169 QualType ClassType = Context.getTypeDeclType(Record); 11170 11171 // FIXME: Shouldn't we be able to perform this check even when the class 11172 // type is dependent? Both gcc and edg can handle that. 11173 if (!ClassType->isDependentType()) { 11174 DeclarationName Name 11175 = Context.DeclarationNames.getCXXDestructorName( 11176 Context.getCanonicalType(ClassType)); 11177 if (NewFD->getDeclName() != Name) { 11178 Diag(NewFD->getLocation(), diag::err_destructor_name); 11179 NewFD->setInvalidDecl(); 11180 return Redeclaration; 11181 } 11182 } 11183 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 11184 if (auto *TD = Guide->getDescribedFunctionTemplate()) 11185 CheckDeductionGuideTemplate(TD); 11186 11187 // A deduction guide is not on the list of entities that can be 11188 // explicitly specialized. 11189 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 11190 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized) 11191 << /*explicit specialization*/ 1; 11192 } 11193 11194 // Find any virtual functions that this function overrides. 11195 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 11196 if (!Method->isFunctionTemplateSpecialization() && 11197 !Method->getDescribedFunctionTemplate() && 11198 Method->isCanonicalDecl()) { 11199 AddOverriddenMethods(Method->getParent(), Method); 11200 } 11201 if (Method->isVirtual() && NewFD->getTrailingRequiresClause()) 11202 // C++2a [class.virtual]p6 11203 // A virtual method shall not have a requires-clause. 11204 Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(), 11205 diag::err_constrained_virtual_method); 11206 11207 if (Method->isStatic()) 11208 checkThisInStaticMemberFunctionType(Method); 11209 } 11210 11211 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD)) 11212 ActOnConversionDeclarator(Conversion); 11213 11214 // Extra checking for C++ overloaded operators (C++ [over.oper]). 11215 if (NewFD->isOverloadedOperator() && 11216 CheckOverloadedOperatorDeclaration(NewFD)) { 11217 NewFD->setInvalidDecl(); 11218 return Redeclaration; 11219 } 11220 11221 // Extra checking for C++0x literal operators (C++0x [over.literal]). 11222 if (NewFD->getLiteralIdentifier() && 11223 CheckLiteralOperatorDeclaration(NewFD)) { 11224 NewFD->setInvalidDecl(); 11225 return Redeclaration; 11226 } 11227 11228 // In C++, check default arguments now that we have merged decls. Unless 11229 // the lexical context is the class, because in this case this is done 11230 // during delayed parsing anyway. 11231 if (!CurContext->isRecord()) 11232 CheckCXXDefaultArguments(NewFD); 11233 11234 // If this function is declared as being extern "C", then check to see if 11235 // the function returns a UDT (class, struct, or union type) that is not C 11236 // compatible, and if it does, warn the user. 11237 // But, issue any diagnostic on the first declaration only. 11238 if (Previous.empty() && NewFD->isExternC()) { 11239 QualType R = NewFD->getReturnType(); 11240 if (R->isIncompleteType() && !R->isVoidType()) 11241 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 11242 << NewFD << R; 11243 else if (!R.isPODType(Context) && !R->isVoidType() && 11244 !R->isObjCObjectPointerType()) 11245 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 11246 } 11247 11248 // C++1z [dcl.fct]p6: 11249 // [...] whether the function has a non-throwing exception-specification 11250 // [is] part of the function type 11251 // 11252 // This results in an ABI break between C++14 and C++17 for functions whose 11253 // declared type includes an exception-specification in a parameter or 11254 // return type. (Exception specifications on the function itself are OK in 11255 // most cases, and exception specifications are not permitted in most other 11256 // contexts where they could make it into a mangling.) 11257 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { 11258 auto HasNoexcept = [&](QualType T) -> bool { 11259 // Strip off declarator chunks that could be between us and a function 11260 // type. We don't need to look far, exception specifications are very 11261 // restricted prior to C++17. 11262 if (auto *RT = T->getAs<ReferenceType>()) 11263 T = RT->getPointeeType(); 11264 else if (T->isAnyPointerType()) 11265 T = T->getPointeeType(); 11266 else if (auto *MPT = T->getAs<MemberPointerType>()) 11267 T = MPT->getPointeeType(); 11268 if (auto *FPT = T->getAs<FunctionProtoType>()) 11269 if (FPT->isNothrow()) 11270 return true; 11271 return false; 11272 }; 11273 11274 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 11275 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 11276 for (QualType T : FPT->param_types()) 11277 AnyNoexcept |= HasNoexcept(T); 11278 if (AnyNoexcept) 11279 Diag(NewFD->getLocation(), 11280 diag::warn_cxx17_compat_exception_spec_in_signature) 11281 << NewFD; 11282 } 11283 11284 if (!Redeclaration && LangOpts.CUDA) 11285 checkCUDATargetOverload(NewFD, Previous); 11286 } 11287 return Redeclaration; 11288 } 11289 11290 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 11291 // C++11 [basic.start.main]p3: 11292 // A program that [...] declares main to be inline, static or 11293 // constexpr is ill-formed. 11294 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 11295 // appear in a declaration of main. 11296 // static main is not an error under C99, but we should warn about it. 11297 // We accept _Noreturn main as an extension. 11298 if (FD->getStorageClass() == SC_Static) 11299 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 11300 ? diag::err_static_main : diag::warn_static_main) 11301 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 11302 if (FD->isInlineSpecified()) 11303 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 11304 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 11305 if (DS.isNoreturnSpecified()) { 11306 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 11307 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 11308 Diag(NoreturnLoc, diag::ext_noreturn_main); 11309 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 11310 << FixItHint::CreateRemoval(NoreturnRange); 11311 } 11312 if (FD->isConstexpr()) { 11313 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 11314 << FD->isConsteval() 11315 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 11316 FD->setConstexprKind(ConstexprSpecKind::Unspecified); 11317 } 11318 11319 if (getLangOpts().OpenCL) { 11320 Diag(FD->getLocation(), diag::err_opencl_no_main) 11321 << FD->hasAttr<OpenCLKernelAttr>(); 11322 FD->setInvalidDecl(); 11323 return; 11324 } 11325 11326 QualType T = FD->getType(); 11327 assert(T->isFunctionType() && "function decl is not of function type"); 11328 const FunctionType* FT = T->castAs<FunctionType>(); 11329 11330 // Set default calling convention for main() 11331 if (FT->getCallConv() != CC_C) { 11332 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); 11333 FD->setType(QualType(FT, 0)); 11334 T = Context.getCanonicalType(FD->getType()); 11335 } 11336 11337 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 11338 // In C with GNU extensions we allow main() to have non-integer return 11339 // type, but we should warn about the extension, and we disable the 11340 // implicit-return-zero rule. 11341 11342 // GCC in C mode accepts qualified 'int'. 11343 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 11344 FD->setHasImplicitReturnZero(true); 11345 else { 11346 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 11347 SourceRange RTRange = FD->getReturnTypeSourceRange(); 11348 if (RTRange.isValid()) 11349 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 11350 << FixItHint::CreateReplacement(RTRange, "int"); 11351 } 11352 } else { 11353 // In C and C++, main magically returns 0 if you fall off the end; 11354 // set the flag which tells us that. 11355 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 11356 11357 // All the standards say that main() should return 'int'. 11358 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 11359 FD->setHasImplicitReturnZero(true); 11360 else { 11361 // Otherwise, this is just a flat-out error. 11362 SourceRange RTRange = FD->getReturnTypeSourceRange(); 11363 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 11364 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 11365 : FixItHint()); 11366 FD->setInvalidDecl(true); 11367 } 11368 } 11369 11370 // Treat protoless main() as nullary. 11371 if (isa<FunctionNoProtoType>(FT)) return; 11372 11373 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 11374 unsigned nparams = FTP->getNumParams(); 11375 assert(FD->getNumParams() == nparams); 11376 11377 bool HasExtraParameters = (nparams > 3); 11378 11379 if (FTP->isVariadic()) { 11380 Diag(FD->getLocation(), diag::ext_variadic_main); 11381 // FIXME: if we had information about the location of the ellipsis, we 11382 // could add a FixIt hint to remove it as a parameter. 11383 } 11384 11385 // Darwin passes an undocumented fourth argument of type char**. If 11386 // other platforms start sprouting these, the logic below will start 11387 // getting shifty. 11388 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 11389 HasExtraParameters = false; 11390 11391 if (HasExtraParameters) { 11392 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 11393 FD->setInvalidDecl(true); 11394 nparams = 3; 11395 } 11396 11397 // FIXME: a lot of the following diagnostics would be improved 11398 // if we had some location information about types. 11399 11400 QualType CharPP = 11401 Context.getPointerType(Context.getPointerType(Context.CharTy)); 11402 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 11403 11404 for (unsigned i = 0; i < nparams; ++i) { 11405 QualType AT = FTP->getParamType(i); 11406 11407 bool mismatch = true; 11408 11409 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 11410 mismatch = false; 11411 else if (Expected[i] == CharPP) { 11412 // As an extension, the following forms are okay: 11413 // char const ** 11414 // char const * const * 11415 // char * const * 11416 11417 QualifierCollector qs; 11418 const PointerType* PT; 11419 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 11420 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 11421 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 11422 Context.CharTy)) { 11423 qs.removeConst(); 11424 mismatch = !qs.empty(); 11425 } 11426 } 11427 11428 if (mismatch) { 11429 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 11430 // TODO: suggest replacing given type with expected type 11431 FD->setInvalidDecl(true); 11432 } 11433 } 11434 11435 if (nparams == 1 && !FD->isInvalidDecl()) { 11436 Diag(FD->getLocation(), diag::warn_main_one_arg); 11437 } 11438 11439 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11440 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11441 FD->setInvalidDecl(); 11442 } 11443 } 11444 11445 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) { 11446 11447 // Default calling convention for main and wmain is __cdecl 11448 if (FD->getName() == "main" || FD->getName() == "wmain") 11449 return false; 11450 11451 // Default calling convention for MinGW is __cdecl 11452 const llvm::Triple &T = S.Context.getTargetInfo().getTriple(); 11453 if (T.isWindowsGNUEnvironment()) 11454 return false; 11455 11456 // Default calling convention for WinMain, wWinMain and DllMain 11457 // is __stdcall on 32 bit Windows 11458 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86) 11459 return true; 11460 11461 return false; 11462 } 11463 11464 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 11465 QualType T = FD->getType(); 11466 assert(T->isFunctionType() && "function decl is not of function type"); 11467 const FunctionType *FT = T->castAs<FunctionType>(); 11468 11469 // Set an implicit return of 'zero' if the function can return some integral, 11470 // enumeration, pointer or nullptr type. 11471 if (FT->getReturnType()->isIntegralOrEnumerationType() || 11472 FT->getReturnType()->isAnyPointerType() || 11473 FT->getReturnType()->isNullPtrType()) 11474 // DllMain is exempt because a return value of zero means it failed. 11475 if (FD->getName() != "DllMain") 11476 FD->setHasImplicitReturnZero(true); 11477 11478 // Explicity specified calling conventions are applied to MSVC entry points 11479 if (!hasExplicitCallingConv(T)) { 11480 if (isDefaultStdCall(FD, *this)) { 11481 if (FT->getCallConv() != CC_X86StdCall) { 11482 FT = Context.adjustFunctionType( 11483 FT, FT->getExtInfo().withCallingConv(CC_X86StdCall)); 11484 FD->setType(QualType(FT, 0)); 11485 } 11486 } else if (FT->getCallConv() != CC_C) { 11487 FT = Context.adjustFunctionType(FT, 11488 FT->getExtInfo().withCallingConv(CC_C)); 11489 FD->setType(QualType(FT, 0)); 11490 } 11491 } 11492 11493 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11494 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11495 FD->setInvalidDecl(); 11496 } 11497 } 11498 11499 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 11500 // FIXME: Need strict checking. In C89, we need to check for 11501 // any assignment, increment, decrement, function-calls, or 11502 // commas outside of a sizeof. In C99, it's the same list, 11503 // except that the aforementioned are allowed in unevaluated 11504 // expressions. Everything else falls under the 11505 // "may accept other forms of constant expressions" exception. 11506 // 11507 // Regular C++ code will not end up here (exceptions: language extensions, 11508 // OpenCL C++ etc), so the constant expression rules there don't matter. 11509 if (Init->isValueDependent()) { 11510 assert(Init->containsErrors() && 11511 "Dependent code should only occur in error-recovery path."); 11512 return true; 11513 } 11514 const Expr *Culprit; 11515 if (Init->isConstantInitializer(Context, false, &Culprit)) 11516 return false; 11517 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 11518 << Culprit->getSourceRange(); 11519 return true; 11520 } 11521 11522 namespace { 11523 // Visits an initialization expression to see if OrigDecl is evaluated in 11524 // its own initialization and throws a warning if it does. 11525 class SelfReferenceChecker 11526 : public EvaluatedExprVisitor<SelfReferenceChecker> { 11527 Sema &S; 11528 Decl *OrigDecl; 11529 bool isRecordType; 11530 bool isPODType; 11531 bool isReferenceType; 11532 11533 bool isInitList; 11534 llvm::SmallVector<unsigned, 4> InitFieldIndex; 11535 11536 public: 11537 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 11538 11539 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 11540 S(S), OrigDecl(OrigDecl) { 11541 isPODType = false; 11542 isRecordType = false; 11543 isReferenceType = false; 11544 isInitList = false; 11545 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 11546 isPODType = VD->getType().isPODType(S.Context); 11547 isRecordType = VD->getType()->isRecordType(); 11548 isReferenceType = VD->getType()->isReferenceType(); 11549 } 11550 } 11551 11552 // For most expressions, just call the visitor. For initializer lists, 11553 // track the index of the field being initialized since fields are 11554 // initialized in order allowing use of previously initialized fields. 11555 void CheckExpr(Expr *E) { 11556 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 11557 if (!InitList) { 11558 Visit(E); 11559 return; 11560 } 11561 11562 // Track and increment the index here. 11563 isInitList = true; 11564 InitFieldIndex.push_back(0); 11565 for (auto Child : InitList->children()) { 11566 CheckExpr(cast<Expr>(Child)); 11567 ++InitFieldIndex.back(); 11568 } 11569 InitFieldIndex.pop_back(); 11570 } 11571 11572 // Returns true if MemberExpr is checked and no further checking is needed. 11573 // Returns false if additional checking is required. 11574 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 11575 llvm::SmallVector<FieldDecl*, 4> Fields; 11576 Expr *Base = E; 11577 bool ReferenceField = false; 11578 11579 // Get the field members used. 11580 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11581 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 11582 if (!FD) 11583 return false; 11584 Fields.push_back(FD); 11585 if (FD->getType()->isReferenceType()) 11586 ReferenceField = true; 11587 Base = ME->getBase()->IgnoreParenImpCasts(); 11588 } 11589 11590 // Keep checking only if the base Decl is the same. 11591 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 11592 if (!DRE || DRE->getDecl() != OrigDecl) 11593 return false; 11594 11595 // A reference field can be bound to an unininitialized field. 11596 if (CheckReference && !ReferenceField) 11597 return true; 11598 11599 // Convert FieldDecls to their index number. 11600 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 11601 for (const FieldDecl *I : llvm::reverse(Fields)) 11602 UsedFieldIndex.push_back(I->getFieldIndex()); 11603 11604 // See if a warning is needed by checking the first difference in index 11605 // numbers. If field being used has index less than the field being 11606 // initialized, then the use is safe. 11607 for (auto UsedIter = UsedFieldIndex.begin(), 11608 UsedEnd = UsedFieldIndex.end(), 11609 OrigIter = InitFieldIndex.begin(), 11610 OrigEnd = InitFieldIndex.end(); 11611 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 11612 if (*UsedIter < *OrigIter) 11613 return true; 11614 if (*UsedIter > *OrigIter) 11615 break; 11616 } 11617 11618 // TODO: Add a different warning which will print the field names. 11619 HandleDeclRefExpr(DRE); 11620 return true; 11621 } 11622 11623 // For most expressions, the cast is directly above the DeclRefExpr. 11624 // For conditional operators, the cast can be outside the conditional 11625 // operator if both expressions are DeclRefExpr's. 11626 void HandleValue(Expr *E) { 11627 E = E->IgnoreParens(); 11628 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 11629 HandleDeclRefExpr(DRE); 11630 return; 11631 } 11632 11633 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 11634 Visit(CO->getCond()); 11635 HandleValue(CO->getTrueExpr()); 11636 HandleValue(CO->getFalseExpr()); 11637 return; 11638 } 11639 11640 if (BinaryConditionalOperator *BCO = 11641 dyn_cast<BinaryConditionalOperator>(E)) { 11642 Visit(BCO->getCond()); 11643 HandleValue(BCO->getFalseExpr()); 11644 return; 11645 } 11646 11647 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 11648 HandleValue(OVE->getSourceExpr()); 11649 return; 11650 } 11651 11652 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11653 if (BO->getOpcode() == BO_Comma) { 11654 Visit(BO->getLHS()); 11655 HandleValue(BO->getRHS()); 11656 return; 11657 } 11658 } 11659 11660 if (isa<MemberExpr>(E)) { 11661 if (isInitList) { 11662 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 11663 false /*CheckReference*/)) 11664 return; 11665 } 11666 11667 Expr *Base = E->IgnoreParenImpCasts(); 11668 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11669 // Check for static member variables and don't warn on them. 11670 if (!isa<FieldDecl>(ME->getMemberDecl())) 11671 return; 11672 Base = ME->getBase()->IgnoreParenImpCasts(); 11673 } 11674 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 11675 HandleDeclRefExpr(DRE); 11676 return; 11677 } 11678 11679 Visit(E); 11680 } 11681 11682 // Reference types not handled in HandleValue are handled here since all 11683 // uses of references are bad, not just r-value uses. 11684 void VisitDeclRefExpr(DeclRefExpr *E) { 11685 if (isReferenceType) 11686 HandleDeclRefExpr(E); 11687 } 11688 11689 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 11690 if (E->getCastKind() == CK_LValueToRValue) { 11691 HandleValue(E->getSubExpr()); 11692 return; 11693 } 11694 11695 Inherited::VisitImplicitCastExpr(E); 11696 } 11697 11698 void VisitMemberExpr(MemberExpr *E) { 11699 if (isInitList) { 11700 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 11701 return; 11702 } 11703 11704 // Don't warn on arrays since they can be treated as pointers. 11705 if (E->getType()->canDecayToPointerType()) return; 11706 11707 // Warn when a non-static method call is followed by non-static member 11708 // field accesses, which is followed by a DeclRefExpr. 11709 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 11710 bool Warn = (MD && !MD->isStatic()); 11711 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 11712 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11713 if (!isa<FieldDecl>(ME->getMemberDecl())) 11714 Warn = false; 11715 Base = ME->getBase()->IgnoreParenImpCasts(); 11716 } 11717 11718 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 11719 if (Warn) 11720 HandleDeclRefExpr(DRE); 11721 return; 11722 } 11723 11724 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 11725 // Visit that expression. 11726 Visit(Base); 11727 } 11728 11729 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 11730 Expr *Callee = E->getCallee(); 11731 11732 if (isa<UnresolvedLookupExpr>(Callee)) 11733 return Inherited::VisitCXXOperatorCallExpr(E); 11734 11735 Visit(Callee); 11736 for (auto Arg: E->arguments()) 11737 HandleValue(Arg->IgnoreParenImpCasts()); 11738 } 11739 11740 void VisitUnaryOperator(UnaryOperator *E) { 11741 // For POD record types, addresses of its own members are well-defined. 11742 if (E->getOpcode() == UO_AddrOf && isRecordType && 11743 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 11744 if (!isPODType) 11745 HandleValue(E->getSubExpr()); 11746 return; 11747 } 11748 11749 if (E->isIncrementDecrementOp()) { 11750 HandleValue(E->getSubExpr()); 11751 return; 11752 } 11753 11754 Inherited::VisitUnaryOperator(E); 11755 } 11756 11757 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 11758 11759 void VisitCXXConstructExpr(CXXConstructExpr *E) { 11760 if (E->getConstructor()->isCopyConstructor()) { 11761 Expr *ArgExpr = E->getArg(0); 11762 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 11763 if (ILE->getNumInits() == 1) 11764 ArgExpr = ILE->getInit(0); 11765 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 11766 if (ICE->getCastKind() == CK_NoOp) 11767 ArgExpr = ICE->getSubExpr(); 11768 HandleValue(ArgExpr); 11769 return; 11770 } 11771 Inherited::VisitCXXConstructExpr(E); 11772 } 11773 11774 void VisitCallExpr(CallExpr *E) { 11775 // Treat std::move as a use. 11776 if (E->isCallToStdMove()) { 11777 HandleValue(E->getArg(0)); 11778 return; 11779 } 11780 11781 Inherited::VisitCallExpr(E); 11782 } 11783 11784 void VisitBinaryOperator(BinaryOperator *E) { 11785 if (E->isCompoundAssignmentOp()) { 11786 HandleValue(E->getLHS()); 11787 Visit(E->getRHS()); 11788 return; 11789 } 11790 11791 Inherited::VisitBinaryOperator(E); 11792 } 11793 11794 // A custom visitor for BinaryConditionalOperator is needed because the 11795 // regular visitor would check the condition and true expression separately 11796 // but both point to the same place giving duplicate diagnostics. 11797 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 11798 Visit(E->getCond()); 11799 Visit(E->getFalseExpr()); 11800 } 11801 11802 void HandleDeclRefExpr(DeclRefExpr *DRE) { 11803 Decl* ReferenceDecl = DRE->getDecl(); 11804 if (OrigDecl != ReferenceDecl) return; 11805 unsigned diag; 11806 if (isReferenceType) { 11807 diag = diag::warn_uninit_self_reference_in_reference_init; 11808 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 11809 diag = diag::warn_static_self_reference_in_init; 11810 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 11811 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 11812 DRE->getDecl()->getType()->isRecordType()) { 11813 diag = diag::warn_uninit_self_reference_in_init; 11814 } else { 11815 // Local variables will be handled by the CFG analysis. 11816 return; 11817 } 11818 11819 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE, 11820 S.PDiag(diag) 11821 << DRE->getDecl() << OrigDecl->getLocation() 11822 << DRE->getSourceRange()); 11823 } 11824 }; 11825 11826 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 11827 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 11828 bool DirectInit) { 11829 // Parameters arguments are occassionially constructed with itself, 11830 // for instance, in recursive functions. Skip them. 11831 if (isa<ParmVarDecl>(OrigDecl)) 11832 return; 11833 11834 E = E->IgnoreParens(); 11835 11836 // Skip checking T a = a where T is not a record or reference type. 11837 // Doing so is a way to silence uninitialized warnings. 11838 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 11839 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 11840 if (ICE->getCastKind() == CK_LValueToRValue) 11841 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 11842 if (DRE->getDecl() == OrigDecl) 11843 return; 11844 11845 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 11846 } 11847 } // end anonymous namespace 11848 11849 namespace { 11850 // Simple wrapper to add the name of a variable or (if no variable is 11851 // available) a DeclarationName into a diagnostic. 11852 struct VarDeclOrName { 11853 VarDecl *VDecl; 11854 DeclarationName Name; 11855 11856 friend const Sema::SemaDiagnosticBuilder & 11857 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 11858 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 11859 } 11860 }; 11861 } // end anonymous namespace 11862 11863 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 11864 DeclarationName Name, QualType Type, 11865 TypeSourceInfo *TSI, 11866 SourceRange Range, bool DirectInit, 11867 Expr *Init) { 11868 bool IsInitCapture = !VDecl; 11869 assert((!VDecl || !VDecl->isInitCapture()) && 11870 "init captures are expected to be deduced prior to initialization"); 11871 11872 VarDeclOrName VN{VDecl, Name}; 11873 11874 DeducedType *Deduced = Type->getContainedDeducedType(); 11875 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 11876 11877 // C++11 [dcl.spec.auto]p3 11878 if (!Init) { 11879 assert(VDecl && "no init for init capture deduction?"); 11880 11881 // Except for class argument deduction, and then for an initializing 11882 // declaration only, i.e. no static at class scope or extern. 11883 if (!isa<DeducedTemplateSpecializationType>(Deduced) || 11884 VDecl->hasExternalStorage() || 11885 VDecl->isStaticDataMember()) { 11886 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 11887 << VDecl->getDeclName() << Type; 11888 return QualType(); 11889 } 11890 } 11891 11892 ArrayRef<Expr*> DeduceInits; 11893 if (Init) 11894 DeduceInits = Init; 11895 11896 if (DirectInit) { 11897 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) 11898 DeduceInits = PL->exprs(); 11899 } 11900 11901 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 11902 assert(VDecl && "non-auto type for init capture deduction?"); 11903 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 11904 InitializationKind Kind = InitializationKind::CreateForInit( 11905 VDecl->getLocation(), DirectInit, Init); 11906 // FIXME: Initialization should not be taking a mutable list of inits. 11907 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 11908 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 11909 InitsCopy); 11910 } 11911 11912 if (DirectInit) { 11913 if (auto *IL = dyn_cast<InitListExpr>(Init)) 11914 DeduceInits = IL->inits(); 11915 } 11916 11917 // Deduction only works if we have exactly one source expression. 11918 if (DeduceInits.empty()) { 11919 // It isn't possible to write this directly, but it is possible to 11920 // end up in this situation with "auto x(some_pack...);" 11921 Diag(Init->getBeginLoc(), IsInitCapture 11922 ? diag::err_init_capture_no_expression 11923 : diag::err_auto_var_init_no_expression) 11924 << VN << Type << Range; 11925 return QualType(); 11926 } 11927 11928 if (DeduceInits.size() > 1) { 11929 Diag(DeduceInits[1]->getBeginLoc(), 11930 IsInitCapture ? diag::err_init_capture_multiple_expressions 11931 : diag::err_auto_var_init_multiple_expressions) 11932 << VN << Type << Range; 11933 return QualType(); 11934 } 11935 11936 Expr *DeduceInit = DeduceInits[0]; 11937 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 11938 Diag(Init->getBeginLoc(), IsInitCapture 11939 ? diag::err_init_capture_paren_braces 11940 : diag::err_auto_var_init_paren_braces) 11941 << isa<InitListExpr>(Init) << VN << Type << Range; 11942 return QualType(); 11943 } 11944 11945 // Expressions default to 'id' when we're in a debugger. 11946 bool DefaultedAnyToId = false; 11947 if (getLangOpts().DebuggerCastResultToId && 11948 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 11949 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 11950 if (Result.isInvalid()) { 11951 return QualType(); 11952 } 11953 Init = Result.get(); 11954 DefaultedAnyToId = true; 11955 } 11956 11957 // C++ [dcl.decomp]p1: 11958 // If the assignment-expression [...] has array type A and no ref-qualifier 11959 // is present, e has type cv A 11960 if (VDecl && isa<DecompositionDecl>(VDecl) && 11961 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 11962 DeduceInit->getType()->isConstantArrayType()) 11963 return Context.getQualifiedType(DeduceInit->getType(), 11964 Type.getQualifiers()); 11965 11966 QualType DeducedType; 11967 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 11968 if (!IsInitCapture) 11969 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 11970 else if (isa<InitListExpr>(Init)) 11971 Diag(Range.getBegin(), 11972 diag::err_init_capture_deduction_failure_from_init_list) 11973 << VN 11974 << (DeduceInit->getType().isNull() ? TSI->getType() 11975 : DeduceInit->getType()) 11976 << DeduceInit->getSourceRange(); 11977 else 11978 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 11979 << VN << TSI->getType() 11980 << (DeduceInit->getType().isNull() ? TSI->getType() 11981 : DeduceInit->getType()) 11982 << DeduceInit->getSourceRange(); 11983 } 11984 11985 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 11986 // 'id' instead of a specific object type prevents most of our usual 11987 // checks. 11988 // We only want to warn outside of template instantiations, though: 11989 // inside a template, the 'id' could have come from a parameter. 11990 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 11991 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 11992 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 11993 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 11994 } 11995 11996 return DeducedType; 11997 } 11998 11999 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 12000 Expr *Init) { 12001 assert(!Init || !Init->containsErrors()); 12002 QualType DeducedType = deduceVarTypeFromInitializer( 12003 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 12004 VDecl->getSourceRange(), DirectInit, Init); 12005 if (DeducedType.isNull()) { 12006 VDecl->setInvalidDecl(); 12007 return true; 12008 } 12009 12010 VDecl->setType(DeducedType); 12011 assert(VDecl->isLinkageValid()); 12012 12013 // In ARC, infer lifetime. 12014 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 12015 VDecl->setInvalidDecl(); 12016 12017 if (getLangOpts().OpenCL) 12018 deduceOpenCLAddressSpace(VDecl); 12019 12020 // If this is a redeclaration, check that the type we just deduced matches 12021 // the previously declared type. 12022 if (VarDecl *Old = VDecl->getPreviousDecl()) { 12023 // We never need to merge the type, because we cannot form an incomplete 12024 // array of auto, nor deduce such a type. 12025 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 12026 } 12027 12028 // Check the deduced type is valid for a variable declaration. 12029 CheckVariableDeclarationType(VDecl); 12030 return VDecl->isInvalidDecl(); 12031 } 12032 12033 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init, 12034 SourceLocation Loc) { 12035 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init)) 12036 Init = EWC->getSubExpr(); 12037 12038 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 12039 Init = CE->getSubExpr(); 12040 12041 QualType InitType = Init->getType(); 12042 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12043 InitType.hasNonTrivialToPrimitiveCopyCUnion()) && 12044 "shouldn't be called if type doesn't have a non-trivial C struct"); 12045 if (auto *ILE = dyn_cast<InitListExpr>(Init)) { 12046 for (auto I : ILE->inits()) { 12047 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() && 12048 !I->getType().hasNonTrivialToPrimitiveCopyCUnion()) 12049 continue; 12050 SourceLocation SL = I->getExprLoc(); 12051 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc); 12052 } 12053 return; 12054 } 12055 12056 if (isa<ImplicitValueInitExpr>(Init)) { 12057 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 12058 checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject, 12059 NTCUK_Init); 12060 } else { 12061 // Assume all other explicit initializers involving copying some existing 12062 // object. 12063 // TODO: ignore any explicit initializers where we can guarantee 12064 // copy-elision. 12065 if (InitType.hasNonTrivialToPrimitiveCopyCUnion()) 12066 checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy); 12067 } 12068 } 12069 12070 namespace { 12071 12072 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) { 12073 // Ignore unavailable fields. A field can be marked as unavailable explicitly 12074 // in the source code or implicitly by the compiler if it is in a union 12075 // defined in a system header and has non-trivial ObjC ownership 12076 // qualifications. We don't want those fields to participate in determining 12077 // whether the containing union is non-trivial. 12078 return FD->hasAttr<UnavailableAttr>(); 12079 } 12080 12081 struct DiagNonTrivalCUnionDefaultInitializeVisitor 12082 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 12083 void> { 12084 using Super = 12085 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 12086 void>; 12087 12088 DiagNonTrivalCUnionDefaultInitializeVisitor( 12089 QualType OrigTy, SourceLocation OrigLoc, 12090 Sema::NonTrivialCUnionContext UseContext, Sema &S) 12091 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 12092 12093 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT, 12094 const FieldDecl *FD, bool InNonTrivialUnion) { 12095 if (const auto *AT = S.Context.getAsArrayType(QT)) 12096 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 12097 InNonTrivialUnion); 12098 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion); 12099 } 12100 12101 void visitARCStrong(QualType QT, const FieldDecl *FD, 12102 bool InNonTrivialUnion) { 12103 if (InNonTrivialUnion) 12104 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12105 << 1 << 0 << QT << FD->getName(); 12106 } 12107 12108 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12109 if (InNonTrivialUnion) 12110 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12111 << 1 << 0 << QT << FD->getName(); 12112 } 12113 12114 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12115 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 12116 if (RD->isUnion()) { 12117 if (OrigLoc.isValid()) { 12118 bool IsUnion = false; 12119 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 12120 IsUnion = OrigRD->isUnion(); 12121 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 12122 << 0 << OrigTy << IsUnion << UseContext; 12123 // Reset OrigLoc so that this diagnostic is emitted only once. 12124 OrigLoc = SourceLocation(); 12125 } 12126 InNonTrivialUnion = true; 12127 } 12128 12129 if (InNonTrivialUnion) 12130 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 12131 << 0 << 0 << QT.getUnqualifiedType() << ""; 12132 12133 for (const FieldDecl *FD : RD->fields()) 12134 if (!shouldIgnoreForRecordTriviality(FD)) 12135 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 12136 } 12137 12138 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 12139 12140 // The non-trivial C union type or the struct/union type that contains a 12141 // non-trivial C union. 12142 QualType OrigTy; 12143 SourceLocation OrigLoc; 12144 Sema::NonTrivialCUnionContext UseContext; 12145 Sema &S; 12146 }; 12147 12148 struct DiagNonTrivalCUnionDestructedTypeVisitor 12149 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> { 12150 using Super = 12151 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>; 12152 12153 DiagNonTrivalCUnionDestructedTypeVisitor( 12154 QualType OrigTy, SourceLocation OrigLoc, 12155 Sema::NonTrivialCUnionContext UseContext, Sema &S) 12156 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 12157 12158 void visitWithKind(QualType::DestructionKind DK, QualType QT, 12159 const FieldDecl *FD, bool InNonTrivialUnion) { 12160 if (const auto *AT = S.Context.getAsArrayType(QT)) 12161 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 12162 InNonTrivialUnion); 12163 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion); 12164 } 12165 12166 void visitARCStrong(QualType QT, const FieldDecl *FD, 12167 bool InNonTrivialUnion) { 12168 if (InNonTrivialUnion) 12169 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12170 << 1 << 1 << QT << FD->getName(); 12171 } 12172 12173 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12174 if (InNonTrivialUnion) 12175 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12176 << 1 << 1 << QT << FD->getName(); 12177 } 12178 12179 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12180 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 12181 if (RD->isUnion()) { 12182 if (OrigLoc.isValid()) { 12183 bool IsUnion = false; 12184 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 12185 IsUnion = OrigRD->isUnion(); 12186 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 12187 << 1 << OrigTy << IsUnion << UseContext; 12188 // Reset OrigLoc so that this diagnostic is emitted only once. 12189 OrigLoc = SourceLocation(); 12190 } 12191 InNonTrivialUnion = true; 12192 } 12193 12194 if (InNonTrivialUnion) 12195 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 12196 << 0 << 1 << QT.getUnqualifiedType() << ""; 12197 12198 for (const FieldDecl *FD : RD->fields()) 12199 if (!shouldIgnoreForRecordTriviality(FD)) 12200 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 12201 } 12202 12203 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 12204 void visitCXXDestructor(QualType QT, const FieldDecl *FD, 12205 bool InNonTrivialUnion) {} 12206 12207 // The non-trivial C union type or the struct/union type that contains a 12208 // non-trivial C union. 12209 QualType OrigTy; 12210 SourceLocation OrigLoc; 12211 Sema::NonTrivialCUnionContext UseContext; 12212 Sema &S; 12213 }; 12214 12215 struct DiagNonTrivalCUnionCopyVisitor 12216 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> { 12217 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>; 12218 12219 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc, 12220 Sema::NonTrivialCUnionContext UseContext, 12221 Sema &S) 12222 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 12223 12224 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT, 12225 const FieldDecl *FD, bool InNonTrivialUnion) { 12226 if (const auto *AT = S.Context.getAsArrayType(QT)) 12227 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 12228 InNonTrivialUnion); 12229 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion); 12230 } 12231 12232 void visitARCStrong(QualType QT, const FieldDecl *FD, 12233 bool InNonTrivialUnion) { 12234 if (InNonTrivialUnion) 12235 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12236 << 1 << 2 << QT << FD->getName(); 12237 } 12238 12239 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12240 if (InNonTrivialUnion) 12241 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12242 << 1 << 2 << QT << FD->getName(); 12243 } 12244 12245 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12246 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 12247 if (RD->isUnion()) { 12248 if (OrigLoc.isValid()) { 12249 bool IsUnion = false; 12250 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 12251 IsUnion = OrigRD->isUnion(); 12252 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 12253 << 2 << OrigTy << IsUnion << UseContext; 12254 // Reset OrigLoc so that this diagnostic is emitted only once. 12255 OrigLoc = SourceLocation(); 12256 } 12257 InNonTrivialUnion = true; 12258 } 12259 12260 if (InNonTrivialUnion) 12261 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 12262 << 0 << 2 << QT.getUnqualifiedType() << ""; 12263 12264 for (const FieldDecl *FD : RD->fields()) 12265 if (!shouldIgnoreForRecordTriviality(FD)) 12266 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 12267 } 12268 12269 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT, 12270 const FieldDecl *FD, bool InNonTrivialUnion) {} 12271 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 12272 void visitVolatileTrivial(QualType QT, const FieldDecl *FD, 12273 bool InNonTrivialUnion) {} 12274 12275 // The non-trivial C union type or the struct/union type that contains a 12276 // non-trivial C union. 12277 QualType OrigTy; 12278 SourceLocation OrigLoc; 12279 Sema::NonTrivialCUnionContext UseContext; 12280 Sema &S; 12281 }; 12282 12283 } // namespace 12284 12285 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc, 12286 NonTrivialCUnionContext UseContext, 12287 unsigned NonTrivialKind) { 12288 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12289 QT.hasNonTrivialToPrimitiveDestructCUnion() || 12290 QT.hasNonTrivialToPrimitiveCopyCUnion()) && 12291 "shouldn't be called if type doesn't have a non-trivial C union"); 12292 12293 if ((NonTrivialKind & NTCUK_Init) && 12294 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 12295 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this) 12296 .visit(QT, nullptr, false); 12297 if ((NonTrivialKind & NTCUK_Destruct) && 12298 QT.hasNonTrivialToPrimitiveDestructCUnion()) 12299 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this) 12300 .visit(QT, nullptr, false); 12301 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion()) 12302 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this) 12303 .visit(QT, nullptr, false); 12304 } 12305 12306 /// AddInitializerToDecl - Adds the initializer Init to the 12307 /// declaration dcl. If DirectInit is true, this is C++ direct 12308 /// initialization rather than copy initialization. 12309 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 12310 // If there is no declaration, there was an error parsing it. Just ignore 12311 // the initializer. 12312 if (!RealDecl || RealDecl->isInvalidDecl()) { 12313 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 12314 return; 12315 } 12316 12317 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 12318 // Pure-specifiers are handled in ActOnPureSpecifier. 12319 Diag(Method->getLocation(), diag::err_member_function_initialization) 12320 << Method->getDeclName() << Init->getSourceRange(); 12321 Method->setInvalidDecl(); 12322 return; 12323 } 12324 12325 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 12326 if (!VDecl) { 12327 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 12328 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 12329 RealDecl->setInvalidDecl(); 12330 return; 12331 } 12332 12333 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 12334 if (VDecl->getType()->isUndeducedType()) { 12335 // Attempt typo correction early so that the type of the init expression can 12336 // be deduced based on the chosen correction if the original init contains a 12337 // TypoExpr. 12338 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 12339 if (!Res.isUsable()) { 12340 // There are unresolved typos in Init, just drop them. 12341 // FIXME: improve the recovery strategy to preserve the Init. 12342 RealDecl->setInvalidDecl(); 12343 return; 12344 } 12345 if (Res.get()->containsErrors()) { 12346 // Invalidate the decl as we don't know the type for recovery-expr yet. 12347 RealDecl->setInvalidDecl(); 12348 VDecl->setInit(Res.get()); 12349 return; 12350 } 12351 Init = Res.get(); 12352 12353 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 12354 return; 12355 } 12356 12357 // dllimport cannot be used on variable definitions. 12358 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 12359 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 12360 VDecl->setInvalidDecl(); 12361 return; 12362 } 12363 12364 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 12365 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 12366 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 12367 VDecl->setInvalidDecl(); 12368 return; 12369 } 12370 12371 if (!VDecl->getType()->isDependentType()) { 12372 // A definition must end up with a complete type, which means it must be 12373 // complete with the restriction that an array type might be completed by 12374 // the initializer; note that later code assumes this restriction. 12375 QualType BaseDeclType = VDecl->getType(); 12376 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 12377 BaseDeclType = Array->getElementType(); 12378 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 12379 diag::err_typecheck_decl_incomplete_type)) { 12380 RealDecl->setInvalidDecl(); 12381 return; 12382 } 12383 12384 // The variable can not have an abstract class type. 12385 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 12386 diag::err_abstract_type_in_decl, 12387 AbstractVariableType)) 12388 VDecl->setInvalidDecl(); 12389 } 12390 12391 // If adding the initializer will turn this declaration into a definition, 12392 // and we already have a definition for this variable, diagnose or otherwise 12393 // handle the situation. 12394 if (VarDecl *Def = VDecl->getDefinition()) 12395 if (Def != VDecl && 12396 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 12397 !VDecl->isThisDeclarationADemotedDefinition() && 12398 checkVarDeclRedefinition(Def, VDecl)) 12399 return; 12400 12401 if (getLangOpts().CPlusPlus) { 12402 // C++ [class.static.data]p4 12403 // If a static data member is of const integral or const 12404 // enumeration type, its declaration in the class definition can 12405 // specify a constant-initializer which shall be an integral 12406 // constant expression (5.19). In that case, the member can appear 12407 // in integral constant expressions. The member shall still be 12408 // defined in a namespace scope if it is used in the program and the 12409 // namespace scope definition shall not contain an initializer. 12410 // 12411 // We already performed a redefinition check above, but for static 12412 // data members we also need to check whether there was an in-class 12413 // declaration with an initializer. 12414 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 12415 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 12416 << VDecl->getDeclName(); 12417 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 12418 diag::note_previous_initializer) 12419 << 0; 12420 return; 12421 } 12422 12423 if (VDecl->hasLocalStorage()) 12424 setFunctionHasBranchProtectedScope(); 12425 12426 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 12427 VDecl->setInvalidDecl(); 12428 return; 12429 } 12430 } 12431 12432 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 12433 // a kernel function cannot be initialized." 12434 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 12435 Diag(VDecl->getLocation(), diag::err_local_cant_init); 12436 VDecl->setInvalidDecl(); 12437 return; 12438 } 12439 12440 // The LoaderUninitialized attribute acts as a definition (of undef). 12441 if (VDecl->hasAttr<LoaderUninitializedAttr>()) { 12442 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init); 12443 VDecl->setInvalidDecl(); 12444 return; 12445 } 12446 12447 // Get the decls type and save a reference for later, since 12448 // CheckInitializerTypes may change it. 12449 QualType DclT = VDecl->getType(), SavT = DclT; 12450 12451 // Expressions default to 'id' when we're in a debugger 12452 // and we are assigning it to a variable of Objective-C pointer type. 12453 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 12454 Init->getType() == Context.UnknownAnyTy) { 12455 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 12456 if (Result.isInvalid()) { 12457 VDecl->setInvalidDecl(); 12458 return; 12459 } 12460 Init = Result.get(); 12461 } 12462 12463 // Perform the initialization. 12464 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 12465 if (!VDecl->isInvalidDecl()) { 12466 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 12467 InitializationKind Kind = InitializationKind::CreateForInit( 12468 VDecl->getLocation(), DirectInit, Init); 12469 12470 MultiExprArg Args = Init; 12471 if (CXXDirectInit) 12472 Args = MultiExprArg(CXXDirectInit->getExprs(), 12473 CXXDirectInit->getNumExprs()); 12474 12475 // Try to correct any TypoExprs in the initialization arguments. 12476 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 12477 ExprResult Res = CorrectDelayedTyposInExpr( 12478 Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true, 12479 [this, Entity, Kind](Expr *E) { 12480 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 12481 return Init.Failed() ? ExprError() : E; 12482 }); 12483 if (Res.isInvalid()) { 12484 VDecl->setInvalidDecl(); 12485 } else if (Res.get() != Args[Idx]) { 12486 Args[Idx] = Res.get(); 12487 } 12488 } 12489 if (VDecl->isInvalidDecl()) 12490 return; 12491 12492 InitializationSequence InitSeq(*this, Entity, Kind, Args, 12493 /*TopLevelOfInitList=*/false, 12494 /*TreatUnavailableAsInvalid=*/false); 12495 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 12496 if (Result.isInvalid()) { 12497 // If the provided initializer fails to initialize the var decl, 12498 // we attach a recovery expr for better recovery. 12499 auto RecoveryExpr = 12500 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args); 12501 if (RecoveryExpr.get()) 12502 VDecl->setInit(RecoveryExpr.get()); 12503 return; 12504 } 12505 12506 Init = Result.getAs<Expr>(); 12507 } 12508 12509 // Check for self-references within variable initializers. 12510 // Variables declared within a function/method body (except for references) 12511 // are handled by a dataflow analysis. 12512 // This is undefined behavior in C++, but valid in C. 12513 if (getLangOpts().CPlusPlus) 12514 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 12515 VDecl->getType()->isReferenceType()) 12516 CheckSelfReference(*this, RealDecl, Init, DirectInit); 12517 12518 // If the type changed, it means we had an incomplete type that was 12519 // completed by the initializer. For example: 12520 // int ary[] = { 1, 3, 5 }; 12521 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 12522 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 12523 VDecl->setType(DclT); 12524 12525 if (!VDecl->isInvalidDecl()) { 12526 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 12527 12528 if (VDecl->hasAttr<BlocksAttr>()) 12529 checkRetainCycles(VDecl, Init); 12530 12531 // It is safe to assign a weak reference into a strong variable. 12532 // Although this code can still have problems: 12533 // id x = self.weakProp; 12534 // id y = self.weakProp; 12535 // we do not warn to warn spuriously when 'x' and 'y' are on separate 12536 // paths through the function. This should be revisited if 12537 // -Wrepeated-use-of-weak is made flow-sensitive. 12538 if (FunctionScopeInfo *FSI = getCurFunction()) 12539 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 12540 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 12541 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 12542 Init->getBeginLoc())) 12543 FSI->markSafeWeakUse(Init); 12544 } 12545 12546 // The initialization is usually a full-expression. 12547 // 12548 // FIXME: If this is a braced initialization of an aggregate, it is not 12549 // an expression, and each individual field initializer is a separate 12550 // full-expression. For instance, in: 12551 // 12552 // struct Temp { ~Temp(); }; 12553 // struct S { S(Temp); }; 12554 // struct T { S a, b; } t = { Temp(), Temp() } 12555 // 12556 // we should destroy the first Temp before constructing the second. 12557 ExprResult Result = 12558 ActOnFinishFullExpr(Init, VDecl->getLocation(), 12559 /*DiscardedValue*/ false, VDecl->isConstexpr()); 12560 if (Result.isInvalid()) { 12561 VDecl->setInvalidDecl(); 12562 return; 12563 } 12564 Init = Result.get(); 12565 12566 // Attach the initializer to the decl. 12567 VDecl->setInit(Init); 12568 12569 if (VDecl->isLocalVarDecl()) { 12570 // Don't check the initializer if the declaration is malformed. 12571 if (VDecl->isInvalidDecl()) { 12572 // do nothing 12573 12574 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 12575 // This is true even in C++ for OpenCL. 12576 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 12577 CheckForConstantInitializer(Init, DclT); 12578 12579 // Otherwise, C++ does not restrict the initializer. 12580 } else if (getLangOpts().CPlusPlus) { 12581 // do nothing 12582 12583 // C99 6.7.8p4: All the expressions in an initializer for an object that has 12584 // static storage duration shall be constant expressions or string literals. 12585 } else if (VDecl->getStorageClass() == SC_Static) { 12586 CheckForConstantInitializer(Init, DclT); 12587 12588 // C89 is stricter than C99 for aggregate initializers. 12589 // C89 6.5.7p3: All the expressions [...] in an initializer list 12590 // for an object that has aggregate or union type shall be 12591 // constant expressions. 12592 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 12593 isa<InitListExpr>(Init)) { 12594 const Expr *Culprit; 12595 if (!Init->isConstantInitializer(Context, false, &Culprit)) { 12596 Diag(Culprit->getExprLoc(), 12597 diag::ext_aggregate_init_not_constant) 12598 << Culprit->getSourceRange(); 12599 } 12600 } 12601 12602 if (auto *E = dyn_cast<ExprWithCleanups>(Init)) 12603 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens())) 12604 if (VDecl->hasLocalStorage()) 12605 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 12606 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 12607 VDecl->getLexicalDeclContext()->isRecord()) { 12608 // This is an in-class initialization for a static data member, e.g., 12609 // 12610 // struct S { 12611 // static const int value = 17; 12612 // }; 12613 12614 // C++ [class.mem]p4: 12615 // A member-declarator can contain a constant-initializer only 12616 // if it declares a static member (9.4) of const integral or 12617 // const enumeration type, see 9.4.2. 12618 // 12619 // C++11 [class.static.data]p3: 12620 // If a non-volatile non-inline const static data member is of integral 12621 // or enumeration type, its declaration in the class definition can 12622 // specify a brace-or-equal-initializer in which every initializer-clause 12623 // that is an assignment-expression is a constant expression. A static 12624 // data member of literal type can be declared in the class definition 12625 // with the constexpr specifier; if so, its declaration shall specify a 12626 // brace-or-equal-initializer in which every initializer-clause that is 12627 // an assignment-expression is a constant expression. 12628 12629 // Do nothing on dependent types. 12630 if (DclT->isDependentType()) { 12631 12632 // Allow any 'static constexpr' members, whether or not they are of literal 12633 // type. We separately check that every constexpr variable is of literal 12634 // type. 12635 } else if (VDecl->isConstexpr()) { 12636 12637 // Require constness. 12638 } else if (!DclT.isConstQualified()) { 12639 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 12640 << Init->getSourceRange(); 12641 VDecl->setInvalidDecl(); 12642 12643 // We allow integer constant expressions in all cases. 12644 } else if (DclT->isIntegralOrEnumerationType()) { 12645 // Check whether the expression is a constant expression. 12646 SourceLocation Loc; 12647 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 12648 // In C++11, a non-constexpr const static data member with an 12649 // in-class initializer cannot be volatile. 12650 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 12651 else if (Init->isValueDependent()) 12652 ; // Nothing to check. 12653 else if (Init->isIntegerConstantExpr(Context, &Loc)) 12654 ; // Ok, it's an ICE! 12655 else if (Init->getType()->isScopedEnumeralType() && 12656 Init->isCXX11ConstantExpr(Context)) 12657 ; // Ok, it is a scoped-enum constant expression. 12658 else if (Init->isEvaluatable(Context)) { 12659 // If we can constant fold the initializer through heroics, accept it, 12660 // but report this as a use of an extension for -pedantic. 12661 Diag(Loc, diag::ext_in_class_initializer_non_constant) 12662 << Init->getSourceRange(); 12663 } else { 12664 // Otherwise, this is some crazy unknown case. Report the issue at the 12665 // location provided by the isIntegerConstantExpr failed check. 12666 Diag(Loc, diag::err_in_class_initializer_non_constant) 12667 << Init->getSourceRange(); 12668 VDecl->setInvalidDecl(); 12669 } 12670 12671 // We allow foldable floating-point constants as an extension. 12672 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 12673 // In C++98, this is a GNU extension. In C++11, it is not, but we support 12674 // it anyway and provide a fixit to add the 'constexpr'. 12675 if (getLangOpts().CPlusPlus11) { 12676 Diag(VDecl->getLocation(), 12677 diag::ext_in_class_initializer_float_type_cxx11) 12678 << DclT << Init->getSourceRange(); 12679 Diag(VDecl->getBeginLoc(), 12680 diag::note_in_class_initializer_float_type_cxx11) 12681 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12682 } else { 12683 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 12684 << DclT << Init->getSourceRange(); 12685 12686 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 12687 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 12688 << Init->getSourceRange(); 12689 VDecl->setInvalidDecl(); 12690 } 12691 } 12692 12693 // Suggest adding 'constexpr' in C++11 for literal types. 12694 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 12695 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 12696 << DclT << Init->getSourceRange() 12697 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12698 VDecl->setConstexpr(true); 12699 12700 } else { 12701 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 12702 << DclT << Init->getSourceRange(); 12703 VDecl->setInvalidDecl(); 12704 } 12705 } else if (VDecl->isFileVarDecl()) { 12706 // In C, extern is typically used to avoid tentative definitions when 12707 // declaring variables in headers, but adding an intializer makes it a 12708 // definition. This is somewhat confusing, so GCC and Clang both warn on it. 12709 // In C++, extern is often used to give implictly static const variables 12710 // external linkage, so don't warn in that case. If selectany is present, 12711 // this might be header code intended for C and C++ inclusion, so apply the 12712 // C++ rules. 12713 if (VDecl->getStorageClass() == SC_Extern && 12714 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 12715 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 12716 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 12717 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 12718 Diag(VDecl->getLocation(), diag::warn_extern_init); 12719 12720 // In Microsoft C++ mode, a const variable defined in namespace scope has 12721 // external linkage by default if the variable is declared with 12722 // __declspec(dllexport). 12723 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 12724 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() && 12725 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition()) 12726 VDecl->setStorageClass(SC_Extern); 12727 12728 // C99 6.7.8p4. All file scoped initializers need to be constant. 12729 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 12730 CheckForConstantInitializer(Init, DclT); 12731 } 12732 12733 QualType InitType = Init->getType(); 12734 if (!InitType.isNull() && 12735 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12736 InitType.hasNonTrivialToPrimitiveCopyCUnion())) 12737 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc()); 12738 12739 // We will represent direct-initialization similarly to copy-initialization: 12740 // int x(1); -as-> int x = 1; 12741 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 12742 // 12743 // Clients that want to distinguish between the two forms, can check for 12744 // direct initializer using VarDecl::getInitStyle(). 12745 // A major benefit is that clients that don't particularly care about which 12746 // exactly form was it (like the CodeGen) can handle both cases without 12747 // special case code. 12748 12749 // C++ 8.5p11: 12750 // The form of initialization (using parentheses or '=') is generally 12751 // insignificant, but does matter when the entity being initialized has a 12752 // class type. 12753 if (CXXDirectInit) { 12754 assert(DirectInit && "Call-style initializer must be direct init."); 12755 VDecl->setInitStyle(VarDecl::CallInit); 12756 } else if (DirectInit) { 12757 // This must be list-initialization. No other way is direct-initialization. 12758 VDecl->setInitStyle(VarDecl::ListInit); 12759 } 12760 12761 if (LangOpts.OpenMP && 12762 (LangOpts.OpenMPIsDevice || !LangOpts.OMPTargetTriples.empty()) && 12763 VDecl->isFileVarDecl()) 12764 DeclsToCheckForDeferredDiags.insert(VDecl); 12765 CheckCompleteVariableDeclaration(VDecl); 12766 } 12767 12768 /// ActOnInitializerError - Given that there was an error parsing an 12769 /// initializer for the given declaration, try to at least re-establish 12770 /// invariants such as whether a variable's type is either dependent or 12771 /// complete. 12772 void Sema::ActOnInitializerError(Decl *D) { 12773 // Our main concern here is re-establishing invariants like "a 12774 // variable's type is either dependent or complete". 12775 if (!D || D->isInvalidDecl()) return; 12776 12777 VarDecl *VD = dyn_cast<VarDecl>(D); 12778 if (!VD) return; 12779 12780 // Bindings are not usable if we can't make sense of the initializer. 12781 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 12782 for (auto *BD : DD->bindings()) 12783 BD->setInvalidDecl(); 12784 12785 // Auto types are meaningless if we can't make sense of the initializer. 12786 if (VD->getType()->isUndeducedType()) { 12787 D->setInvalidDecl(); 12788 return; 12789 } 12790 12791 QualType Ty = VD->getType(); 12792 if (Ty->isDependentType()) return; 12793 12794 // Require a complete type. 12795 if (RequireCompleteType(VD->getLocation(), 12796 Context.getBaseElementType(Ty), 12797 diag::err_typecheck_decl_incomplete_type)) { 12798 VD->setInvalidDecl(); 12799 return; 12800 } 12801 12802 // Require a non-abstract type. 12803 if (RequireNonAbstractType(VD->getLocation(), Ty, 12804 diag::err_abstract_type_in_decl, 12805 AbstractVariableType)) { 12806 VD->setInvalidDecl(); 12807 return; 12808 } 12809 12810 // Don't bother complaining about constructors or destructors, 12811 // though. 12812 } 12813 12814 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 12815 // If there is no declaration, there was an error parsing it. Just ignore it. 12816 if (!RealDecl) 12817 return; 12818 12819 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 12820 QualType Type = Var->getType(); 12821 12822 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 12823 if (isa<DecompositionDecl>(RealDecl)) { 12824 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 12825 Var->setInvalidDecl(); 12826 return; 12827 } 12828 12829 if (Type->isUndeducedType() && 12830 DeduceVariableDeclarationType(Var, false, nullptr)) 12831 return; 12832 12833 // C++11 [class.static.data]p3: A static data member can be declared with 12834 // the constexpr specifier; if so, its declaration shall specify 12835 // a brace-or-equal-initializer. 12836 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 12837 // the definition of a variable [...] or the declaration of a static data 12838 // member. 12839 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 12840 !Var->isThisDeclarationADemotedDefinition()) { 12841 if (Var->isStaticDataMember()) { 12842 // C++1z removes the relevant rule; the in-class declaration is always 12843 // a definition there. 12844 if (!getLangOpts().CPlusPlus17 && 12845 !Context.getTargetInfo().getCXXABI().isMicrosoft()) { 12846 Diag(Var->getLocation(), 12847 diag::err_constexpr_static_mem_var_requires_init) 12848 << Var; 12849 Var->setInvalidDecl(); 12850 return; 12851 } 12852 } else { 12853 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 12854 Var->setInvalidDecl(); 12855 return; 12856 } 12857 } 12858 12859 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 12860 // be initialized. 12861 if (!Var->isInvalidDecl() && 12862 Var->getType().getAddressSpace() == LangAS::opencl_constant && 12863 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 12864 bool HasConstExprDefaultConstructor = false; 12865 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) { 12866 for (auto *Ctor : RD->ctors()) { 12867 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 && 12868 Ctor->getMethodQualifiers().getAddressSpace() == 12869 LangAS::opencl_constant) { 12870 HasConstExprDefaultConstructor = true; 12871 } 12872 } 12873 } 12874 if (!HasConstExprDefaultConstructor) { 12875 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 12876 Var->setInvalidDecl(); 12877 return; 12878 } 12879 } 12880 12881 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) { 12882 if (Var->getStorageClass() == SC_Extern) { 12883 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl) 12884 << Var; 12885 Var->setInvalidDecl(); 12886 return; 12887 } 12888 if (RequireCompleteType(Var->getLocation(), Var->getType(), 12889 diag::err_typecheck_decl_incomplete_type)) { 12890 Var->setInvalidDecl(); 12891 return; 12892 } 12893 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) { 12894 if (!RD->hasTrivialDefaultConstructor()) { 12895 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor); 12896 Var->setInvalidDecl(); 12897 return; 12898 } 12899 } 12900 // The declaration is unitialized, no need for further checks. 12901 return; 12902 } 12903 12904 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition(); 12905 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly && 12906 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 12907 checkNonTrivialCUnion(Var->getType(), Var->getLocation(), 12908 NTCUC_DefaultInitializedObject, NTCUK_Init); 12909 12910 12911 switch (DefKind) { 12912 case VarDecl::Definition: 12913 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 12914 break; 12915 12916 // We have an out-of-line definition of a static data member 12917 // that has an in-class initializer, so we type-check this like 12918 // a declaration. 12919 // 12920 LLVM_FALLTHROUGH; 12921 12922 case VarDecl::DeclarationOnly: 12923 // It's only a declaration. 12924 12925 // Block scope. C99 6.7p7: If an identifier for an object is 12926 // declared with no linkage (C99 6.2.2p6), the type for the 12927 // object shall be complete. 12928 if (!Type->isDependentType() && Var->isLocalVarDecl() && 12929 !Var->hasLinkage() && !Var->isInvalidDecl() && 12930 RequireCompleteType(Var->getLocation(), Type, 12931 diag::err_typecheck_decl_incomplete_type)) 12932 Var->setInvalidDecl(); 12933 12934 // Make sure that the type is not abstract. 12935 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12936 RequireNonAbstractType(Var->getLocation(), Type, 12937 diag::err_abstract_type_in_decl, 12938 AbstractVariableType)) 12939 Var->setInvalidDecl(); 12940 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12941 Var->getStorageClass() == SC_PrivateExtern) { 12942 Diag(Var->getLocation(), diag::warn_private_extern); 12943 Diag(Var->getLocation(), diag::note_private_extern); 12944 } 12945 12946 if (Context.getTargetInfo().allowDebugInfoForExternalRef() && 12947 !Var->isInvalidDecl() && !getLangOpts().CPlusPlus) 12948 ExternalDeclarations.push_back(Var); 12949 12950 return; 12951 12952 case VarDecl::TentativeDefinition: 12953 // File scope. C99 6.9.2p2: A declaration of an identifier for an 12954 // object that has file scope without an initializer, and without a 12955 // storage-class specifier or with the storage-class specifier "static", 12956 // constitutes a tentative definition. Note: A tentative definition with 12957 // external linkage is valid (C99 6.2.2p5). 12958 if (!Var->isInvalidDecl()) { 12959 if (const IncompleteArrayType *ArrayT 12960 = Context.getAsIncompleteArrayType(Type)) { 12961 if (RequireCompleteSizedType( 12962 Var->getLocation(), ArrayT->getElementType(), 12963 diag::err_array_incomplete_or_sizeless_type)) 12964 Var->setInvalidDecl(); 12965 } else if (Var->getStorageClass() == SC_Static) { 12966 // C99 6.9.2p3: If the declaration of an identifier for an object is 12967 // a tentative definition and has internal linkage (C99 6.2.2p3), the 12968 // declared type shall not be an incomplete type. 12969 // NOTE: code such as the following 12970 // static struct s; 12971 // struct s { int a; }; 12972 // is accepted by gcc. Hence here we issue a warning instead of 12973 // an error and we do not invalidate the static declaration. 12974 // NOTE: to avoid multiple warnings, only check the first declaration. 12975 if (Var->isFirstDecl()) 12976 RequireCompleteType(Var->getLocation(), Type, 12977 diag::ext_typecheck_decl_incomplete_type); 12978 } 12979 } 12980 12981 // Record the tentative definition; we're done. 12982 if (!Var->isInvalidDecl()) 12983 TentativeDefinitions.push_back(Var); 12984 return; 12985 } 12986 12987 // Provide a specific diagnostic for uninitialized variable 12988 // definitions with incomplete array type. 12989 if (Type->isIncompleteArrayType()) { 12990 Diag(Var->getLocation(), 12991 diag::err_typecheck_incomplete_array_needs_initializer); 12992 Var->setInvalidDecl(); 12993 return; 12994 } 12995 12996 // Provide a specific diagnostic for uninitialized variable 12997 // definitions with reference type. 12998 if (Type->isReferenceType()) { 12999 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 13000 << Var << SourceRange(Var->getLocation(), Var->getLocation()); 13001 Var->setInvalidDecl(); 13002 return; 13003 } 13004 13005 // Do not attempt to type-check the default initializer for a 13006 // variable with dependent type. 13007 if (Type->isDependentType()) 13008 return; 13009 13010 if (Var->isInvalidDecl()) 13011 return; 13012 13013 if (!Var->hasAttr<AliasAttr>()) { 13014 if (RequireCompleteType(Var->getLocation(), 13015 Context.getBaseElementType(Type), 13016 diag::err_typecheck_decl_incomplete_type)) { 13017 Var->setInvalidDecl(); 13018 return; 13019 } 13020 } else { 13021 return; 13022 } 13023 13024 // The variable can not have an abstract class type. 13025 if (RequireNonAbstractType(Var->getLocation(), Type, 13026 diag::err_abstract_type_in_decl, 13027 AbstractVariableType)) { 13028 Var->setInvalidDecl(); 13029 return; 13030 } 13031 13032 // Check for jumps past the implicit initializer. C++0x 13033 // clarifies that this applies to a "variable with automatic 13034 // storage duration", not a "local variable". 13035 // C++11 [stmt.dcl]p3 13036 // A program that jumps from a point where a variable with automatic 13037 // storage duration is not in scope to a point where it is in scope is 13038 // ill-formed unless the variable has scalar type, class type with a 13039 // trivial default constructor and a trivial destructor, a cv-qualified 13040 // version of one of these types, or an array of one of the preceding 13041 // types and is declared without an initializer. 13042 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 13043 if (const RecordType *Record 13044 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 13045 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 13046 // Mark the function (if we're in one) for further checking even if the 13047 // looser rules of C++11 do not require such checks, so that we can 13048 // diagnose incompatibilities with C++98. 13049 if (!CXXRecord->isPOD()) 13050 setFunctionHasBranchProtectedScope(); 13051 } 13052 } 13053 // In OpenCL, we can't initialize objects in the __local address space, 13054 // even implicitly, so don't synthesize an implicit initializer. 13055 if (getLangOpts().OpenCL && 13056 Var->getType().getAddressSpace() == LangAS::opencl_local) 13057 return; 13058 // C++03 [dcl.init]p9: 13059 // If no initializer is specified for an object, and the 13060 // object is of (possibly cv-qualified) non-POD class type (or 13061 // array thereof), the object shall be default-initialized; if 13062 // the object is of const-qualified type, the underlying class 13063 // type shall have a user-declared default 13064 // constructor. Otherwise, if no initializer is specified for 13065 // a non- static object, the object and its subobjects, if 13066 // any, have an indeterminate initial value); if the object 13067 // or any of its subobjects are of const-qualified type, the 13068 // program is ill-formed. 13069 // C++0x [dcl.init]p11: 13070 // If no initializer is specified for an object, the object is 13071 // default-initialized; [...]. 13072 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 13073 InitializationKind Kind 13074 = InitializationKind::CreateDefault(Var->getLocation()); 13075 13076 InitializationSequence InitSeq(*this, Entity, Kind, None); 13077 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 13078 13079 if (Init.get()) { 13080 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 13081 // This is important for template substitution. 13082 Var->setInitStyle(VarDecl::CallInit); 13083 } else if (Init.isInvalid()) { 13084 // If default-init fails, attach a recovery-expr initializer to track 13085 // that initialization was attempted and failed. 13086 auto RecoveryExpr = 13087 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {}); 13088 if (RecoveryExpr.get()) 13089 Var->setInit(RecoveryExpr.get()); 13090 } 13091 13092 CheckCompleteVariableDeclaration(Var); 13093 } 13094 } 13095 13096 void Sema::ActOnCXXForRangeDecl(Decl *D) { 13097 // If there is no declaration, there was an error parsing it. Ignore it. 13098 if (!D) 13099 return; 13100 13101 VarDecl *VD = dyn_cast<VarDecl>(D); 13102 if (!VD) { 13103 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 13104 D->setInvalidDecl(); 13105 return; 13106 } 13107 13108 VD->setCXXForRangeDecl(true); 13109 13110 // for-range-declaration cannot be given a storage class specifier. 13111 int Error = -1; 13112 switch (VD->getStorageClass()) { 13113 case SC_None: 13114 break; 13115 case SC_Extern: 13116 Error = 0; 13117 break; 13118 case SC_Static: 13119 Error = 1; 13120 break; 13121 case SC_PrivateExtern: 13122 Error = 2; 13123 break; 13124 case SC_Auto: 13125 Error = 3; 13126 break; 13127 case SC_Register: 13128 Error = 4; 13129 break; 13130 } 13131 13132 // for-range-declaration cannot be given a storage class specifier con't. 13133 switch (VD->getTSCSpec()) { 13134 case TSCS_thread_local: 13135 Error = 6; 13136 break; 13137 case TSCS___thread: 13138 case TSCS__Thread_local: 13139 case TSCS_unspecified: 13140 break; 13141 } 13142 13143 if (Error != -1) { 13144 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 13145 << VD << Error; 13146 D->setInvalidDecl(); 13147 } 13148 } 13149 13150 StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 13151 IdentifierInfo *Ident, 13152 ParsedAttributes &Attrs) { 13153 // C++1y [stmt.iter]p1: 13154 // A range-based for statement of the form 13155 // for ( for-range-identifier : for-range-initializer ) statement 13156 // is equivalent to 13157 // for ( auto&& for-range-identifier : for-range-initializer ) statement 13158 DeclSpec DS(Attrs.getPool().getFactory()); 13159 13160 const char *PrevSpec; 13161 unsigned DiagID; 13162 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 13163 getPrintingPolicy()); 13164 13165 Declarator D(DS, DeclaratorContext::ForInit); 13166 D.SetIdentifier(Ident, IdentLoc); 13167 D.takeAttributes(Attrs); 13168 13169 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false), 13170 IdentLoc); 13171 Decl *Var = ActOnDeclarator(S, D); 13172 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 13173 FinalizeDeclaration(Var); 13174 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 13175 Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd() 13176 : IdentLoc); 13177 } 13178 13179 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 13180 if (var->isInvalidDecl()) return; 13181 13182 MaybeAddCUDAConstantAttr(var); 13183 13184 if (getLangOpts().OpenCL) { 13185 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 13186 // initialiser 13187 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 13188 !var->hasInit()) { 13189 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 13190 << 1 /*Init*/; 13191 var->setInvalidDecl(); 13192 return; 13193 } 13194 } 13195 13196 // In Objective-C, don't allow jumps past the implicit initialization of a 13197 // local retaining variable. 13198 if (getLangOpts().ObjC && 13199 var->hasLocalStorage()) { 13200 switch (var->getType().getObjCLifetime()) { 13201 case Qualifiers::OCL_None: 13202 case Qualifiers::OCL_ExplicitNone: 13203 case Qualifiers::OCL_Autoreleasing: 13204 break; 13205 13206 case Qualifiers::OCL_Weak: 13207 case Qualifiers::OCL_Strong: 13208 setFunctionHasBranchProtectedScope(); 13209 break; 13210 } 13211 } 13212 13213 if (var->hasLocalStorage() && 13214 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 13215 setFunctionHasBranchProtectedScope(); 13216 13217 // Warn about externally-visible variables being defined without a 13218 // prior declaration. We only want to do this for global 13219 // declarations, but we also specifically need to avoid doing it for 13220 // class members because the linkage of an anonymous class can 13221 // change if it's later given a typedef name. 13222 if (var->isThisDeclarationADefinition() && 13223 var->getDeclContext()->getRedeclContext()->isFileContext() && 13224 var->isExternallyVisible() && var->hasLinkage() && 13225 !var->isInline() && !var->getDescribedVarTemplate() && 13226 !isa<VarTemplatePartialSpecializationDecl>(var) && 13227 !isTemplateInstantiation(var->getTemplateSpecializationKind()) && 13228 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 13229 var->getLocation())) { 13230 // Find a previous declaration that's not a definition. 13231 VarDecl *prev = var->getPreviousDecl(); 13232 while (prev && prev->isThisDeclarationADefinition()) 13233 prev = prev->getPreviousDecl(); 13234 13235 if (!prev) { 13236 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 13237 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 13238 << /* variable */ 0; 13239 } 13240 } 13241 13242 // Cache the result of checking for constant initialization. 13243 Optional<bool> CacheHasConstInit; 13244 const Expr *CacheCulprit = nullptr; 13245 auto checkConstInit = [&]() mutable { 13246 if (!CacheHasConstInit) 13247 CacheHasConstInit = var->getInit()->isConstantInitializer( 13248 Context, var->getType()->isReferenceType(), &CacheCulprit); 13249 return *CacheHasConstInit; 13250 }; 13251 13252 if (var->getTLSKind() == VarDecl::TLS_Static) { 13253 if (var->getType().isDestructedType()) { 13254 // GNU C++98 edits for __thread, [basic.start.term]p3: 13255 // The type of an object with thread storage duration shall not 13256 // have a non-trivial destructor. 13257 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 13258 if (getLangOpts().CPlusPlus11) 13259 Diag(var->getLocation(), diag::note_use_thread_local); 13260 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 13261 if (!checkConstInit()) { 13262 // GNU C++98 edits for __thread, [basic.start.init]p4: 13263 // An object of thread storage duration shall not require dynamic 13264 // initialization. 13265 // FIXME: Need strict checking here. 13266 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 13267 << CacheCulprit->getSourceRange(); 13268 if (getLangOpts().CPlusPlus11) 13269 Diag(var->getLocation(), diag::note_use_thread_local); 13270 } 13271 } 13272 } 13273 13274 13275 if (!var->getType()->isStructureType() && var->hasInit() && 13276 isa<InitListExpr>(var->getInit())) { 13277 const auto *ILE = cast<InitListExpr>(var->getInit()); 13278 unsigned NumInits = ILE->getNumInits(); 13279 if (NumInits > 2) 13280 for (unsigned I = 0; I < NumInits; ++I) { 13281 const auto *Init = ILE->getInit(I); 13282 if (!Init) 13283 break; 13284 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); 13285 if (!SL) 13286 break; 13287 13288 unsigned NumConcat = SL->getNumConcatenated(); 13289 // Diagnose missing comma in string array initialization. 13290 // Do not warn when all the elements in the initializer are concatenated 13291 // together. Do not warn for macros too. 13292 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) { 13293 bool OnlyOneMissingComma = true; 13294 for (unsigned J = I + 1; J < NumInits; ++J) { 13295 const auto *Init = ILE->getInit(J); 13296 if (!Init) 13297 break; 13298 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); 13299 if (!SLJ || SLJ->getNumConcatenated() > 1) { 13300 OnlyOneMissingComma = false; 13301 break; 13302 } 13303 } 13304 13305 if (OnlyOneMissingComma) { 13306 SmallVector<FixItHint, 1> Hints; 13307 for (unsigned i = 0; i < NumConcat - 1; ++i) 13308 Hints.push_back(FixItHint::CreateInsertion( 13309 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ",")); 13310 13311 Diag(SL->getStrTokenLoc(1), 13312 diag::warn_concatenated_literal_array_init) 13313 << Hints; 13314 Diag(SL->getBeginLoc(), 13315 diag::note_concatenated_string_literal_silence); 13316 } 13317 // In any case, stop now. 13318 break; 13319 } 13320 } 13321 } 13322 13323 13324 QualType type = var->getType(); 13325 13326 if (var->hasAttr<BlocksAttr>()) 13327 getCurFunction()->addByrefBlockVar(var); 13328 13329 Expr *Init = var->getInit(); 13330 bool GlobalStorage = var->hasGlobalStorage(); 13331 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 13332 QualType baseType = Context.getBaseElementType(type); 13333 bool HasConstInit = true; 13334 13335 // Check whether the initializer is sufficiently constant. 13336 if (getLangOpts().CPlusPlus && !type->isDependentType() && Init && 13337 !Init->isValueDependent() && 13338 (GlobalStorage || var->isConstexpr() || 13339 var->mightBeUsableInConstantExpressions(Context))) { 13340 // If this variable might have a constant initializer or might be usable in 13341 // constant expressions, check whether or not it actually is now. We can't 13342 // do this lazily, because the result might depend on things that change 13343 // later, such as which constexpr functions happen to be defined. 13344 SmallVector<PartialDiagnosticAt, 8> Notes; 13345 if (!getLangOpts().CPlusPlus11) { 13346 // Prior to C++11, in contexts where a constant initializer is required, 13347 // the set of valid constant initializers is described by syntactic rules 13348 // in [expr.const]p2-6. 13349 // FIXME: Stricter checking for these rules would be useful for constinit / 13350 // -Wglobal-constructors. 13351 HasConstInit = checkConstInit(); 13352 13353 // Compute and cache the constant value, and remember that we have a 13354 // constant initializer. 13355 if (HasConstInit) { 13356 (void)var->checkForConstantInitialization(Notes); 13357 Notes.clear(); 13358 } else if (CacheCulprit) { 13359 Notes.emplace_back(CacheCulprit->getExprLoc(), 13360 PDiag(diag::note_invalid_subexpr_in_const_expr)); 13361 Notes.back().second << CacheCulprit->getSourceRange(); 13362 } 13363 } else { 13364 // Evaluate the initializer to see if it's a constant initializer. 13365 HasConstInit = var->checkForConstantInitialization(Notes); 13366 } 13367 13368 if (HasConstInit) { 13369 // FIXME: Consider replacing the initializer with a ConstantExpr. 13370 } else if (var->isConstexpr()) { 13371 SourceLocation DiagLoc = var->getLocation(); 13372 // If the note doesn't add any useful information other than a source 13373 // location, fold it into the primary diagnostic. 13374 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 13375 diag::note_invalid_subexpr_in_const_expr) { 13376 DiagLoc = Notes[0].first; 13377 Notes.clear(); 13378 } 13379 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 13380 << var << Init->getSourceRange(); 13381 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 13382 Diag(Notes[I].first, Notes[I].second); 13383 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) { 13384 auto *Attr = var->getAttr<ConstInitAttr>(); 13385 Diag(var->getLocation(), diag::err_require_constant_init_failed) 13386 << Init->getSourceRange(); 13387 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here) 13388 << Attr->getRange() << Attr->isConstinit(); 13389 for (auto &it : Notes) 13390 Diag(it.first, it.second); 13391 } else if (IsGlobal && 13392 !getDiagnostics().isIgnored(diag::warn_global_constructor, 13393 var->getLocation())) { 13394 // Warn about globals which don't have a constant initializer. Don't 13395 // warn about globals with a non-trivial destructor because we already 13396 // warned about them. 13397 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 13398 if (!(RD && !RD->hasTrivialDestructor())) { 13399 // checkConstInit() here permits trivial default initialization even in 13400 // C++11 onwards, where such an initializer is not a constant initializer 13401 // but nonetheless doesn't require a global constructor. 13402 if (!checkConstInit()) 13403 Diag(var->getLocation(), diag::warn_global_constructor) 13404 << Init->getSourceRange(); 13405 } 13406 } 13407 } 13408 13409 // Apply section attributes and pragmas to global variables. 13410 if (GlobalStorage && var->isThisDeclarationADefinition() && 13411 !inTemplateInstantiation()) { 13412 PragmaStack<StringLiteral *> *Stack = nullptr; 13413 int SectionFlags = ASTContext::PSF_Read; 13414 if (var->getType().isConstQualified()) { 13415 if (HasConstInit) 13416 Stack = &ConstSegStack; 13417 else { 13418 Stack = &BSSSegStack; 13419 SectionFlags |= ASTContext::PSF_Write; 13420 } 13421 } else if (var->hasInit() && HasConstInit) { 13422 Stack = &DataSegStack; 13423 SectionFlags |= ASTContext::PSF_Write; 13424 } else { 13425 Stack = &BSSSegStack; 13426 SectionFlags |= ASTContext::PSF_Write; 13427 } 13428 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) { 13429 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec) 13430 SectionFlags |= ASTContext::PSF_Implicit; 13431 UnifySection(SA->getName(), SectionFlags, var); 13432 } else if (Stack->CurrentValue) { 13433 SectionFlags |= ASTContext::PSF_Implicit; 13434 auto SectionName = Stack->CurrentValue->getString(); 13435 var->addAttr(SectionAttr::CreateImplicit( 13436 Context, SectionName, Stack->CurrentPragmaLocation, 13437 AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate)); 13438 if (UnifySection(SectionName, SectionFlags, var)) 13439 var->dropAttr<SectionAttr>(); 13440 } 13441 13442 // Apply the init_seg attribute if this has an initializer. If the 13443 // initializer turns out to not be dynamic, we'll end up ignoring this 13444 // attribute. 13445 if (CurInitSeg && var->getInit()) 13446 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 13447 CurInitSegLoc, 13448 AttributeCommonInfo::AS_Pragma)); 13449 } 13450 13451 // All the following checks are C++ only. 13452 if (!getLangOpts().CPlusPlus) { 13453 // If this variable must be emitted, add it as an initializer for the 13454 // current module. 13455 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 13456 Context.addModuleInitializer(ModuleScopes.back().Module, var); 13457 return; 13458 } 13459 13460 // Require the destructor. 13461 if (!type->isDependentType()) 13462 if (const RecordType *recordType = baseType->getAs<RecordType>()) 13463 FinalizeVarWithDestructor(var, recordType); 13464 13465 // If this variable must be emitted, add it as an initializer for the current 13466 // module. 13467 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 13468 Context.addModuleInitializer(ModuleScopes.back().Module, var); 13469 13470 // Build the bindings if this is a structured binding declaration. 13471 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 13472 CheckCompleteDecompositionDeclaration(DD); 13473 } 13474 13475 /// Check if VD needs to be dllexport/dllimport due to being in a 13476 /// dllexport/import function. 13477 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) { 13478 assert(VD->isStaticLocal()); 13479 13480 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 13481 13482 // Find outermost function when VD is in lambda function. 13483 while (FD && !getDLLAttr(FD) && 13484 !FD->hasAttr<DLLExportStaticLocalAttr>() && 13485 !FD->hasAttr<DLLImportStaticLocalAttr>()) { 13486 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod()); 13487 } 13488 13489 if (!FD) 13490 return; 13491 13492 // Static locals inherit dll attributes from their function. 13493 if (Attr *A = getDLLAttr(FD)) { 13494 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 13495 NewAttr->setInherited(true); 13496 VD->addAttr(NewAttr); 13497 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) { 13498 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A); 13499 NewAttr->setInherited(true); 13500 VD->addAttr(NewAttr); 13501 13502 // Export this function to enforce exporting this static variable even 13503 // if it is not used in this compilation unit. 13504 if (!FD->hasAttr<DLLExportAttr>()) 13505 FD->addAttr(NewAttr); 13506 13507 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) { 13508 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A); 13509 NewAttr->setInherited(true); 13510 VD->addAttr(NewAttr); 13511 } 13512 } 13513 13514 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 13515 /// any semantic actions necessary after any initializer has been attached. 13516 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 13517 // Note that we are no longer parsing the initializer for this declaration. 13518 ParsingInitForAutoVars.erase(ThisDecl); 13519 13520 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 13521 if (!VD) 13522 return; 13523 13524 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active 13525 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && 13526 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { 13527 if (PragmaClangBSSSection.Valid) 13528 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit( 13529 Context, PragmaClangBSSSection.SectionName, 13530 PragmaClangBSSSection.PragmaLocation, 13531 AttributeCommonInfo::AS_Pragma)); 13532 if (PragmaClangDataSection.Valid) 13533 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit( 13534 Context, PragmaClangDataSection.SectionName, 13535 PragmaClangDataSection.PragmaLocation, 13536 AttributeCommonInfo::AS_Pragma)); 13537 if (PragmaClangRodataSection.Valid) 13538 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit( 13539 Context, PragmaClangRodataSection.SectionName, 13540 PragmaClangRodataSection.PragmaLocation, 13541 AttributeCommonInfo::AS_Pragma)); 13542 if (PragmaClangRelroSection.Valid) 13543 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit( 13544 Context, PragmaClangRelroSection.SectionName, 13545 PragmaClangRelroSection.PragmaLocation, 13546 AttributeCommonInfo::AS_Pragma)); 13547 } 13548 13549 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 13550 for (auto *BD : DD->bindings()) { 13551 FinalizeDeclaration(BD); 13552 } 13553 } 13554 13555 checkAttributesAfterMerging(*this, *VD); 13556 13557 // Perform TLS alignment check here after attributes attached to the variable 13558 // which may affect the alignment have been processed. Only perform the check 13559 // if the target has a maximum TLS alignment (zero means no constraints). 13560 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 13561 // Protect the check so that it's not performed on dependent types and 13562 // dependent alignments (we can't determine the alignment in that case). 13563 if (VD->getTLSKind() && !VD->hasDependentAlignment()) { 13564 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 13565 if (Context.getDeclAlign(VD) > MaxAlignChars) { 13566 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 13567 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 13568 << (unsigned)MaxAlignChars.getQuantity(); 13569 } 13570 } 13571 } 13572 13573 if (VD->isStaticLocal()) 13574 CheckStaticLocalForDllExport(VD); 13575 13576 // Perform check for initializers of device-side global variables. 13577 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 13578 // 7.5). We must also apply the same checks to all __shared__ 13579 // variables whether they are local or not. CUDA also allows 13580 // constant initializers for __constant__ and __device__ variables. 13581 if (getLangOpts().CUDA) 13582 checkAllowedCUDAInitializer(VD); 13583 13584 // Grab the dllimport or dllexport attribute off of the VarDecl. 13585 const InheritableAttr *DLLAttr = getDLLAttr(VD); 13586 13587 // Imported static data members cannot be defined out-of-line. 13588 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 13589 if (VD->isStaticDataMember() && VD->isOutOfLine() && 13590 VD->isThisDeclarationADefinition()) { 13591 // We allow definitions of dllimport class template static data members 13592 // with a warning. 13593 CXXRecordDecl *Context = 13594 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 13595 bool IsClassTemplateMember = 13596 isa<ClassTemplatePartialSpecializationDecl>(Context) || 13597 Context->getDescribedClassTemplate(); 13598 13599 Diag(VD->getLocation(), 13600 IsClassTemplateMember 13601 ? diag::warn_attribute_dllimport_static_field_definition 13602 : diag::err_attribute_dllimport_static_field_definition); 13603 Diag(IA->getLocation(), diag::note_attribute); 13604 if (!IsClassTemplateMember) 13605 VD->setInvalidDecl(); 13606 } 13607 } 13608 13609 // dllimport/dllexport variables cannot be thread local, their TLS index 13610 // isn't exported with the variable. 13611 if (DLLAttr && VD->getTLSKind()) { 13612 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 13613 if (F && getDLLAttr(F)) { 13614 assert(VD->isStaticLocal()); 13615 // But if this is a static local in a dlimport/dllexport function, the 13616 // function will never be inlined, which means the var would never be 13617 // imported, so having it marked import/export is safe. 13618 } else { 13619 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 13620 << DLLAttr; 13621 VD->setInvalidDecl(); 13622 } 13623 } 13624 13625 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 13626 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 13627 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition) 13628 << Attr; 13629 VD->dropAttr<UsedAttr>(); 13630 } 13631 } 13632 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) { 13633 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 13634 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition) 13635 << Attr; 13636 VD->dropAttr<RetainAttr>(); 13637 } 13638 } 13639 13640 const DeclContext *DC = VD->getDeclContext(); 13641 // If there's a #pragma GCC visibility in scope, and this isn't a class 13642 // member, set the visibility of this variable. 13643 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 13644 AddPushedVisibilityAttribute(VD); 13645 13646 // FIXME: Warn on unused var template partial specializations. 13647 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 13648 MarkUnusedFileScopedDecl(VD); 13649 13650 // Now we have parsed the initializer and can update the table of magic 13651 // tag values. 13652 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 13653 !VD->getType()->isIntegralOrEnumerationType()) 13654 return; 13655 13656 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 13657 const Expr *MagicValueExpr = VD->getInit(); 13658 if (!MagicValueExpr) { 13659 continue; 13660 } 13661 Optional<llvm::APSInt> MagicValueInt; 13662 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) { 13663 Diag(I->getRange().getBegin(), 13664 diag::err_type_tag_for_datatype_not_ice) 13665 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13666 continue; 13667 } 13668 if (MagicValueInt->getActiveBits() > 64) { 13669 Diag(I->getRange().getBegin(), 13670 diag::err_type_tag_for_datatype_too_large) 13671 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13672 continue; 13673 } 13674 uint64_t MagicValue = MagicValueInt->getZExtValue(); 13675 RegisterTypeTagForDatatype(I->getArgumentKind(), 13676 MagicValue, 13677 I->getMatchingCType(), 13678 I->getLayoutCompatible(), 13679 I->getMustBeNull()); 13680 } 13681 } 13682 13683 static bool hasDeducedAuto(DeclaratorDecl *DD) { 13684 auto *VD = dyn_cast<VarDecl>(DD); 13685 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 13686 } 13687 13688 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 13689 ArrayRef<Decl *> Group) { 13690 SmallVector<Decl*, 8> Decls; 13691 13692 if (DS.isTypeSpecOwned()) 13693 Decls.push_back(DS.getRepAsDecl()); 13694 13695 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 13696 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 13697 bool DiagnosedMultipleDecomps = false; 13698 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 13699 bool DiagnosedNonDeducedAuto = false; 13700 13701 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13702 if (Decl *D = Group[i]) { 13703 // For declarators, there are some additional syntactic-ish checks we need 13704 // to perform. 13705 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 13706 if (!FirstDeclaratorInGroup) 13707 FirstDeclaratorInGroup = DD; 13708 if (!FirstDecompDeclaratorInGroup) 13709 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 13710 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 13711 !hasDeducedAuto(DD)) 13712 FirstNonDeducedAutoInGroup = DD; 13713 13714 if (FirstDeclaratorInGroup != DD) { 13715 // A decomposition declaration cannot be combined with any other 13716 // declaration in the same group. 13717 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 13718 Diag(FirstDecompDeclaratorInGroup->getLocation(), 13719 diag::err_decomp_decl_not_alone) 13720 << FirstDeclaratorInGroup->getSourceRange() 13721 << DD->getSourceRange(); 13722 DiagnosedMultipleDecomps = true; 13723 } 13724 13725 // A declarator that uses 'auto' in any way other than to declare a 13726 // variable with a deduced type cannot be combined with any other 13727 // declarator in the same group. 13728 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 13729 Diag(FirstNonDeducedAutoInGroup->getLocation(), 13730 diag::err_auto_non_deduced_not_alone) 13731 << FirstNonDeducedAutoInGroup->getType() 13732 ->hasAutoForTrailingReturnType() 13733 << FirstDeclaratorInGroup->getSourceRange() 13734 << DD->getSourceRange(); 13735 DiagnosedNonDeducedAuto = true; 13736 } 13737 } 13738 } 13739 13740 Decls.push_back(D); 13741 } 13742 } 13743 13744 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 13745 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 13746 handleTagNumbering(Tag, S); 13747 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 13748 getLangOpts().CPlusPlus) 13749 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 13750 } 13751 } 13752 13753 return BuildDeclaratorGroup(Decls); 13754 } 13755 13756 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 13757 /// group, performing any necessary semantic checking. 13758 Sema::DeclGroupPtrTy 13759 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 13760 // C++14 [dcl.spec.auto]p7: (DR1347) 13761 // If the type that replaces the placeholder type is not the same in each 13762 // deduction, the program is ill-formed. 13763 if (Group.size() > 1) { 13764 QualType Deduced; 13765 VarDecl *DeducedDecl = nullptr; 13766 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13767 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 13768 if (!D || D->isInvalidDecl()) 13769 break; 13770 DeducedType *DT = D->getType()->getContainedDeducedType(); 13771 if (!DT || DT->getDeducedType().isNull()) 13772 continue; 13773 if (Deduced.isNull()) { 13774 Deduced = DT->getDeducedType(); 13775 DeducedDecl = D; 13776 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 13777 auto *AT = dyn_cast<AutoType>(DT); 13778 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 13779 diag::err_auto_different_deductions) 13780 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced 13781 << DeducedDecl->getDeclName() << DT->getDeducedType() 13782 << D->getDeclName(); 13783 if (DeducedDecl->hasInit()) 13784 Dia << DeducedDecl->getInit()->getSourceRange(); 13785 if (D->getInit()) 13786 Dia << D->getInit()->getSourceRange(); 13787 D->setInvalidDecl(); 13788 break; 13789 } 13790 } 13791 } 13792 13793 ActOnDocumentableDecls(Group); 13794 13795 return DeclGroupPtrTy::make( 13796 DeclGroupRef::Create(Context, Group.data(), Group.size())); 13797 } 13798 13799 void Sema::ActOnDocumentableDecl(Decl *D) { 13800 ActOnDocumentableDecls(D); 13801 } 13802 13803 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 13804 // Don't parse the comment if Doxygen diagnostics are ignored. 13805 if (Group.empty() || !Group[0]) 13806 return; 13807 13808 if (Diags.isIgnored(diag::warn_doc_param_not_found, 13809 Group[0]->getLocation()) && 13810 Diags.isIgnored(diag::warn_unknown_comment_command_name, 13811 Group[0]->getLocation())) 13812 return; 13813 13814 if (Group.size() >= 2) { 13815 // This is a decl group. Normally it will contain only declarations 13816 // produced from declarator list. But in case we have any definitions or 13817 // additional declaration references: 13818 // 'typedef struct S {} S;' 13819 // 'typedef struct S *S;' 13820 // 'struct S *pS;' 13821 // FinalizeDeclaratorGroup adds these as separate declarations. 13822 Decl *MaybeTagDecl = Group[0]; 13823 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 13824 Group = Group.slice(1); 13825 } 13826 } 13827 13828 // FIMXE: We assume every Decl in the group is in the same file. 13829 // This is false when preprocessor constructs the group from decls in 13830 // different files (e. g. macros or #include). 13831 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor()); 13832 } 13833 13834 /// Common checks for a parameter-declaration that should apply to both function 13835 /// parameters and non-type template parameters. 13836 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) { 13837 // Check that there are no default arguments inside the type of this 13838 // parameter. 13839 if (getLangOpts().CPlusPlus) 13840 CheckExtraCXXDefaultArguments(D); 13841 13842 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 13843 if (D.getCXXScopeSpec().isSet()) { 13844 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 13845 << D.getCXXScopeSpec().getRange(); 13846 } 13847 13848 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a 13849 // simple identifier except [...irrelevant cases...]. 13850 switch (D.getName().getKind()) { 13851 case UnqualifiedIdKind::IK_Identifier: 13852 break; 13853 13854 case UnqualifiedIdKind::IK_OperatorFunctionId: 13855 case UnqualifiedIdKind::IK_ConversionFunctionId: 13856 case UnqualifiedIdKind::IK_LiteralOperatorId: 13857 case UnqualifiedIdKind::IK_ConstructorName: 13858 case UnqualifiedIdKind::IK_DestructorName: 13859 case UnqualifiedIdKind::IK_ImplicitSelfParam: 13860 case UnqualifiedIdKind::IK_DeductionGuideName: 13861 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 13862 << GetNameForDeclarator(D).getName(); 13863 break; 13864 13865 case UnqualifiedIdKind::IK_TemplateId: 13866 case UnqualifiedIdKind::IK_ConstructorTemplateId: 13867 // GetNameForDeclarator would not produce a useful name in this case. 13868 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id); 13869 break; 13870 } 13871 } 13872 13873 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 13874 /// to introduce parameters into function prototype scope. 13875 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 13876 const DeclSpec &DS = D.getDeclSpec(); 13877 13878 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 13879 13880 // C++03 [dcl.stc]p2 also permits 'auto'. 13881 StorageClass SC = SC_None; 13882 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 13883 SC = SC_Register; 13884 // In C++11, the 'register' storage class specifier is deprecated. 13885 // In C++17, it is not allowed, but we tolerate it as an extension. 13886 if (getLangOpts().CPlusPlus11) { 13887 Diag(DS.getStorageClassSpecLoc(), 13888 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 13889 : diag::warn_deprecated_register) 13890 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 13891 } 13892 } else if (getLangOpts().CPlusPlus && 13893 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 13894 SC = SC_Auto; 13895 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 13896 Diag(DS.getStorageClassSpecLoc(), 13897 diag::err_invalid_storage_class_in_func_decl); 13898 D.getMutableDeclSpec().ClearStorageClassSpecs(); 13899 } 13900 13901 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 13902 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 13903 << DeclSpec::getSpecifierName(TSCS); 13904 if (DS.isInlineSpecified()) 13905 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 13906 << getLangOpts().CPlusPlus17; 13907 if (DS.hasConstexprSpecifier()) 13908 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 13909 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 13910 13911 DiagnoseFunctionSpecifiers(DS); 13912 13913 CheckFunctionOrTemplateParamDeclarator(S, D); 13914 13915 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13916 QualType parmDeclType = TInfo->getType(); 13917 13918 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 13919 IdentifierInfo *II = D.getIdentifier(); 13920 if (II) { 13921 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 13922 ForVisibleRedeclaration); 13923 LookupName(R, S); 13924 if (R.isSingleResult()) { 13925 NamedDecl *PrevDecl = R.getFoundDecl(); 13926 if (PrevDecl->isTemplateParameter()) { 13927 // Maybe we will complain about the shadowed template parameter. 13928 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13929 // Just pretend that we didn't see the previous declaration. 13930 PrevDecl = nullptr; 13931 } else if (S->isDeclScope(PrevDecl)) { 13932 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 13933 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 13934 13935 // Recover by removing the name 13936 II = nullptr; 13937 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 13938 D.setInvalidType(true); 13939 } 13940 } 13941 } 13942 13943 // Temporarily put parameter variables in the translation unit, not 13944 // the enclosing context. This prevents them from accidentally 13945 // looking like class members in C++. 13946 ParmVarDecl *New = 13947 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(), 13948 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC); 13949 13950 if (D.isInvalidType()) 13951 New->setInvalidDecl(); 13952 13953 assert(S->isFunctionPrototypeScope()); 13954 assert(S->getFunctionPrototypeDepth() >= 1); 13955 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 13956 S->getNextFunctionPrototypeIndex()); 13957 13958 // Add the parameter declaration into this scope. 13959 S->AddDecl(New); 13960 if (II) 13961 IdResolver.AddDecl(New); 13962 13963 ProcessDeclAttributes(S, New, D); 13964 13965 if (D.getDeclSpec().isModulePrivateSpecified()) 13966 Diag(New->getLocation(), diag::err_module_private_local) 13967 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 13968 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 13969 13970 if (New->hasAttr<BlocksAttr>()) { 13971 Diag(New->getLocation(), diag::err_block_on_nonlocal); 13972 } 13973 13974 if (getLangOpts().OpenCL) 13975 deduceOpenCLAddressSpace(New); 13976 13977 return New; 13978 } 13979 13980 /// Synthesizes a variable for a parameter arising from a 13981 /// typedef. 13982 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 13983 SourceLocation Loc, 13984 QualType T) { 13985 /* FIXME: setting StartLoc == Loc. 13986 Would it be worth to modify callers so as to provide proper source 13987 location for the unnamed parameters, embedding the parameter's type? */ 13988 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 13989 T, Context.getTrivialTypeSourceInfo(T, Loc), 13990 SC_None, nullptr); 13991 Param->setImplicit(); 13992 return Param; 13993 } 13994 13995 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 13996 // Don't diagnose unused-parameter errors in template instantiations; we 13997 // will already have done so in the template itself. 13998 if (inTemplateInstantiation()) 13999 return; 14000 14001 for (const ParmVarDecl *Parameter : Parameters) { 14002 if (!Parameter->isReferenced() && Parameter->getDeclName() && 14003 !Parameter->hasAttr<UnusedAttr>()) { 14004 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 14005 << Parameter->getDeclName(); 14006 } 14007 } 14008 } 14009 14010 void Sema::DiagnoseSizeOfParametersAndReturnValue( 14011 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 14012 if (LangOpts.NumLargeByValueCopy == 0) // No check. 14013 return; 14014 14015 // Warn if the return value is pass-by-value and larger than the specified 14016 // threshold. 14017 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 14018 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 14019 if (Size > LangOpts.NumLargeByValueCopy) 14020 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size; 14021 } 14022 14023 // Warn if any parameter is pass-by-value and larger than the specified 14024 // threshold. 14025 for (const ParmVarDecl *Parameter : Parameters) { 14026 QualType T = Parameter->getType(); 14027 if (T->isDependentType() || !T.isPODType(Context)) 14028 continue; 14029 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 14030 if (Size > LangOpts.NumLargeByValueCopy) 14031 Diag(Parameter->getLocation(), diag::warn_parameter_size) 14032 << Parameter << Size; 14033 } 14034 } 14035 14036 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 14037 SourceLocation NameLoc, IdentifierInfo *Name, 14038 QualType T, TypeSourceInfo *TSInfo, 14039 StorageClass SC) { 14040 // In ARC, infer a lifetime qualifier for appropriate parameter types. 14041 if (getLangOpts().ObjCAutoRefCount && 14042 T.getObjCLifetime() == Qualifiers::OCL_None && 14043 T->isObjCLifetimeType()) { 14044 14045 Qualifiers::ObjCLifetime lifetime; 14046 14047 // Special cases for arrays: 14048 // - if it's const, use __unsafe_unretained 14049 // - otherwise, it's an error 14050 if (T->isArrayType()) { 14051 if (!T.isConstQualified()) { 14052 if (DelayedDiagnostics.shouldDelayDiagnostics()) 14053 DelayedDiagnostics.add( 14054 sema::DelayedDiagnostic::makeForbiddenType( 14055 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 14056 else 14057 Diag(NameLoc, diag::err_arc_array_param_no_ownership) 14058 << TSInfo->getTypeLoc().getSourceRange(); 14059 } 14060 lifetime = Qualifiers::OCL_ExplicitNone; 14061 } else { 14062 lifetime = T->getObjCARCImplicitLifetime(); 14063 } 14064 T = Context.getLifetimeQualifiedType(T, lifetime); 14065 } 14066 14067 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 14068 Context.getAdjustedParameterType(T), 14069 TSInfo, SC, nullptr); 14070 14071 // Make a note if we created a new pack in the scope of a lambda, so that 14072 // we know that references to that pack must also be expanded within the 14073 // lambda scope. 14074 if (New->isParameterPack()) 14075 if (auto *LSI = getEnclosingLambda()) 14076 LSI->LocalPacks.push_back(New); 14077 14078 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() || 14079 New->getType().hasNonTrivialToPrimitiveCopyCUnion()) 14080 checkNonTrivialCUnion(New->getType(), New->getLocation(), 14081 NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy); 14082 14083 // Parameters can not be abstract class types. 14084 // For record types, this is done by the AbstractClassUsageDiagnoser once 14085 // the class has been completely parsed. 14086 if (!CurContext->isRecord() && 14087 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 14088 AbstractParamType)) 14089 New->setInvalidDecl(); 14090 14091 // Parameter declarators cannot be interface types. All ObjC objects are 14092 // passed by reference. 14093 if (T->isObjCObjectType()) { 14094 SourceLocation TypeEndLoc = 14095 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc()); 14096 Diag(NameLoc, 14097 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 14098 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 14099 T = Context.getObjCObjectPointerType(T); 14100 New->setType(T); 14101 } 14102 14103 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 14104 // duration shall not be qualified by an address-space qualifier." 14105 // Since all parameters have automatic store duration, they can not have 14106 // an address space. 14107 if (T.getAddressSpace() != LangAS::Default && 14108 // OpenCL allows function arguments declared to be an array of a type 14109 // to be qualified with an address space. 14110 !(getLangOpts().OpenCL && 14111 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) { 14112 Diag(NameLoc, diag::err_arg_with_address_space); 14113 New->setInvalidDecl(); 14114 } 14115 14116 // PPC MMA non-pointer types are not allowed as function argument types. 14117 if (Context.getTargetInfo().getTriple().isPPC64() && 14118 CheckPPCMMAType(New->getOriginalType(), New->getLocation())) { 14119 New->setInvalidDecl(); 14120 } 14121 14122 return New; 14123 } 14124 14125 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 14126 SourceLocation LocAfterDecls) { 14127 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 14128 14129 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 14130 // for a K&R function. 14131 if (!FTI.hasPrototype) { 14132 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 14133 --i; 14134 if (FTI.Params[i].Param == nullptr) { 14135 SmallString<256> Code; 14136 llvm::raw_svector_ostream(Code) 14137 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 14138 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 14139 << FTI.Params[i].Ident 14140 << FixItHint::CreateInsertion(LocAfterDecls, Code); 14141 14142 // Implicitly declare the argument as type 'int' for lack of a better 14143 // type. 14144 AttributeFactory attrs; 14145 DeclSpec DS(attrs); 14146 const char* PrevSpec; // unused 14147 unsigned DiagID; // unused 14148 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 14149 DiagID, Context.getPrintingPolicy()); 14150 // Use the identifier location for the type source range. 14151 DS.SetRangeStart(FTI.Params[i].IdentLoc); 14152 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 14153 Declarator ParamD(DS, DeclaratorContext::KNRTypeList); 14154 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 14155 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 14156 } 14157 } 14158 } 14159 } 14160 14161 Decl * 14162 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 14163 MultiTemplateParamsArg TemplateParameterLists, 14164 SkipBodyInfo *SkipBody) { 14165 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 14166 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 14167 Scope *ParentScope = FnBodyScope->getParent(); 14168 14169 // Check if we are in an `omp begin/end declare variant` scope. If we are, and 14170 // we define a non-templated function definition, we will create a declaration 14171 // instead (=BaseFD), and emit the definition with a mangled name afterwards. 14172 // The base function declaration will have the equivalent of an `omp declare 14173 // variant` annotation which specifies the mangled definition as a 14174 // specialization function under the OpenMP context defined as part of the 14175 // `omp begin declare variant`. 14176 SmallVector<FunctionDecl *, 4> Bases; 14177 if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope()) 14178 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( 14179 ParentScope, D, TemplateParameterLists, Bases); 14180 14181 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition); 14182 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 14183 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 14184 14185 if (!Bases.empty()) 14186 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases); 14187 14188 return Dcl; 14189 } 14190 14191 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 14192 Consumer.HandleInlineFunctionDefinition(D); 14193 } 14194 14195 static bool 14196 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 14197 const FunctionDecl *&PossiblePrototype) { 14198 // Don't warn about invalid declarations. 14199 if (FD->isInvalidDecl()) 14200 return false; 14201 14202 // Or declarations that aren't global. 14203 if (!FD->isGlobal()) 14204 return false; 14205 14206 // Don't warn about C++ member functions. 14207 if (isa<CXXMethodDecl>(FD)) 14208 return false; 14209 14210 // Don't warn about 'main'. 14211 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext())) 14212 if (IdentifierInfo *II = FD->getIdentifier()) 14213 if (II->isStr("main") || II->isStr("efi_main")) 14214 return false; 14215 14216 // Don't warn about inline functions. 14217 if (FD->isInlined()) 14218 return false; 14219 14220 // Don't warn about function templates. 14221 if (FD->getDescribedFunctionTemplate()) 14222 return false; 14223 14224 // Don't warn about function template specializations. 14225 if (FD->isFunctionTemplateSpecialization()) 14226 return false; 14227 14228 // Don't warn for OpenCL kernels. 14229 if (FD->hasAttr<OpenCLKernelAttr>()) 14230 return false; 14231 14232 // Don't warn on explicitly deleted functions. 14233 if (FD->isDeleted()) 14234 return false; 14235 14236 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 14237 Prev; Prev = Prev->getPreviousDecl()) { 14238 // Ignore any declarations that occur in function or method 14239 // scope, because they aren't visible from the header. 14240 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 14241 continue; 14242 14243 PossiblePrototype = Prev; 14244 return Prev->getType()->isFunctionNoProtoType(); 14245 } 14246 14247 return true; 14248 } 14249 14250 void 14251 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 14252 const FunctionDecl *EffectiveDefinition, 14253 SkipBodyInfo *SkipBody) { 14254 const FunctionDecl *Definition = EffectiveDefinition; 14255 if (!Definition && 14256 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true)) 14257 return; 14258 14259 if (Definition->getFriendObjectKind() != Decl::FOK_None) { 14260 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) { 14261 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { 14262 // A merged copy of the same function, instantiated as a member of 14263 // the same class, is OK. 14264 if (declaresSameEntity(OrigFD, OrigDef) && 14265 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()), 14266 cast<Decl>(FD->getLexicalDeclContext()))) 14267 return; 14268 } 14269 } 14270 } 14271 14272 if (canRedefineFunction(Definition, getLangOpts())) 14273 return; 14274 14275 // Don't emit an error when this is redefinition of a typo-corrected 14276 // definition. 14277 if (TypoCorrectedFunctionDefinitions.count(Definition)) 14278 return; 14279 14280 // If we don't have a visible definition of the function, and it's inline or 14281 // a template, skip the new definition. 14282 if (SkipBody && !hasVisibleDefinition(Definition) && 14283 (Definition->getFormalLinkage() == InternalLinkage || 14284 Definition->isInlined() || 14285 Definition->getDescribedFunctionTemplate() || 14286 Definition->getNumTemplateParameterLists())) { 14287 SkipBody->ShouldSkip = true; 14288 SkipBody->Previous = const_cast<FunctionDecl*>(Definition); 14289 if (auto *TD = Definition->getDescribedFunctionTemplate()) 14290 makeMergedDefinitionVisible(TD); 14291 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 14292 return; 14293 } 14294 14295 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 14296 Definition->getStorageClass() == SC_Extern) 14297 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 14298 << FD << getLangOpts().CPlusPlus; 14299 else 14300 Diag(FD->getLocation(), diag::err_redefinition) << FD; 14301 14302 Diag(Definition->getLocation(), diag::note_previous_definition); 14303 FD->setInvalidDecl(); 14304 } 14305 14306 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 14307 Sema &S) { 14308 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 14309 14310 LambdaScopeInfo *LSI = S.PushLambdaScope(); 14311 LSI->CallOperator = CallOperator; 14312 LSI->Lambda = LambdaClass; 14313 LSI->ReturnType = CallOperator->getReturnType(); 14314 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 14315 14316 if (LCD == LCD_None) 14317 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 14318 else if (LCD == LCD_ByCopy) 14319 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 14320 else if (LCD == LCD_ByRef) 14321 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 14322 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 14323 14324 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 14325 LSI->Mutable = !CallOperator->isConst(); 14326 14327 // Add the captures to the LSI so they can be noted as already 14328 // captured within tryCaptureVar. 14329 auto I = LambdaClass->field_begin(); 14330 for (const auto &C : LambdaClass->captures()) { 14331 if (C.capturesVariable()) { 14332 VarDecl *VD = C.getCapturedVar(); 14333 if (VD->isInitCapture()) 14334 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 14335 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 14336 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 14337 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 14338 /*EllipsisLoc*/C.isPackExpansion() 14339 ? C.getEllipsisLoc() : SourceLocation(), 14340 I->getType(), /*Invalid*/false); 14341 14342 } else if (C.capturesThis()) { 14343 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(), 14344 C.getCaptureKind() == LCK_StarThis); 14345 } else { 14346 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(), 14347 I->getType()); 14348 } 14349 ++I; 14350 } 14351 } 14352 14353 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 14354 SkipBodyInfo *SkipBody) { 14355 if (!D) { 14356 // Parsing the function declaration failed in some way. Push on a fake scope 14357 // anyway so we can try to parse the function body. 14358 PushFunctionScope(); 14359 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 14360 return D; 14361 } 14362 14363 FunctionDecl *FD = nullptr; 14364 14365 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 14366 FD = FunTmpl->getTemplatedDecl(); 14367 else 14368 FD = cast<FunctionDecl>(D); 14369 14370 // Do not push if it is a lambda because one is already pushed when building 14371 // the lambda in ActOnStartOfLambdaDefinition(). 14372 if (!isLambdaCallOperator(FD)) 14373 PushExpressionEvaluationContext( 14374 FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated 14375 : ExprEvalContexts.back().Context); 14376 14377 // Check for defining attributes before the check for redefinition. 14378 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 14379 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 14380 FD->dropAttr<AliasAttr>(); 14381 FD->setInvalidDecl(); 14382 } 14383 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 14384 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 14385 FD->dropAttr<IFuncAttr>(); 14386 FD->setInvalidDecl(); 14387 } 14388 14389 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { 14390 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 14391 Ctor->isDefaultConstructor() && 14392 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 14393 // If this is an MS ABI dllexport default constructor, instantiate any 14394 // default arguments. 14395 InstantiateDefaultCtorDefaultArgs(Ctor); 14396 } 14397 } 14398 14399 // See if this is a redefinition. If 'will have body' (or similar) is already 14400 // set, then these checks were already performed when it was set. 14401 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() && 14402 !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) { 14403 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 14404 14405 // If we're skipping the body, we're done. Don't enter the scope. 14406 if (SkipBody && SkipBody->ShouldSkip) 14407 return D; 14408 } 14409 14410 // Mark this function as "will have a body eventually". This lets users to 14411 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 14412 // this function. 14413 FD->setWillHaveBody(); 14414 14415 // If we are instantiating a generic lambda call operator, push 14416 // a LambdaScopeInfo onto the function stack. But use the information 14417 // that's already been calculated (ActOnLambdaExpr) to prime the current 14418 // LambdaScopeInfo. 14419 // When the template operator is being specialized, the LambdaScopeInfo, 14420 // has to be properly restored so that tryCaptureVariable doesn't try 14421 // and capture any new variables. In addition when calculating potential 14422 // captures during transformation of nested lambdas, it is necessary to 14423 // have the LSI properly restored. 14424 if (isGenericLambdaCallOperatorSpecialization(FD)) { 14425 assert(inTemplateInstantiation() && 14426 "There should be an active template instantiation on the stack " 14427 "when instantiating a generic lambda!"); 14428 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 14429 } else { 14430 // Enter a new function scope 14431 PushFunctionScope(); 14432 } 14433 14434 // Builtin functions cannot be defined. 14435 if (unsigned BuiltinID = FD->getBuiltinID()) { 14436 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 14437 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 14438 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 14439 FD->setInvalidDecl(); 14440 } 14441 } 14442 14443 // The return type of a function definition must be complete 14444 // (C99 6.9.1p3, C++ [dcl.fct]p6). 14445 QualType ResultType = FD->getReturnType(); 14446 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 14447 !FD->isInvalidDecl() && 14448 RequireCompleteType(FD->getLocation(), ResultType, 14449 diag::err_func_def_incomplete_result)) 14450 FD->setInvalidDecl(); 14451 14452 if (FnBodyScope) 14453 PushDeclContext(FnBodyScope, FD); 14454 14455 // Check the validity of our function parameters 14456 CheckParmsForFunctionDef(FD->parameters(), 14457 /*CheckParameterNames=*/true); 14458 14459 // Add non-parameter declarations already in the function to the current 14460 // scope. 14461 if (FnBodyScope) { 14462 for (Decl *NPD : FD->decls()) { 14463 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 14464 if (!NonParmDecl) 14465 continue; 14466 assert(!isa<ParmVarDecl>(NonParmDecl) && 14467 "parameters should not be in newly created FD yet"); 14468 14469 // If the decl has a name, make it accessible in the current scope. 14470 if (NonParmDecl->getDeclName()) 14471 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 14472 14473 // Similarly, dive into enums and fish their constants out, making them 14474 // accessible in this scope. 14475 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 14476 for (auto *EI : ED->enumerators()) 14477 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 14478 } 14479 } 14480 } 14481 14482 // Introduce our parameters into the function scope 14483 for (auto Param : FD->parameters()) { 14484 Param->setOwningFunction(FD); 14485 14486 // If this has an identifier, add it to the scope stack. 14487 if (Param->getIdentifier() && FnBodyScope) { 14488 CheckShadow(FnBodyScope, Param); 14489 14490 PushOnScopeChains(Param, FnBodyScope); 14491 } 14492 } 14493 14494 // Ensure that the function's exception specification is instantiated. 14495 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 14496 ResolveExceptionSpec(D->getLocation(), FPT); 14497 14498 // dllimport cannot be applied to non-inline function definitions. 14499 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 14500 !FD->isTemplateInstantiation()) { 14501 assert(!FD->hasAttr<DLLExportAttr>()); 14502 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 14503 FD->setInvalidDecl(); 14504 return D; 14505 } 14506 // We want to attach documentation to original Decl (which might be 14507 // a function template). 14508 ActOnDocumentableDecl(D); 14509 if (getCurLexicalContext()->isObjCContainer() && 14510 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 14511 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 14512 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 14513 14514 return D; 14515 } 14516 14517 /// Given the set of return statements within a function body, 14518 /// compute the variables that are subject to the named return value 14519 /// optimization. 14520 /// 14521 /// Each of the variables that is subject to the named return value 14522 /// optimization will be marked as NRVO variables in the AST, and any 14523 /// return statement that has a marked NRVO variable as its NRVO candidate can 14524 /// use the named return value optimization. 14525 /// 14526 /// This function applies a very simplistic algorithm for NRVO: if every return 14527 /// statement in the scope of a variable has the same NRVO candidate, that 14528 /// candidate is an NRVO variable. 14529 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 14530 ReturnStmt **Returns = Scope->Returns.data(); 14531 14532 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 14533 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 14534 if (!NRVOCandidate->isNRVOVariable()) 14535 Returns[I]->setNRVOCandidate(nullptr); 14536 } 14537 } 14538 } 14539 14540 bool Sema::canDelayFunctionBody(const Declarator &D) { 14541 // We can't delay parsing the body of a constexpr function template (yet). 14542 if (D.getDeclSpec().hasConstexprSpecifier()) 14543 return false; 14544 14545 // We can't delay parsing the body of a function template with a deduced 14546 // return type (yet). 14547 if (D.getDeclSpec().hasAutoTypeSpec()) { 14548 // If the placeholder introduces a non-deduced trailing return type, 14549 // we can still delay parsing it. 14550 if (D.getNumTypeObjects()) { 14551 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 14552 if (Outer.Kind == DeclaratorChunk::Function && 14553 Outer.Fun.hasTrailingReturnType()) { 14554 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 14555 return Ty.isNull() || !Ty->isUndeducedType(); 14556 } 14557 } 14558 return false; 14559 } 14560 14561 return true; 14562 } 14563 14564 bool Sema::canSkipFunctionBody(Decl *D) { 14565 // We cannot skip the body of a function (or function template) which is 14566 // constexpr, since we may need to evaluate its body in order to parse the 14567 // rest of the file. 14568 // We cannot skip the body of a function with an undeduced return type, 14569 // because any callers of that function need to know the type. 14570 if (const FunctionDecl *FD = D->getAsFunction()) { 14571 if (FD->isConstexpr()) 14572 return false; 14573 // We can't simply call Type::isUndeducedType here, because inside template 14574 // auto can be deduced to a dependent type, which is not considered 14575 // "undeduced". 14576 if (FD->getReturnType()->getContainedDeducedType()) 14577 return false; 14578 } 14579 return Consumer.shouldSkipFunctionBody(D); 14580 } 14581 14582 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 14583 if (!Decl) 14584 return nullptr; 14585 if (FunctionDecl *FD = Decl->getAsFunction()) 14586 FD->setHasSkippedBody(); 14587 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) 14588 MD->setHasSkippedBody(); 14589 return Decl; 14590 } 14591 14592 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 14593 return ActOnFinishFunctionBody(D, BodyArg, false); 14594 } 14595 14596 /// RAII object that pops an ExpressionEvaluationContext when exiting a function 14597 /// body. 14598 class ExitFunctionBodyRAII { 14599 public: 14600 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {} 14601 ~ExitFunctionBodyRAII() { 14602 if (!IsLambda) 14603 S.PopExpressionEvaluationContext(); 14604 } 14605 14606 private: 14607 Sema &S; 14608 bool IsLambda = false; 14609 }; 14610 14611 static void diagnoseImplicitlyRetainedSelf(Sema &S) { 14612 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo; 14613 14614 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) { 14615 if (EscapeInfo.count(BD)) 14616 return EscapeInfo[BD]; 14617 14618 bool R = false; 14619 const BlockDecl *CurBD = BD; 14620 14621 do { 14622 R = !CurBD->doesNotEscape(); 14623 if (R) 14624 break; 14625 CurBD = CurBD->getParent()->getInnermostBlockDecl(); 14626 } while (CurBD); 14627 14628 return EscapeInfo[BD] = R; 14629 }; 14630 14631 // If the location where 'self' is implicitly retained is inside a escaping 14632 // block, emit a diagnostic. 14633 for (const std::pair<SourceLocation, const BlockDecl *> &P : 14634 S.ImplicitlyRetainedSelfLocs) 14635 if (IsOrNestedInEscapingBlock(P.second)) 14636 S.Diag(P.first, diag::warn_implicitly_retains_self) 14637 << FixItHint::CreateInsertion(P.first, "self->"); 14638 } 14639 14640 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 14641 bool IsInstantiation) { 14642 FunctionScopeInfo *FSI = getCurFunction(); 14643 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 14644 14645 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>()) 14646 FD->addAttr(StrictFPAttr::CreateImplicit(Context)); 14647 14648 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 14649 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 14650 14651 if (getLangOpts().Coroutines && FSI->isCoroutine()) 14652 CheckCompletedCoroutineBody(FD, Body); 14653 14654 { 14655 // Do not call PopExpressionEvaluationContext() if it is a lambda because 14656 // one is already popped when finishing the lambda in BuildLambdaExpr(). 14657 // This is meant to pop the context added in ActOnStartOfFunctionDef(). 14658 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD)); 14659 14660 if (FD) { 14661 FD->setBody(Body); 14662 FD->setWillHaveBody(false); 14663 14664 if (getLangOpts().CPlusPlus14) { 14665 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 14666 FD->getReturnType()->isUndeducedType()) { 14667 // For a function with a deduced result type to return void, 14668 // the result type as written must be 'auto' or 'decltype(auto)', 14669 // possibly cv-qualified or constrained, but not ref-qualified. 14670 if (!FD->getReturnType()->getAs<AutoType>()) { 14671 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 14672 << FD->getReturnType(); 14673 FD->setInvalidDecl(); 14674 } else { 14675 // Falling off the end of the function is the same as 'return;'. 14676 Expr *Dummy = nullptr; 14677 if (DeduceFunctionTypeFromReturnExpr( 14678 FD, dcl->getLocation(), Dummy, 14679 FD->getReturnType()->getAs<AutoType>())) 14680 FD->setInvalidDecl(); 14681 } 14682 } 14683 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 14684 // In C++11, we don't use 'auto' deduction rules for lambda call 14685 // operators because we don't support return type deduction. 14686 auto *LSI = getCurLambda(); 14687 if (LSI->HasImplicitReturnType) { 14688 deduceClosureReturnType(*LSI); 14689 14690 // C++11 [expr.prim.lambda]p4: 14691 // [...] if there are no return statements in the compound-statement 14692 // [the deduced type is] the type void 14693 QualType RetType = 14694 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 14695 14696 // Update the return type to the deduced type. 14697 const auto *Proto = FD->getType()->castAs<FunctionProtoType>(); 14698 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 14699 Proto->getExtProtoInfo())); 14700 } 14701 } 14702 14703 // If the function implicitly returns zero (like 'main') or is naked, 14704 // don't complain about missing return statements. 14705 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 14706 WP.disableCheckFallThrough(); 14707 14708 // MSVC permits the use of pure specifier (=0) on function definition, 14709 // defined at class scope, warn about this non-standard construct. 14710 if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine()) 14711 Diag(FD->getLocation(), diag::ext_pure_function_definition); 14712 14713 if (!FD->isInvalidDecl()) { 14714 // Don't diagnose unused parameters of defaulted, deleted or naked 14715 // functions. 14716 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() && 14717 !FD->hasAttr<NakedAttr>()) 14718 DiagnoseUnusedParameters(FD->parameters()); 14719 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 14720 FD->getReturnType(), FD); 14721 14722 // If this is a structor, we need a vtable. 14723 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 14724 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 14725 else if (CXXDestructorDecl *Destructor = 14726 dyn_cast<CXXDestructorDecl>(FD)) 14727 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 14728 14729 // Try to apply the named return value optimization. We have to check 14730 // if we can do this here because lambdas keep return statements around 14731 // to deduce an implicit return type. 14732 if (FD->getReturnType()->isRecordType() && 14733 (!getLangOpts().CPlusPlus || !FD->isDependentContext())) 14734 computeNRVO(Body, FSI); 14735 } 14736 14737 // GNU warning -Wmissing-prototypes: 14738 // Warn if a global function is defined without a previous 14739 // prototype declaration. This warning is issued even if the 14740 // definition itself provides a prototype. The aim is to detect 14741 // global functions that fail to be declared in header files. 14742 const FunctionDecl *PossiblePrototype = nullptr; 14743 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) { 14744 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 14745 14746 if (PossiblePrototype) { 14747 // We found a declaration that is not a prototype, 14748 // but that could be a zero-parameter prototype 14749 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) { 14750 TypeLoc TL = TI->getTypeLoc(); 14751 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 14752 Diag(PossiblePrototype->getLocation(), 14753 diag::note_declaration_not_a_prototype) 14754 << (FD->getNumParams() != 0) 14755 << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion( 14756 FTL.getRParenLoc(), "void") 14757 : FixItHint{}); 14758 } 14759 } else { 14760 // Returns true if the token beginning at this Loc is `const`. 14761 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM, 14762 const LangOptions &LangOpts) { 14763 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); 14764 if (LocInfo.first.isInvalid()) 14765 return false; 14766 14767 bool Invalid = false; 14768 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid); 14769 if (Invalid) 14770 return false; 14771 14772 if (LocInfo.second > Buffer.size()) 14773 return false; 14774 14775 const char *LexStart = Buffer.data() + LocInfo.second; 14776 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second); 14777 14778 return StartTok.consume_front("const") && 14779 (StartTok.empty() || isWhitespace(StartTok[0]) || 14780 StartTok.startswith("/*") || StartTok.startswith("//")); 14781 }; 14782 14783 auto findBeginLoc = [&]() { 14784 // If the return type has `const` qualifier, we want to insert 14785 // `static` before `const` (and not before the typename). 14786 if ((FD->getReturnType()->isAnyPointerType() && 14787 FD->getReturnType()->getPointeeType().isConstQualified()) || 14788 FD->getReturnType().isConstQualified()) { 14789 // But only do this if we can determine where the `const` is. 14790 14791 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(), 14792 getLangOpts())) 14793 14794 return FD->getBeginLoc(); 14795 } 14796 return FD->getTypeSpecStartLoc(); 14797 }; 14798 Diag(FD->getTypeSpecStartLoc(), 14799 diag::note_static_for_internal_linkage) 14800 << /* function */ 1 14801 << (FD->getStorageClass() == SC_None 14802 ? FixItHint::CreateInsertion(findBeginLoc(), "static ") 14803 : FixItHint{}); 14804 } 14805 14806 // GNU warning -Wstrict-prototypes 14807 // Warn if K&R function is defined without a previous declaration. 14808 // This warning is issued only if the definition itself does not 14809 // provide a prototype. Only K&R definitions do not provide a 14810 // prototype. 14811 if (!FD->hasWrittenPrototype()) { 14812 TypeSourceInfo *TI = FD->getTypeSourceInfo(); 14813 TypeLoc TL = TI->getTypeLoc(); 14814 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); 14815 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2; 14816 } 14817 } 14818 14819 // Warn on CPUDispatch with an actual body. 14820 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body) 14821 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body)) 14822 if (!CmpndBody->body_empty()) 14823 Diag(CmpndBody->body_front()->getBeginLoc(), 14824 diag::warn_dispatch_body_ignored); 14825 14826 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 14827 const CXXMethodDecl *KeyFunction; 14828 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 14829 MD->isVirtual() && 14830 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 14831 MD == KeyFunction->getCanonicalDecl()) { 14832 // Update the key-function state if necessary for this ABI. 14833 if (FD->isInlined() && 14834 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 14835 Context.setNonKeyFunction(MD); 14836 14837 // If the newly-chosen key function is already defined, then we 14838 // need to mark the vtable as used retroactively. 14839 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 14840 const FunctionDecl *Definition; 14841 if (KeyFunction && KeyFunction->isDefined(Definition)) 14842 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 14843 } else { 14844 // We just defined they key function; mark the vtable as used. 14845 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 14846 } 14847 } 14848 } 14849 14850 assert( 14851 (FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 14852 "Function parsing confused"); 14853 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 14854 assert(MD == getCurMethodDecl() && "Method parsing confused"); 14855 MD->setBody(Body); 14856 if (!MD->isInvalidDecl()) { 14857 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 14858 MD->getReturnType(), MD); 14859 14860 if (Body) 14861 computeNRVO(Body, FSI); 14862 } 14863 if (FSI->ObjCShouldCallSuper) { 14864 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call) 14865 << MD->getSelector().getAsString(); 14866 FSI->ObjCShouldCallSuper = false; 14867 } 14868 if (FSI->ObjCWarnForNoDesignatedInitChain) { 14869 const ObjCMethodDecl *InitMethod = nullptr; 14870 bool isDesignated = 14871 MD->isDesignatedInitializerForTheInterface(&InitMethod); 14872 assert(isDesignated && InitMethod); 14873 (void)isDesignated; 14874 14875 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 14876 auto IFace = MD->getClassInterface(); 14877 if (!IFace) 14878 return false; 14879 auto SuperD = IFace->getSuperClass(); 14880 if (!SuperD) 14881 return false; 14882 return SuperD->getIdentifier() == 14883 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 14884 }; 14885 // Don't issue this warning for unavailable inits or direct subclasses 14886 // of NSObject. 14887 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 14888 Diag(MD->getLocation(), 14889 diag::warn_objc_designated_init_missing_super_call); 14890 Diag(InitMethod->getLocation(), 14891 diag::note_objc_designated_init_marked_here); 14892 } 14893 FSI->ObjCWarnForNoDesignatedInitChain = false; 14894 } 14895 if (FSI->ObjCWarnForNoInitDelegation) { 14896 // Don't issue this warning for unavaialable inits. 14897 if (!MD->isUnavailable()) 14898 Diag(MD->getLocation(), 14899 diag::warn_objc_secondary_init_missing_init_call); 14900 FSI->ObjCWarnForNoInitDelegation = false; 14901 } 14902 14903 diagnoseImplicitlyRetainedSelf(*this); 14904 } else { 14905 // Parsing the function declaration failed in some way. Pop the fake scope 14906 // we pushed on. 14907 PopFunctionScopeInfo(ActivePolicy, dcl); 14908 return nullptr; 14909 } 14910 14911 if (Body && FSI->HasPotentialAvailabilityViolations) 14912 DiagnoseUnguardedAvailabilityViolations(dcl); 14913 14914 assert(!FSI->ObjCShouldCallSuper && 14915 "This should only be set for ObjC methods, which should have been " 14916 "handled in the block above."); 14917 14918 // Verify and clean out per-function state. 14919 if (Body && (!FD || !FD->isDefaulted())) { 14920 // C++ constructors that have function-try-blocks can't have return 14921 // statements in the handlers of that block. (C++ [except.handle]p14) 14922 // Verify this. 14923 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 14924 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 14925 14926 // Verify that gotos and switch cases don't jump into scopes illegally. 14927 if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled()) 14928 DiagnoseInvalidJumps(Body); 14929 14930 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 14931 if (!Destructor->getParent()->isDependentType()) 14932 CheckDestructor(Destructor); 14933 14934 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 14935 Destructor->getParent()); 14936 } 14937 14938 // If any errors have occurred, clear out any temporaries that may have 14939 // been leftover. This ensures that these temporaries won't be picked up 14940 // for deletion in some later function. 14941 if (hasUncompilableErrorOccurred() || 14942 getDiagnostics().getSuppressAllDiagnostics()) { 14943 DiscardCleanupsInEvaluationContext(); 14944 } 14945 if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) { 14946 // Since the body is valid, issue any analysis-based warnings that are 14947 // enabled. 14948 ActivePolicy = &WP; 14949 } 14950 14951 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 14952 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose)) 14953 FD->setInvalidDecl(); 14954 14955 if (FD && FD->hasAttr<NakedAttr>()) { 14956 for (const Stmt *S : Body->children()) { 14957 // Allow local register variables without initializer as they don't 14958 // require prologue. 14959 bool RegisterVariables = false; 14960 if (auto *DS = dyn_cast<DeclStmt>(S)) { 14961 for (const auto *Decl : DS->decls()) { 14962 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 14963 RegisterVariables = 14964 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 14965 if (!RegisterVariables) 14966 break; 14967 } 14968 } 14969 } 14970 if (RegisterVariables) 14971 continue; 14972 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 14973 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function); 14974 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 14975 FD->setInvalidDecl(); 14976 break; 14977 } 14978 } 14979 } 14980 14981 assert(ExprCleanupObjects.size() == 14982 ExprEvalContexts.back().NumCleanupObjects && 14983 "Leftover temporaries in function"); 14984 assert(!Cleanup.exprNeedsCleanups() && 14985 "Unaccounted cleanups in function"); 14986 assert(MaybeODRUseExprs.empty() && 14987 "Leftover expressions for odr-use checking"); 14988 } 14989 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop 14990 // the declaration context below. Otherwise, we're unable to transform 14991 // 'this' expressions when transforming immediate context functions. 14992 14993 if (!IsInstantiation) 14994 PopDeclContext(); 14995 14996 PopFunctionScopeInfo(ActivePolicy, dcl); 14997 // If any errors have occurred, clear out any temporaries that may have 14998 // been leftover. This ensures that these temporaries won't be picked up for 14999 // deletion in some later function. 15000 if (hasUncompilableErrorOccurred()) { 15001 DiscardCleanupsInEvaluationContext(); 15002 } 15003 15004 if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsDevice || 15005 !LangOpts.OMPTargetTriples.empty())) || 15006 LangOpts.CUDA || LangOpts.SYCLIsDevice)) { 15007 auto ES = getEmissionStatus(FD); 15008 if (ES == Sema::FunctionEmissionStatus::Emitted || 15009 ES == Sema::FunctionEmissionStatus::Unknown) 15010 DeclsToCheckForDeferredDiags.insert(FD); 15011 } 15012 15013 if (FD && !FD->isDeleted()) 15014 checkTypeSupport(FD->getType(), FD->getLocation(), FD); 15015 15016 return dcl; 15017 } 15018 15019 /// When we finish delayed parsing of an attribute, we must attach it to the 15020 /// relevant Decl. 15021 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 15022 ParsedAttributes &Attrs) { 15023 // Always attach attributes to the underlying decl. 15024 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 15025 D = TD->getTemplatedDecl(); 15026 ProcessDeclAttributeList(S, D, Attrs); 15027 15028 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 15029 if (Method->isStatic()) 15030 checkThisInStaticMemberFunctionAttributes(Method); 15031 } 15032 15033 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 15034 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 15035 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 15036 IdentifierInfo &II, Scope *S) { 15037 // Find the scope in which the identifier is injected and the corresponding 15038 // DeclContext. 15039 // FIXME: C89 does not say what happens if there is no enclosing block scope. 15040 // In that case, we inject the declaration into the translation unit scope 15041 // instead. 15042 Scope *BlockScope = S; 15043 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) 15044 BlockScope = BlockScope->getParent(); 15045 15046 Scope *ContextScope = BlockScope; 15047 while (!ContextScope->getEntity()) 15048 ContextScope = ContextScope->getParent(); 15049 ContextRAII SavedContext(*this, ContextScope->getEntity()); 15050 15051 // Before we produce a declaration for an implicitly defined 15052 // function, see whether there was a locally-scoped declaration of 15053 // this name as a function or variable. If so, use that 15054 // (non-visible) declaration, and complain about it. 15055 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); 15056 if (ExternCPrev) { 15057 // We still need to inject the function into the enclosing block scope so 15058 // that later (non-call) uses can see it. 15059 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); 15060 15061 // C89 footnote 38: 15062 // If in fact it is not defined as having type "function returning int", 15063 // the behavior is undefined. 15064 if (!isa<FunctionDecl>(ExternCPrev) || 15065 !Context.typesAreCompatible( 15066 cast<FunctionDecl>(ExternCPrev)->getType(), 15067 Context.getFunctionNoProtoType(Context.IntTy))) { 15068 Diag(Loc, diag::ext_use_out_of_scope_declaration) 15069 << ExternCPrev << !getLangOpts().C99; 15070 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 15071 return ExternCPrev; 15072 } 15073 } 15074 15075 // Extension in C99. Legal in C90, but warn about it. 15076 unsigned diag_id; 15077 if (II.getName().startswith("__builtin_")) 15078 diag_id = diag::warn_builtin_unknown; 15079 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. 15080 else if (getLangOpts().OpenCL) 15081 diag_id = diag::err_opencl_implicit_function_decl; 15082 else if (getLangOpts().C99) 15083 diag_id = diag::ext_implicit_function_decl; 15084 else 15085 diag_id = diag::warn_implicit_function_decl; 15086 15087 TypoCorrection Corrected; 15088 // Because typo correction is expensive, only do it if the implicit 15089 // function declaration is going to be treated as an error. 15090 // 15091 // Perform the corection before issuing the main diagnostic, as some consumers 15092 // use typo-correction callbacks to enhance the main diagnostic. 15093 if (S && !ExternCPrev && 15094 (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) { 15095 DeclFilterCCC<FunctionDecl> CCC{}; 15096 Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName, 15097 S, nullptr, CCC, CTK_NonError); 15098 } 15099 15100 Diag(Loc, diag_id) << &II; 15101 if (Corrected) 15102 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 15103 /*ErrorRecovery*/ false); 15104 15105 // If we found a prior declaration of this function, don't bother building 15106 // another one. We've already pushed that one into scope, so there's nothing 15107 // more to do. 15108 if (ExternCPrev) 15109 return ExternCPrev; 15110 15111 // Set a Declarator for the implicit definition: int foo(); 15112 const char *Dummy; 15113 AttributeFactory attrFactory; 15114 DeclSpec DS(attrFactory); 15115 unsigned DiagID; 15116 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 15117 Context.getPrintingPolicy()); 15118 (void)Error; // Silence warning. 15119 assert(!Error && "Error setting up implicit decl!"); 15120 SourceLocation NoLoc; 15121 Declarator D(DS, DeclaratorContext::Block); 15122 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 15123 /*IsAmbiguous=*/false, 15124 /*LParenLoc=*/NoLoc, 15125 /*Params=*/nullptr, 15126 /*NumParams=*/0, 15127 /*EllipsisLoc=*/NoLoc, 15128 /*RParenLoc=*/NoLoc, 15129 /*RefQualifierIsLvalueRef=*/true, 15130 /*RefQualifierLoc=*/NoLoc, 15131 /*MutableLoc=*/NoLoc, EST_None, 15132 /*ESpecRange=*/SourceRange(), 15133 /*Exceptions=*/nullptr, 15134 /*ExceptionRanges=*/nullptr, 15135 /*NumExceptions=*/0, 15136 /*NoexceptExpr=*/nullptr, 15137 /*ExceptionSpecTokens=*/nullptr, 15138 /*DeclsInPrototype=*/None, Loc, 15139 Loc, D), 15140 std::move(DS.getAttributes()), SourceLocation()); 15141 D.SetIdentifier(&II, Loc); 15142 15143 // Insert this function into the enclosing block scope. 15144 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); 15145 FD->setImplicit(); 15146 15147 AddKnownFunctionAttributes(FD); 15148 15149 return FD; 15150 } 15151 15152 /// If this function is a C++ replaceable global allocation function 15153 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]), 15154 /// adds any function attributes that we know a priori based on the standard. 15155 /// 15156 /// We need to check for duplicate attributes both here and where user-written 15157 /// attributes are applied to declarations. 15158 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction( 15159 FunctionDecl *FD) { 15160 if (FD->isInvalidDecl()) 15161 return; 15162 15163 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New && 15164 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New) 15165 return; 15166 15167 Optional<unsigned> AlignmentParam; 15168 bool IsNothrow = false; 15169 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow)) 15170 return; 15171 15172 // C++2a [basic.stc.dynamic.allocation]p4: 15173 // An allocation function that has a non-throwing exception specification 15174 // indicates failure by returning a null pointer value. Any other allocation 15175 // function never returns a null pointer value and indicates failure only by 15176 // throwing an exception [...] 15177 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>()) 15178 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation())); 15179 15180 // C++2a [basic.stc.dynamic.allocation]p2: 15181 // An allocation function attempts to allocate the requested amount of 15182 // storage. [...] If the request succeeds, the value returned by a 15183 // replaceable allocation function is a [...] pointer value p0 different 15184 // from any previously returned value p1 [...] 15185 // 15186 // However, this particular information is being added in codegen, 15187 // because there is an opt-out switch for it (-fno-assume-sane-operator-new) 15188 15189 // C++2a [basic.stc.dynamic.allocation]p2: 15190 // An allocation function attempts to allocate the requested amount of 15191 // storage. If it is successful, it returns the address of the start of a 15192 // block of storage whose length in bytes is at least as large as the 15193 // requested size. 15194 if (!FD->hasAttr<AllocSizeAttr>()) { 15195 FD->addAttr(AllocSizeAttr::CreateImplicit( 15196 Context, /*ElemSizeParam=*/ParamIdx(1, FD), 15197 /*NumElemsParam=*/ParamIdx(), FD->getLocation())); 15198 } 15199 15200 // C++2a [basic.stc.dynamic.allocation]p3: 15201 // For an allocation function [...], the pointer returned on a successful 15202 // call shall represent the address of storage that is aligned as follows: 15203 // (3.1) If the allocation function takes an argument of type 15204 // std::align_val_t, the storage will have the alignment 15205 // specified by the value of this argument. 15206 if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) { 15207 FD->addAttr(AllocAlignAttr::CreateImplicit( 15208 Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation())); 15209 } 15210 15211 // FIXME: 15212 // C++2a [basic.stc.dynamic.allocation]p3: 15213 // For an allocation function [...], the pointer returned on a successful 15214 // call shall represent the address of storage that is aligned as follows: 15215 // (3.2) Otherwise, if the allocation function is named operator new[], 15216 // the storage is aligned for any object that does not have 15217 // new-extended alignment ([basic.align]) and is no larger than the 15218 // requested size. 15219 // (3.3) Otherwise, the storage is aligned for any object that does not 15220 // have new-extended alignment and is of the requested size. 15221 } 15222 15223 /// Adds any function attributes that we know a priori based on 15224 /// the declaration of this function. 15225 /// 15226 /// These attributes can apply both to implicitly-declared builtins 15227 /// (like __builtin___printf_chk) or to library-declared functions 15228 /// like NSLog or printf. 15229 /// 15230 /// We need to check for duplicate attributes both here and where user-written 15231 /// attributes are applied to declarations. 15232 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 15233 if (FD->isInvalidDecl()) 15234 return; 15235 15236 // If this is a built-in function, map its builtin attributes to 15237 // actual attributes. 15238 if (unsigned BuiltinID = FD->getBuiltinID()) { 15239 // Handle printf-formatting attributes. 15240 unsigned FormatIdx; 15241 bool HasVAListArg; 15242 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 15243 if (!FD->hasAttr<FormatAttr>()) { 15244 const char *fmt = "printf"; 15245 unsigned int NumParams = FD->getNumParams(); 15246 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 15247 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 15248 fmt = "NSString"; 15249 FD->addAttr(FormatAttr::CreateImplicit(Context, 15250 &Context.Idents.get(fmt), 15251 FormatIdx+1, 15252 HasVAListArg ? 0 : FormatIdx+2, 15253 FD->getLocation())); 15254 } 15255 } 15256 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 15257 HasVAListArg)) { 15258 if (!FD->hasAttr<FormatAttr>()) 15259 FD->addAttr(FormatAttr::CreateImplicit(Context, 15260 &Context.Idents.get("scanf"), 15261 FormatIdx+1, 15262 HasVAListArg ? 0 : FormatIdx+2, 15263 FD->getLocation())); 15264 } 15265 15266 // Handle automatically recognized callbacks. 15267 SmallVector<int, 4> Encoding; 15268 if (!FD->hasAttr<CallbackAttr>() && 15269 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding)) 15270 FD->addAttr(CallbackAttr::CreateImplicit( 15271 Context, Encoding.data(), Encoding.size(), FD->getLocation())); 15272 15273 // Mark const if we don't care about errno and that is the only thing 15274 // preventing the function from being const. This allows IRgen to use LLVM 15275 // intrinsics for such functions. 15276 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() && 15277 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) 15278 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 15279 15280 // We make "fma" on GNU or Windows const because we know it does not set 15281 // errno in those environments even though it could set errno based on the 15282 // C standard. 15283 const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); 15284 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) && 15285 !FD->hasAttr<ConstAttr>()) { 15286 switch (BuiltinID) { 15287 case Builtin::BI__builtin_fma: 15288 case Builtin::BI__builtin_fmaf: 15289 case Builtin::BI__builtin_fmal: 15290 case Builtin::BIfma: 15291 case Builtin::BIfmaf: 15292 case Builtin::BIfmal: 15293 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 15294 break; 15295 default: 15296 break; 15297 } 15298 } 15299 15300 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 15301 !FD->hasAttr<ReturnsTwiceAttr>()) 15302 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 15303 FD->getLocation())); 15304 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 15305 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 15306 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 15307 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 15308 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 15309 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 15310 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 15311 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 15312 // Add the appropriate attribute, depending on the CUDA compilation mode 15313 // and which target the builtin belongs to. For example, during host 15314 // compilation, aux builtins are __device__, while the rest are __host__. 15315 if (getLangOpts().CUDAIsDevice != 15316 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 15317 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 15318 else 15319 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 15320 } 15321 15322 // Add known guaranteed alignment for allocation functions. 15323 switch (BuiltinID) { 15324 case Builtin::BImemalign: 15325 case Builtin::BIaligned_alloc: 15326 if (!FD->hasAttr<AllocAlignAttr>()) 15327 FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD), 15328 FD->getLocation())); 15329 break; 15330 default: 15331 break; 15332 } 15333 15334 // Add allocsize attribute for allocation functions. 15335 switch (BuiltinID) { 15336 case Builtin::BIcalloc: 15337 FD->addAttr(AllocSizeAttr::CreateImplicit( 15338 Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation())); 15339 break; 15340 case Builtin::BImemalign: 15341 case Builtin::BIaligned_alloc: 15342 case Builtin::BIrealloc: 15343 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD), 15344 ParamIdx(), FD->getLocation())); 15345 break; 15346 case Builtin::BImalloc: 15347 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD), 15348 ParamIdx(), FD->getLocation())); 15349 break; 15350 default: 15351 break; 15352 } 15353 } 15354 15355 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD); 15356 15357 // If C++ exceptions are enabled but we are told extern "C" functions cannot 15358 // throw, add an implicit nothrow attribute to any extern "C" function we come 15359 // across. 15360 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 15361 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 15362 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 15363 if (!FPT || FPT->getExceptionSpecType() == EST_None) 15364 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 15365 } 15366 15367 IdentifierInfo *Name = FD->getIdentifier(); 15368 if (!Name) 15369 return; 15370 if ((!getLangOpts().CPlusPlus && 15371 FD->getDeclContext()->isTranslationUnit()) || 15372 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 15373 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 15374 LinkageSpecDecl::lang_c)) { 15375 // Okay: this could be a libc/libm/Objective-C function we know 15376 // about. 15377 } else 15378 return; 15379 15380 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 15381 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 15382 // target-specific builtins, perhaps? 15383 if (!FD->hasAttr<FormatAttr>()) 15384 FD->addAttr(FormatAttr::CreateImplicit(Context, 15385 &Context.Idents.get("printf"), 2, 15386 Name->isStr("vasprintf") ? 0 : 3, 15387 FD->getLocation())); 15388 } 15389 15390 if (Name->isStr("__CFStringMakeConstantString")) { 15391 // We already have a __builtin___CFStringMakeConstantString, 15392 // but builds that use -fno-constant-cfstrings don't go through that. 15393 if (!FD->hasAttr<FormatArgAttr>()) 15394 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), 15395 FD->getLocation())); 15396 } 15397 } 15398 15399 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 15400 TypeSourceInfo *TInfo) { 15401 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 15402 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 15403 15404 if (!TInfo) { 15405 assert(D.isInvalidType() && "no declarator info for valid type"); 15406 TInfo = Context.getTrivialTypeSourceInfo(T); 15407 } 15408 15409 // Scope manipulation handled by caller. 15410 TypedefDecl *NewTD = 15411 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(), 15412 D.getIdentifierLoc(), D.getIdentifier(), TInfo); 15413 15414 // Bail out immediately if we have an invalid declaration. 15415 if (D.isInvalidType()) { 15416 NewTD->setInvalidDecl(); 15417 return NewTD; 15418 } 15419 15420 if (D.getDeclSpec().isModulePrivateSpecified()) { 15421 if (CurContext->isFunctionOrMethod()) 15422 Diag(NewTD->getLocation(), diag::err_module_private_local) 15423 << 2 << NewTD 15424 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 15425 << FixItHint::CreateRemoval( 15426 D.getDeclSpec().getModulePrivateSpecLoc()); 15427 else 15428 NewTD->setModulePrivate(); 15429 } 15430 15431 // C++ [dcl.typedef]p8: 15432 // If the typedef declaration defines an unnamed class (or 15433 // enum), the first typedef-name declared by the declaration 15434 // to be that class type (or enum type) is used to denote the 15435 // class type (or enum type) for linkage purposes only. 15436 // We need to check whether the type was declared in the declaration. 15437 switch (D.getDeclSpec().getTypeSpecType()) { 15438 case TST_enum: 15439 case TST_struct: 15440 case TST_interface: 15441 case TST_union: 15442 case TST_class: { 15443 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 15444 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 15445 break; 15446 } 15447 15448 default: 15449 break; 15450 } 15451 15452 return NewTD; 15453 } 15454 15455 /// Check that this is a valid underlying type for an enum declaration. 15456 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 15457 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 15458 QualType T = TI->getType(); 15459 15460 if (T->isDependentType()) 15461 return false; 15462 15463 // This doesn't use 'isIntegralType' despite the error message mentioning 15464 // integral type because isIntegralType would also allow enum types in C. 15465 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 15466 if (BT->isInteger()) 15467 return false; 15468 15469 if (T->isBitIntType()) 15470 return false; 15471 15472 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 15473 } 15474 15475 /// Check whether this is a valid redeclaration of a previous enumeration. 15476 /// \return true if the redeclaration was invalid. 15477 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 15478 QualType EnumUnderlyingTy, bool IsFixed, 15479 const EnumDecl *Prev) { 15480 if (IsScoped != Prev->isScoped()) { 15481 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 15482 << Prev->isScoped(); 15483 Diag(Prev->getLocation(), diag::note_previous_declaration); 15484 return true; 15485 } 15486 15487 if (IsFixed && Prev->isFixed()) { 15488 if (!EnumUnderlyingTy->isDependentType() && 15489 !Prev->getIntegerType()->isDependentType() && 15490 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 15491 Prev->getIntegerType())) { 15492 // TODO: Highlight the underlying type of the redeclaration. 15493 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 15494 << EnumUnderlyingTy << Prev->getIntegerType(); 15495 Diag(Prev->getLocation(), diag::note_previous_declaration) 15496 << Prev->getIntegerTypeRange(); 15497 return true; 15498 } 15499 } else if (IsFixed != Prev->isFixed()) { 15500 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 15501 << Prev->isFixed(); 15502 Diag(Prev->getLocation(), diag::note_previous_declaration); 15503 return true; 15504 } 15505 15506 return false; 15507 } 15508 15509 /// Get diagnostic %select index for tag kind for 15510 /// redeclaration diagnostic message. 15511 /// WARNING: Indexes apply to particular diagnostics only! 15512 /// 15513 /// \returns diagnostic %select index. 15514 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 15515 switch (Tag) { 15516 case TTK_Struct: return 0; 15517 case TTK_Interface: return 1; 15518 case TTK_Class: return 2; 15519 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 15520 } 15521 } 15522 15523 /// Determine if tag kind is a class-key compatible with 15524 /// class for redeclaration (class, struct, or __interface). 15525 /// 15526 /// \returns true iff the tag kind is compatible. 15527 static bool isClassCompatTagKind(TagTypeKind Tag) 15528 { 15529 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 15530 } 15531 15532 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 15533 TagTypeKind TTK) { 15534 if (isa<TypedefDecl>(PrevDecl)) 15535 return NTK_Typedef; 15536 else if (isa<TypeAliasDecl>(PrevDecl)) 15537 return NTK_TypeAlias; 15538 else if (isa<ClassTemplateDecl>(PrevDecl)) 15539 return NTK_Template; 15540 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 15541 return NTK_TypeAliasTemplate; 15542 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 15543 return NTK_TemplateTemplateArgument; 15544 switch (TTK) { 15545 case TTK_Struct: 15546 case TTK_Interface: 15547 case TTK_Class: 15548 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 15549 case TTK_Union: 15550 return NTK_NonUnion; 15551 case TTK_Enum: 15552 return NTK_NonEnum; 15553 } 15554 llvm_unreachable("invalid TTK"); 15555 } 15556 15557 /// Determine whether a tag with a given kind is acceptable 15558 /// as a redeclaration of the given tag declaration. 15559 /// 15560 /// \returns true if the new tag kind is acceptable, false otherwise. 15561 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 15562 TagTypeKind NewTag, bool isDefinition, 15563 SourceLocation NewTagLoc, 15564 const IdentifierInfo *Name) { 15565 // C++ [dcl.type.elab]p3: 15566 // The class-key or enum keyword present in the 15567 // elaborated-type-specifier shall agree in kind with the 15568 // declaration to which the name in the elaborated-type-specifier 15569 // refers. This rule also applies to the form of 15570 // elaborated-type-specifier that declares a class-name or 15571 // friend class since it can be construed as referring to the 15572 // definition of the class. Thus, in any 15573 // elaborated-type-specifier, the enum keyword shall be used to 15574 // refer to an enumeration (7.2), the union class-key shall be 15575 // used to refer to a union (clause 9), and either the class or 15576 // struct class-key shall be used to refer to a class (clause 9) 15577 // declared using the class or struct class-key. 15578 TagTypeKind OldTag = Previous->getTagKind(); 15579 if (OldTag != NewTag && 15580 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag))) 15581 return false; 15582 15583 // Tags are compatible, but we might still want to warn on mismatched tags. 15584 // Non-class tags can't be mismatched at this point. 15585 if (!isClassCompatTagKind(NewTag)) 15586 return true; 15587 15588 // Declarations for which -Wmismatched-tags is disabled are entirely ignored 15589 // by our warning analysis. We don't want to warn about mismatches with (eg) 15590 // declarations in system headers that are designed to be specialized, but if 15591 // a user asks us to warn, we should warn if their code contains mismatched 15592 // declarations. 15593 auto IsIgnoredLoc = [&](SourceLocation Loc) { 15594 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch, 15595 Loc); 15596 }; 15597 if (IsIgnoredLoc(NewTagLoc)) 15598 return true; 15599 15600 auto IsIgnored = [&](const TagDecl *Tag) { 15601 return IsIgnoredLoc(Tag->getLocation()); 15602 }; 15603 while (IsIgnored(Previous)) { 15604 Previous = Previous->getPreviousDecl(); 15605 if (!Previous) 15606 return true; 15607 OldTag = Previous->getTagKind(); 15608 } 15609 15610 bool isTemplate = false; 15611 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 15612 isTemplate = Record->getDescribedClassTemplate(); 15613 15614 if (inTemplateInstantiation()) { 15615 if (OldTag != NewTag) { 15616 // In a template instantiation, do not offer fix-its for tag mismatches 15617 // since they usually mess up the template instead of fixing the problem. 15618 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15619 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15620 << getRedeclDiagFromTagKind(OldTag); 15621 // FIXME: Note previous location? 15622 } 15623 return true; 15624 } 15625 15626 if (isDefinition) { 15627 // On definitions, check all previous tags and issue a fix-it for each 15628 // one that doesn't match the current tag. 15629 if (Previous->getDefinition()) { 15630 // Don't suggest fix-its for redefinitions. 15631 return true; 15632 } 15633 15634 bool previousMismatch = false; 15635 for (const TagDecl *I : Previous->redecls()) { 15636 if (I->getTagKind() != NewTag) { 15637 // Ignore previous declarations for which the warning was disabled. 15638 if (IsIgnored(I)) 15639 continue; 15640 15641 if (!previousMismatch) { 15642 previousMismatch = true; 15643 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 15644 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15645 << getRedeclDiagFromTagKind(I->getTagKind()); 15646 } 15647 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 15648 << getRedeclDiagFromTagKind(NewTag) 15649 << FixItHint::CreateReplacement(I->getInnerLocStart(), 15650 TypeWithKeyword::getTagTypeKindName(NewTag)); 15651 } 15652 } 15653 return true; 15654 } 15655 15656 // Identify the prevailing tag kind: this is the kind of the definition (if 15657 // there is a non-ignored definition), or otherwise the kind of the prior 15658 // (non-ignored) declaration. 15659 const TagDecl *PrevDef = Previous->getDefinition(); 15660 if (PrevDef && IsIgnored(PrevDef)) 15661 PrevDef = nullptr; 15662 const TagDecl *Redecl = PrevDef ? PrevDef : Previous; 15663 if (Redecl->getTagKind() != NewTag) { 15664 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15665 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15666 << getRedeclDiagFromTagKind(OldTag); 15667 Diag(Redecl->getLocation(), diag::note_previous_use); 15668 15669 // If there is a previous definition, suggest a fix-it. 15670 if (PrevDef) { 15671 Diag(NewTagLoc, diag::note_struct_class_suggestion) 15672 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 15673 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 15674 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 15675 } 15676 } 15677 15678 return true; 15679 } 15680 15681 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 15682 /// from an outer enclosing namespace or file scope inside a friend declaration. 15683 /// This should provide the commented out code in the following snippet: 15684 /// namespace N { 15685 /// struct X; 15686 /// namespace M { 15687 /// struct Y { friend struct /*N::*/ X; }; 15688 /// } 15689 /// } 15690 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 15691 SourceLocation NameLoc) { 15692 // While the decl is in a namespace, do repeated lookup of that name and see 15693 // if we get the same namespace back. If we do not, continue until 15694 // translation unit scope, at which point we have a fully qualified NNS. 15695 SmallVector<IdentifierInfo *, 4> Namespaces; 15696 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15697 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 15698 // This tag should be declared in a namespace, which can only be enclosed by 15699 // other namespaces. Bail if there's an anonymous namespace in the chain. 15700 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 15701 if (!Namespace || Namespace->isAnonymousNamespace()) 15702 return FixItHint(); 15703 IdentifierInfo *II = Namespace->getIdentifier(); 15704 Namespaces.push_back(II); 15705 NamedDecl *Lookup = SemaRef.LookupSingleName( 15706 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 15707 if (Lookup == Namespace) 15708 break; 15709 } 15710 15711 // Once we have all the namespaces, reverse them to go outermost first, and 15712 // build an NNS. 15713 SmallString<64> Insertion; 15714 llvm::raw_svector_ostream OS(Insertion); 15715 if (DC->isTranslationUnit()) 15716 OS << "::"; 15717 std::reverse(Namespaces.begin(), Namespaces.end()); 15718 for (auto *II : Namespaces) 15719 OS << II->getName() << "::"; 15720 return FixItHint::CreateInsertion(NameLoc, Insertion); 15721 } 15722 15723 /// Determine whether a tag originally declared in context \p OldDC can 15724 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup 15725 /// found a declaration in \p OldDC as a previous decl, perhaps through a 15726 /// using-declaration). 15727 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 15728 DeclContext *NewDC) { 15729 OldDC = OldDC->getRedeclContext(); 15730 NewDC = NewDC->getRedeclContext(); 15731 15732 if (OldDC->Equals(NewDC)) 15733 return true; 15734 15735 // In MSVC mode, we allow a redeclaration if the contexts are related (either 15736 // encloses the other). 15737 if (S.getLangOpts().MSVCCompat && 15738 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 15739 return true; 15740 15741 return false; 15742 } 15743 15744 /// This is invoked when we see 'struct foo' or 'struct {'. In the 15745 /// former case, Name will be non-null. In the later case, Name will be null. 15746 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 15747 /// reference/declaration/definition of a tag. 15748 /// 15749 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 15750 /// trailing-type-specifier) other than one in an alias-declaration. 15751 /// 15752 /// \param SkipBody If non-null, will be set to indicate if the caller should 15753 /// skip the definition of this tag and treat it as if it were a declaration. 15754 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 15755 SourceLocation KWLoc, CXXScopeSpec &SS, 15756 IdentifierInfo *Name, SourceLocation NameLoc, 15757 const ParsedAttributesView &Attrs, AccessSpecifier AS, 15758 SourceLocation ModulePrivateLoc, 15759 MultiTemplateParamsArg TemplateParameterLists, 15760 bool &OwnedDecl, bool &IsDependent, 15761 SourceLocation ScopedEnumKWLoc, 15762 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, 15763 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 15764 SkipBodyInfo *SkipBody) { 15765 // If this is not a definition, it must have a name. 15766 IdentifierInfo *OrigName = Name; 15767 assert((Name != nullptr || TUK == TUK_Definition) && 15768 "Nameless record must be a definition!"); 15769 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 15770 15771 OwnedDecl = false; 15772 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 15773 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 15774 15775 // FIXME: Check member specializations more carefully. 15776 bool isMemberSpecialization = false; 15777 bool Invalid = false; 15778 15779 // We only need to do this matching if we have template parameters 15780 // or a scope specifier, which also conveniently avoids this work 15781 // for non-C++ cases. 15782 if (TemplateParameterLists.size() > 0 || 15783 (SS.isNotEmpty() && TUK != TUK_Reference)) { 15784 if (TemplateParameterList *TemplateParams = 15785 MatchTemplateParametersToScopeSpecifier( 15786 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 15787 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 15788 if (Kind == TTK_Enum) { 15789 Diag(KWLoc, diag::err_enum_template); 15790 return nullptr; 15791 } 15792 15793 if (TemplateParams->size() > 0) { 15794 // This is a declaration or definition of a class template (which may 15795 // be a member of another template). 15796 15797 if (Invalid) 15798 return nullptr; 15799 15800 OwnedDecl = false; 15801 DeclResult Result = CheckClassTemplate( 15802 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams, 15803 AS, ModulePrivateLoc, 15804 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1, 15805 TemplateParameterLists.data(), SkipBody); 15806 return Result.get(); 15807 } else { 15808 // The "template<>" header is extraneous. 15809 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 15810 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 15811 isMemberSpecialization = true; 15812 } 15813 } 15814 15815 if (!TemplateParameterLists.empty() && isMemberSpecialization && 15816 CheckTemplateDeclScope(S, TemplateParameterLists.back())) 15817 return nullptr; 15818 } 15819 15820 // Figure out the underlying type if this a enum declaration. We need to do 15821 // this early, because it's needed to detect if this is an incompatible 15822 // redeclaration. 15823 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 15824 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; 15825 15826 if (Kind == TTK_Enum) { 15827 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { 15828 // No underlying type explicitly specified, or we failed to parse the 15829 // type, default to int. 15830 EnumUnderlying = Context.IntTy.getTypePtr(); 15831 } else if (UnderlyingType.get()) { 15832 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 15833 // integral type; any cv-qualification is ignored. 15834 TypeSourceInfo *TI = nullptr; 15835 GetTypeFromParser(UnderlyingType.get(), &TI); 15836 EnumUnderlying = TI; 15837 15838 if (CheckEnumUnderlyingType(TI)) 15839 // Recover by falling back to int. 15840 EnumUnderlying = Context.IntTy.getTypePtr(); 15841 15842 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 15843 UPPC_FixedUnderlyingType)) 15844 EnumUnderlying = Context.IntTy.getTypePtr(); 15845 15846 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) { 15847 // For MSVC ABI compatibility, unfixed enums must use an underlying type 15848 // of 'int'. However, if this is an unfixed forward declaration, don't set 15849 // the underlying type unless the user enables -fms-compatibility. This 15850 // makes unfixed forward declared enums incomplete and is more conforming. 15851 if (TUK == TUK_Definition || getLangOpts().MSVCCompat) 15852 EnumUnderlying = Context.IntTy.getTypePtr(); 15853 } 15854 } 15855 15856 DeclContext *SearchDC = CurContext; 15857 DeclContext *DC = CurContext; 15858 bool isStdBadAlloc = false; 15859 bool isStdAlignValT = false; 15860 15861 RedeclarationKind Redecl = forRedeclarationInCurContext(); 15862 if (TUK == TUK_Friend || TUK == TUK_Reference) 15863 Redecl = NotForRedeclaration; 15864 15865 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C 15866 /// implemented asks for structural equivalence checking, the returned decl 15867 /// here is passed back to the parser, allowing the tag body to be parsed. 15868 auto createTagFromNewDecl = [&]() -> TagDecl * { 15869 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage"); 15870 // If there is an identifier, use the location of the identifier as the 15871 // location of the decl, otherwise use the location of the struct/union 15872 // keyword. 15873 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 15874 TagDecl *New = nullptr; 15875 15876 if (Kind == TTK_Enum) { 15877 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, 15878 ScopedEnum, ScopedEnumUsesClassTag, IsFixed); 15879 // If this is an undefined enum, bail. 15880 if (TUK != TUK_Definition && !Invalid) 15881 return nullptr; 15882 if (EnumUnderlying) { 15883 EnumDecl *ED = cast<EnumDecl>(New); 15884 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) 15885 ED->setIntegerTypeSourceInfo(TI); 15886 else 15887 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); 15888 ED->setPromotionType(ED->getIntegerType()); 15889 } 15890 } else { // struct/union 15891 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 15892 nullptr); 15893 } 15894 15895 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 15896 // Add alignment attributes if necessary; these attributes are checked 15897 // when the ASTContext lays out the structure. 15898 // 15899 // It is important for implementing the correct semantics that this 15900 // happen here (in ActOnTag). The #pragma pack stack is 15901 // maintained as a result of parser callbacks which can occur at 15902 // many points during the parsing of a struct declaration (because 15903 // the #pragma tokens are effectively skipped over during the 15904 // parsing of the struct). 15905 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 15906 AddAlignmentAttributesForRecord(RD); 15907 AddMsStructLayoutForRecord(RD); 15908 } 15909 } 15910 New->setLexicalDeclContext(CurContext); 15911 return New; 15912 }; 15913 15914 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 15915 if (Name && SS.isNotEmpty()) { 15916 // We have a nested-name tag ('struct foo::bar'). 15917 15918 // Check for invalid 'foo::'. 15919 if (SS.isInvalid()) { 15920 Name = nullptr; 15921 goto CreateNewDecl; 15922 } 15923 15924 // If this is a friend or a reference to a class in a dependent 15925 // context, don't try to make a decl for it. 15926 if (TUK == TUK_Friend || TUK == TUK_Reference) { 15927 DC = computeDeclContext(SS, false); 15928 if (!DC) { 15929 IsDependent = true; 15930 return nullptr; 15931 } 15932 } else { 15933 DC = computeDeclContext(SS, true); 15934 if (!DC) { 15935 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 15936 << SS.getRange(); 15937 return nullptr; 15938 } 15939 } 15940 15941 if (RequireCompleteDeclContext(SS, DC)) 15942 return nullptr; 15943 15944 SearchDC = DC; 15945 // Look-up name inside 'foo::'. 15946 LookupQualifiedName(Previous, DC); 15947 15948 if (Previous.isAmbiguous()) 15949 return nullptr; 15950 15951 if (Previous.empty()) { 15952 // Name lookup did not find anything. However, if the 15953 // nested-name-specifier refers to the current instantiation, 15954 // and that current instantiation has any dependent base 15955 // classes, we might find something at instantiation time: treat 15956 // this as a dependent elaborated-type-specifier. 15957 // But this only makes any sense for reference-like lookups. 15958 if (Previous.wasNotFoundInCurrentInstantiation() && 15959 (TUK == TUK_Reference || TUK == TUK_Friend)) { 15960 IsDependent = true; 15961 return nullptr; 15962 } 15963 15964 // A tag 'foo::bar' must already exist. 15965 Diag(NameLoc, diag::err_not_tag_in_scope) 15966 << Kind << Name << DC << SS.getRange(); 15967 Name = nullptr; 15968 Invalid = true; 15969 goto CreateNewDecl; 15970 } 15971 } else if (Name) { 15972 // C++14 [class.mem]p14: 15973 // If T is the name of a class, then each of the following shall have a 15974 // name different from T: 15975 // -- every member of class T that is itself a type 15976 if (TUK != TUK_Reference && TUK != TUK_Friend && 15977 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 15978 return nullptr; 15979 15980 // If this is a named struct, check to see if there was a previous forward 15981 // declaration or definition. 15982 // FIXME: We're looking into outer scopes here, even when we 15983 // shouldn't be. Doing so can result in ambiguities that we 15984 // shouldn't be diagnosing. 15985 LookupName(Previous, S); 15986 15987 // When declaring or defining a tag, ignore ambiguities introduced 15988 // by types using'ed into this scope. 15989 if (Previous.isAmbiguous() && 15990 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 15991 LookupResult::Filter F = Previous.makeFilter(); 15992 while (F.hasNext()) { 15993 NamedDecl *ND = F.next(); 15994 if (!ND->getDeclContext()->getRedeclContext()->Equals( 15995 SearchDC->getRedeclContext())) 15996 F.erase(); 15997 } 15998 F.done(); 15999 } 16000 16001 // C++11 [namespace.memdef]p3: 16002 // If the name in a friend declaration is neither qualified nor 16003 // a template-id and the declaration is a function or an 16004 // elaborated-type-specifier, the lookup to determine whether 16005 // the entity has been previously declared shall not consider 16006 // any scopes outside the innermost enclosing namespace. 16007 // 16008 // MSVC doesn't implement the above rule for types, so a friend tag 16009 // declaration may be a redeclaration of a type declared in an enclosing 16010 // scope. They do implement this rule for friend functions. 16011 // 16012 // Does it matter that this should be by scope instead of by 16013 // semantic context? 16014 if (!Previous.empty() && TUK == TUK_Friend) { 16015 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 16016 LookupResult::Filter F = Previous.makeFilter(); 16017 bool FriendSawTagOutsideEnclosingNamespace = false; 16018 while (F.hasNext()) { 16019 NamedDecl *ND = F.next(); 16020 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 16021 if (DC->isFileContext() && 16022 !EnclosingNS->Encloses(ND->getDeclContext())) { 16023 if (getLangOpts().MSVCCompat) 16024 FriendSawTagOutsideEnclosingNamespace = true; 16025 else 16026 F.erase(); 16027 } 16028 } 16029 F.done(); 16030 16031 // Diagnose this MSVC extension in the easy case where lookup would have 16032 // unambiguously found something outside the enclosing namespace. 16033 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 16034 NamedDecl *ND = Previous.getFoundDecl(); 16035 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 16036 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 16037 } 16038 } 16039 16040 // Note: there used to be some attempt at recovery here. 16041 if (Previous.isAmbiguous()) 16042 return nullptr; 16043 16044 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 16045 // FIXME: This makes sure that we ignore the contexts associated 16046 // with C structs, unions, and enums when looking for a matching 16047 // tag declaration or definition. See the similar lookup tweak 16048 // in Sema::LookupName; is there a better way to deal with this? 16049 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 16050 SearchDC = SearchDC->getParent(); 16051 } 16052 } 16053 16054 if (Previous.isSingleResult() && 16055 Previous.getFoundDecl()->isTemplateParameter()) { 16056 // Maybe we will complain about the shadowed template parameter. 16057 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 16058 // Just pretend that we didn't see the previous declaration. 16059 Previous.clear(); 16060 } 16061 16062 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 16063 DC->Equals(getStdNamespace())) { 16064 if (Name->isStr("bad_alloc")) { 16065 // This is a declaration of or a reference to "std::bad_alloc". 16066 isStdBadAlloc = true; 16067 16068 // If std::bad_alloc has been implicitly declared (but made invisible to 16069 // name lookup), fill in this implicit declaration as the previous 16070 // declaration, so that the declarations get chained appropriately. 16071 if (Previous.empty() && StdBadAlloc) 16072 Previous.addDecl(getStdBadAlloc()); 16073 } else if (Name->isStr("align_val_t")) { 16074 isStdAlignValT = true; 16075 if (Previous.empty() && StdAlignValT) 16076 Previous.addDecl(getStdAlignValT()); 16077 } 16078 } 16079 16080 // If we didn't find a previous declaration, and this is a reference 16081 // (or friend reference), move to the correct scope. In C++, we 16082 // also need to do a redeclaration lookup there, just in case 16083 // there's a shadow friend decl. 16084 if (Name && Previous.empty() && 16085 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { 16086 if (Invalid) goto CreateNewDecl; 16087 assert(SS.isEmpty()); 16088 16089 if (TUK == TUK_Reference || IsTemplateParamOrArg) { 16090 // C++ [basic.scope.pdecl]p5: 16091 // -- for an elaborated-type-specifier of the form 16092 // 16093 // class-key identifier 16094 // 16095 // if the elaborated-type-specifier is used in the 16096 // decl-specifier-seq or parameter-declaration-clause of a 16097 // function defined in namespace scope, the identifier is 16098 // declared as a class-name in the namespace that contains 16099 // the declaration; otherwise, except as a friend 16100 // declaration, the identifier is declared in the smallest 16101 // non-class, non-function-prototype scope that contains the 16102 // declaration. 16103 // 16104 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 16105 // C structs and unions. 16106 // 16107 // It is an error in C++ to declare (rather than define) an enum 16108 // type, including via an elaborated type specifier. We'll 16109 // diagnose that later; for now, declare the enum in the same 16110 // scope as we would have picked for any other tag type. 16111 // 16112 // GNU C also supports this behavior as part of its incomplete 16113 // enum types extension, while GNU C++ does not. 16114 // 16115 // Find the context where we'll be declaring the tag. 16116 // FIXME: We would like to maintain the current DeclContext as the 16117 // lexical context, 16118 SearchDC = getTagInjectionContext(SearchDC); 16119 16120 // Find the scope where we'll be declaring the tag. 16121 S = getTagInjectionScope(S, getLangOpts()); 16122 } else { 16123 assert(TUK == TUK_Friend); 16124 // C++ [namespace.memdef]p3: 16125 // If a friend declaration in a non-local class first declares a 16126 // class or function, the friend class or function is a member of 16127 // the innermost enclosing namespace. 16128 SearchDC = SearchDC->getEnclosingNamespaceContext(); 16129 } 16130 16131 // In C++, we need to do a redeclaration lookup to properly 16132 // diagnose some problems. 16133 // FIXME: redeclaration lookup is also used (with and without C++) to find a 16134 // hidden declaration so that we don't get ambiguity errors when using a 16135 // type declared by an elaborated-type-specifier. In C that is not correct 16136 // and we should instead merge compatible types found by lookup. 16137 if (getLangOpts().CPlusPlus) { 16138 // FIXME: This can perform qualified lookups into function contexts, 16139 // which are meaningless. 16140 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 16141 LookupQualifiedName(Previous, SearchDC); 16142 } else { 16143 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 16144 LookupName(Previous, S); 16145 } 16146 } 16147 16148 // If we have a known previous declaration to use, then use it. 16149 if (Previous.empty() && SkipBody && SkipBody->Previous) 16150 Previous.addDecl(SkipBody->Previous); 16151 16152 if (!Previous.empty()) { 16153 NamedDecl *PrevDecl = Previous.getFoundDecl(); 16154 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 16155 16156 // It's okay to have a tag decl in the same scope as a typedef 16157 // which hides a tag decl in the same scope. Finding this 16158 // with a redeclaration lookup can only actually happen in C++. 16159 // 16160 // This is also okay for elaborated-type-specifiers, which is 16161 // technically forbidden by the current standard but which is 16162 // okay according to the likely resolution of an open issue; 16163 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 16164 if (getLangOpts().CPlusPlus) { 16165 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 16166 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 16167 TagDecl *Tag = TT->getDecl(); 16168 if (Tag->getDeclName() == Name && 16169 Tag->getDeclContext()->getRedeclContext() 16170 ->Equals(TD->getDeclContext()->getRedeclContext())) { 16171 PrevDecl = Tag; 16172 Previous.clear(); 16173 Previous.addDecl(Tag); 16174 Previous.resolveKind(); 16175 } 16176 } 16177 } 16178 } 16179 16180 // If this is a redeclaration of a using shadow declaration, it must 16181 // declare a tag in the same context. In MSVC mode, we allow a 16182 // redefinition if either context is within the other. 16183 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 16184 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 16185 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 16186 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 16187 !(OldTag && isAcceptableTagRedeclContext( 16188 *this, OldTag->getDeclContext(), SearchDC))) { 16189 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 16190 Diag(Shadow->getTargetDecl()->getLocation(), 16191 diag::note_using_decl_target); 16192 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) 16193 << 0; 16194 // Recover by ignoring the old declaration. 16195 Previous.clear(); 16196 goto CreateNewDecl; 16197 } 16198 } 16199 16200 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 16201 // If this is a use of a previous tag, or if the tag is already declared 16202 // in the same scope (so that the definition/declaration completes or 16203 // rementions the tag), reuse the decl. 16204 if (TUK == TUK_Reference || TUK == TUK_Friend || 16205 isDeclInScope(DirectPrevDecl, SearchDC, S, 16206 SS.isNotEmpty() || isMemberSpecialization)) { 16207 // Make sure that this wasn't declared as an enum and now used as a 16208 // struct or something similar. 16209 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 16210 TUK == TUK_Definition, KWLoc, 16211 Name)) { 16212 bool SafeToContinue 16213 = (PrevTagDecl->getTagKind() != TTK_Enum && 16214 Kind != TTK_Enum); 16215 if (SafeToContinue) 16216 Diag(KWLoc, diag::err_use_with_wrong_tag) 16217 << Name 16218 << FixItHint::CreateReplacement(SourceRange(KWLoc), 16219 PrevTagDecl->getKindName()); 16220 else 16221 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 16222 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 16223 16224 if (SafeToContinue) 16225 Kind = PrevTagDecl->getTagKind(); 16226 else { 16227 // Recover by making this an anonymous redefinition. 16228 Name = nullptr; 16229 Previous.clear(); 16230 Invalid = true; 16231 } 16232 } 16233 16234 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 16235 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 16236 if (TUK == TUK_Reference || TUK == TUK_Friend) 16237 return PrevTagDecl; 16238 16239 QualType EnumUnderlyingTy; 16240 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 16241 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 16242 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 16243 EnumUnderlyingTy = QualType(T, 0); 16244 16245 // All conflicts with previous declarations are recovered by 16246 // returning the previous declaration, unless this is a definition, 16247 // in which case we want the caller to bail out. 16248 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 16249 ScopedEnum, EnumUnderlyingTy, 16250 IsFixed, PrevEnum)) 16251 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 16252 } 16253 16254 // C++11 [class.mem]p1: 16255 // A member shall not be declared twice in the member-specification, 16256 // except that a nested class or member class template can be declared 16257 // and then later defined. 16258 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 16259 S->isDeclScope(PrevDecl)) { 16260 Diag(NameLoc, diag::ext_member_redeclared); 16261 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 16262 } 16263 16264 if (!Invalid) { 16265 // If this is a use, just return the declaration we found, unless 16266 // we have attributes. 16267 if (TUK == TUK_Reference || TUK == TUK_Friend) { 16268 if (!Attrs.empty()) { 16269 // FIXME: Diagnose these attributes. For now, we create a new 16270 // declaration to hold them. 16271 } else if (TUK == TUK_Reference && 16272 (PrevTagDecl->getFriendObjectKind() == 16273 Decl::FOK_Undeclared || 16274 PrevDecl->getOwningModule() != getCurrentModule()) && 16275 SS.isEmpty()) { 16276 // This declaration is a reference to an existing entity, but 16277 // has different visibility from that entity: it either makes 16278 // a friend visible or it makes a type visible in a new module. 16279 // In either case, create a new declaration. We only do this if 16280 // the declaration would have meant the same thing if no prior 16281 // declaration were found, that is, if it was found in the same 16282 // scope where we would have injected a declaration. 16283 if (!getTagInjectionContext(CurContext)->getRedeclContext() 16284 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 16285 return PrevTagDecl; 16286 // This is in the injected scope, create a new declaration in 16287 // that scope. 16288 S = getTagInjectionScope(S, getLangOpts()); 16289 } else { 16290 return PrevTagDecl; 16291 } 16292 } 16293 16294 // Diagnose attempts to redefine a tag. 16295 if (TUK == TUK_Definition) { 16296 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 16297 // If we're defining a specialization and the previous definition 16298 // is from an implicit instantiation, don't emit an error 16299 // here; we'll catch this in the general case below. 16300 bool IsExplicitSpecializationAfterInstantiation = false; 16301 if (isMemberSpecialization) { 16302 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 16303 IsExplicitSpecializationAfterInstantiation = 16304 RD->getTemplateSpecializationKind() != 16305 TSK_ExplicitSpecialization; 16306 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 16307 IsExplicitSpecializationAfterInstantiation = 16308 ED->getTemplateSpecializationKind() != 16309 TSK_ExplicitSpecialization; 16310 } 16311 16312 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do 16313 // not keep more that one definition around (merge them). However, 16314 // ensure the decl passes the structural compatibility check in 16315 // C11 6.2.7/1 (or 6.1.2.6/1 in C89). 16316 NamedDecl *Hidden = nullptr; 16317 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 16318 // There is a definition of this tag, but it is not visible. We 16319 // explicitly make use of C++'s one definition rule here, and 16320 // assume that this definition is identical to the hidden one 16321 // we already have. Make the existing definition visible and 16322 // use it in place of this one. 16323 if (!getLangOpts().CPlusPlus) { 16324 // Postpone making the old definition visible until after we 16325 // complete parsing the new one and do the structural 16326 // comparison. 16327 SkipBody->CheckSameAsPrevious = true; 16328 SkipBody->New = createTagFromNewDecl(); 16329 SkipBody->Previous = Def; 16330 return Def; 16331 } else { 16332 SkipBody->ShouldSkip = true; 16333 SkipBody->Previous = Def; 16334 makeMergedDefinitionVisible(Hidden); 16335 // Carry on and handle it like a normal definition. We'll 16336 // skip starting the definitiion later. 16337 } 16338 } else if (!IsExplicitSpecializationAfterInstantiation) { 16339 // A redeclaration in function prototype scope in C isn't 16340 // visible elsewhere, so merely issue a warning. 16341 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 16342 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 16343 else 16344 Diag(NameLoc, diag::err_redefinition) << Name; 16345 notePreviousDefinition(Def, 16346 NameLoc.isValid() ? NameLoc : KWLoc); 16347 // If this is a redefinition, recover by making this 16348 // struct be anonymous, which will make any later 16349 // references get the previous definition. 16350 Name = nullptr; 16351 Previous.clear(); 16352 Invalid = true; 16353 } 16354 } else { 16355 // If the type is currently being defined, complain 16356 // about a nested redefinition. 16357 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 16358 if (TD->isBeingDefined()) { 16359 Diag(NameLoc, diag::err_nested_redefinition) << Name; 16360 Diag(PrevTagDecl->getLocation(), 16361 diag::note_previous_definition); 16362 Name = nullptr; 16363 Previous.clear(); 16364 Invalid = true; 16365 } 16366 } 16367 16368 // Okay, this is definition of a previously declared or referenced 16369 // tag. We're going to create a new Decl for it. 16370 } 16371 16372 // Okay, we're going to make a redeclaration. If this is some kind 16373 // of reference, make sure we build the redeclaration in the same DC 16374 // as the original, and ignore the current access specifier. 16375 if (TUK == TUK_Friend || TUK == TUK_Reference) { 16376 SearchDC = PrevTagDecl->getDeclContext(); 16377 AS = AS_none; 16378 } 16379 } 16380 // If we get here we have (another) forward declaration or we 16381 // have a definition. Just create a new decl. 16382 16383 } else { 16384 // If we get here, this is a definition of a new tag type in a nested 16385 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 16386 // new decl/type. We set PrevDecl to NULL so that the entities 16387 // have distinct types. 16388 Previous.clear(); 16389 } 16390 // If we get here, we're going to create a new Decl. If PrevDecl 16391 // is non-NULL, it's a definition of the tag declared by 16392 // PrevDecl. If it's NULL, we have a new definition. 16393 16394 // Otherwise, PrevDecl is not a tag, but was found with tag 16395 // lookup. This is only actually possible in C++, where a few 16396 // things like templates still live in the tag namespace. 16397 } else { 16398 // Use a better diagnostic if an elaborated-type-specifier 16399 // found the wrong kind of type on the first 16400 // (non-redeclaration) lookup. 16401 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 16402 !Previous.isForRedeclaration()) { 16403 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 16404 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 16405 << Kind; 16406 Diag(PrevDecl->getLocation(), diag::note_declared_at); 16407 Invalid = true; 16408 16409 // Otherwise, only diagnose if the declaration is in scope. 16410 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 16411 SS.isNotEmpty() || isMemberSpecialization)) { 16412 // do nothing 16413 16414 // Diagnose implicit declarations introduced by elaborated types. 16415 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 16416 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 16417 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 16418 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 16419 Invalid = true; 16420 16421 // Otherwise it's a declaration. Call out a particularly common 16422 // case here. 16423 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 16424 unsigned Kind = 0; 16425 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 16426 Diag(NameLoc, diag::err_tag_definition_of_typedef) 16427 << Name << Kind << TND->getUnderlyingType(); 16428 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 16429 Invalid = true; 16430 16431 // Otherwise, diagnose. 16432 } else { 16433 // The tag name clashes with something else in the target scope, 16434 // issue an error and recover by making this tag be anonymous. 16435 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 16436 notePreviousDefinition(PrevDecl, NameLoc); 16437 Name = nullptr; 16438 Invalid = true; 16439 } 16440 16441 // The existing declaration isn't relevant to us; we're in a 16442 // new scope, so clear out the previous declaration. 16443 Previous.clear(); 16444 } 16445 } 16446 16447 CreateNewDecl: 16448 16449 TagDecl *PrevDecl = nullptr; 16450 if (Previous.isSingleResult()) 16451 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 16452 16453 // If there is an identifier, use the location of the identifier as the 16454 // location of the decl, otherwise use the location of the struct/union 16455 // keyword. 16456 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 16457 16458 // Otherwise, create a new declaration. If there is a previous 16459 // declaration of the same entity, the two will be linked via 16460 // PrevDecl. 16461 TagDecl *New; 16462 16463 if (Kind == TTK_Enum) { 16464 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 16465 // enum X { A, B, C } D; D should chain to X. 16466 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 16467 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 16468 ScopedEnumUsesClassTag, IsFixed); 16469 16470 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 16471 StdAlignValT = cast<EnumDecl>(New); 16472 16473 // If this is an undefined enum, warn. 16474 if (TUK != TUK_Definition && !Invalid) { 16475 TagDecl *Def; 16476 if (IsFixed && cast<EnumDecl>(New)->isFixed()) { 16477 // C++0x: 7.2p2: opaque-enum-declaration. 16478 // Conflicts are diagnosed above. Do nothing. 16479 } 16480 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 16481 Diag(Loc, diag::ext_forward_ref_enum_def) 16482 << New; 16483 Diag(Def->getLocation(), diag::note_previous_definition); 16484 } else { 16485 unsigned DiagID = diag::ext_forward_ref_enum; 16486 if (getLangOpts().MSVCCompat) 16487 DiagID = diag::ext_ms_forward_ref_enum; 16488 else if (getLangOpts().CPlusPlus) 16489 DiagID = diag::err_forward_ref_enum; 16490 Diag(Loc, DiagID); 16491 } 16492 } 16493 16494 if (EnumUnderlying) { 16495 EnumDecl *ED = cast<EnumDecl>(New); 16496 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 16497 ED->setIntegerTypeSourceInfo(TI); 16498 else 16499 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 16500 ED->setPromotionType(ED->getIntegerType()); 16501 assert(ED->isComplete() && "enum with type should be complete"); 16502 } 16503 } else { 16504 // struct/union/class 16505 16506 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 16507 // struct X { int A; } D; D should chain to X. 16508 if (getLangOpts().CPlusPlus) { 16509 // FIXME: Look for a way to use RecordDecl for simple structs. 16510 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 16511 cast_or_null<CXXRecordDecl>(PrevDecl)); 16512 16513 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 16514 StdBadAlloc = cast<CXXRecordDecl>(New); 16515 } else 16516 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 16517 cast_or_null<RecordDecl>(PrevDecl)); 16518 } 16519 16520 // C++11 [dcl.type]p3: 16521 // A type-specifier-seq shall not define a class or enumeration [...]. 16522 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && 16523 TUK == TUK_Definition) { 16524 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 16525 << Context.getTagDeclType(New); 16526 Invalid = true; 16527 } 16528 16529 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && 16530 DC->getDeclKind() == Decl::Enum) { 16531 Diag(New->getLocation(), diag::err_type_defined_in_enum) 16532 << Context.getTagDeclType(New); 16533 Invalid = true; 16534 } 16535 16536 // Maybe add qualifier info. 16537 if (SS.isNotEmpty()) { 16538 if (SS.isSet()) { 16539 // If this is either a declaration or a definition, check the 16540 // nested-name-specifier against the current context. 16541 if ((TUK == TUK_Definition || TUK == TUK_Declaration) && 16542 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, 16543 isMemberSpecialization)) 16544 Invalid = true; 16545 16546 New->setQualifierInfo(SS.getWithLocInContext(Context)); 16547 if (TemplateParameterLists.size() > 0) { 16548 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 16549 } 16550 } 16551 else 16552 Invalid = true; 16553 } 16554 16555 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 16556 // Add alignment attributes if necessary; these attributes are checked when 16557 // the ASTContext lays out the structure. 16558 // 16559 // It is important for implementing the correct semantics that this 16560 // happen here (in ActOnTag). The #pragma pack stack is 16561 // maintained as a result of parser callbacks which can occur at 16562 // many points during the parsing of a struct declaration (because 16563 // the #pragma tokens are effectively skipped over during the 16564 // parsing of the struct). 16565 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 16566 AddAlignmentAttributesForRecord(RD); 16567 AddMsStructLayoutForRecord(RD); 16568 } 16569 } 16570 16571 if (ModulePrivateLoc.isValid()) { 16572 if (isMemberSpecialization) 16573 Diag(New->getLocation(), diag::err_module_private_specialization) 16574 << 2 16575 << FixItHint::CreateRemoval(ModulePrivateLoc); 16576 // __module_private__ does not apply to local classes. However, we only 16577 // diagnose this as an error when the declaration specifiers are 16578 // freestanding. Here, we just ignore the __module_private__. 16579 else if (!SearchDC->isFunctionOrMethod()) 16580 New->setModulePrivate(); 16581 } 16582 16583 // If this is a specialization of a member class (of a class template), 16584 // check the specialization. 16585 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 16586 Invalid = true; 16587 16588 // If we're declaring or defining a tag in function prototype scope in C, 16589 // note that this type can only be used within the function and add it to 16590 // the list of decls to inject into the function definition scope. 16591 if ((Name || Kind == TTK_Enum) && 16592 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 16593 if (getLangOpts().CPlusPlus) { 16594 // C++ [dcl.fct]p6: 16595 // Types shall not be defined in return or parameter types. 16596 if (TUK == TUK_Definition && !IsTypeSpecifier) { 16597 Diag(Loc, diag::err_type_defined_in_param_type) 16598 << Name; 16599 Invalid = true; 16600 } 16601 } else if (!PrevDecl) { 16602 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 16603 } 16604 } 16605 16606 if (Invalid) 16607 New->setInvalidDecl(); 16608 16609 // Set the lexical context. If the tag has a C++ scope specifier, the 16610 // lexical context will be different from the semantic context. 16611 New->setLexicalDeclContext(CurContext); 16612 16613 // Mark this as a friend decl if applicable. 16614 // In Microsoft mode, a friend declaration also acts as a forward 16615 // declaration so we always pass true to setObjectOfFriendDecl to make 16616 // the tag name visible. 16617 if (TUK == TUK_Friend) 16618 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 16619 16620 // Set the access specifier. 16621 if (!Invalid && SearchDC->isRecord()) 16622 SetMemberAccessSpecifier(New, PrevDecl, AS); 16623 16624 if (PrevDecl) 16625 CheckRedeclarationInModule(New, PrevDecl); 16626 16627 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) 16628 New->startDefinition(); 16629 16630 ProcessDeclAttributeList(S, New, Attrs); 16631 AddPragmaAttributes(S, New); 16632 16633 // If this has an identifier, add it to the scope stack. 16634 if (TUK == TUK_Friend) { 16635 // We might be replacing an existing declaration in the lookup tables; 16636 // if so, borrow its access specifier. 16637 if (PrevDecl) 16638 New->setAccess(PrevDecl->getAccess()); 16639 16640 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 16641 DC->makeDeclVisibleInContext(New); 16642 if (Name) // can be null along some error paths 16643 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 16644 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 16645 } else if (Name) { 16646 S = getNonFieldDeclScope(S); 16647 PushOnScopeChains(New, S, true); 16648 } else { 16649 CurContext->addDecl(New); 16650 } 16651 16652 // If this is the C FILE type, notify the AST context. 16653 if (IdentifierInfo *II = New->getIdentifier()) 16654 if (!New->isInvalidDecl() && 16655 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 16656 II->isStr("FILE")) 16657 Context.setFILEDecl(New); 16658 16659 if (PrevDecl) 16660 mergeDeclAttributes(New, PrevDecl); 16661 16662 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) 16663 inferGslOwnerPointerAttribute(CXXRD); 16664 16665 // If there's a #pragma GCC visibility in scope, set the visibility of this 16666 // record. 16667 AddPushedVisibilityAttribute(New); 16668 16669 if (isMemberSpecialization && !New->isInvalidDecl()) 16670 CompleteMemberSpecialization(New, Previous); 16671 16672 OwnedDecl = true; 16673 // In C++, don't return an invalid declaration. We can't recover well from 16674 // the cases where we make the type anonymous. 16675 if (Invalid && getLangOpts().CPlusPlus) { 16676 if (New->isBeingDefined()) 16677 if (auto RD = dyn_cast<RecordDecl>(New)) 16678 RD->completeDefinition(); 16679 return nullptr; 16680 } else if (SkipBody && SkipBody->ShouldSkip) { 16681 return SkipBody->Previous; 16682 } else { 16683 return New; 16684 } 16685 } 16686 16687 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 16688 AdjustDeclIfTemplate(TagD); 16689 TagDecl *Tag = cast<TagDecl>(TagD); 16690 16691 // Enter the tag context. 16692 PushDeclContext(S, Tag); 16693 16694 ActOnDocumentableDecl(TagD); 16695 16696 // If there's a #pragma GCC visibility in scope, set the visibility of this 16697 // record. 16698 AddPushedVisibilityAttribute(Tag); 16699 } 16700 16701 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, 16702 SkipBodyInfo &SkipBody) { 16703 if (!hasStructuralCompatLayout(Prev, SkipBody.New)) 16704 return false; 16705 16706 // Make the previous decl visible. 16707 makeMergedDefinitionVisible(SkipBody.Previous); 16708 return true; 16709 } 16710 16711 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 16712 assert(isa<ObjCContainerDecl>(IDecl) && 16713 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 16714 DeclContext *OCD = cast<DeclContext>(IDecl); 16715 assert(OCD->getLexicalParent() == CurContext && 16716 "The next DeclContext should be lexically contained in the current one."); 16717 CurContext = OCD; 16718 return IDecl; 16719 } 16720 16721 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 16722 SourceLocation FinalLoc, 16723 bool IsFinalSpelledSealed, 16724 bool IsAbstract, 16725 SourceLocation LBraceLoc) { 16726 AdjustDeclIfTemplate(TagD); 16727 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 16728 16729 FieldCollector->StartClass(); 16730 16731 if (!Record->getIdentifier()) 16732 return; 16733 16734 if (IsAbstract) 16735 Record->markAbstract(); 16736 16737 if (FinalLoc.isValid()) { 16738 Record->addAttr(FinalAttr::Create( 16739 Context, FinalLoc, AttributeCommonInfo::AS_Keyword, 16740 static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed))); 16741 } 16742 // C++ [class]p2: 16743 // [...] The class-name is also inserted into the scope of the 16744 // class itself; this is known as the injected-class-name. For 16745 // purposes of access checking, the injected-class-name is treated 16746 // as if it were a public member name. 16747 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create( 16748 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(), 16749 Record->getLocation(), Record->getIdentifier(), 16750 /*PrevDecl=*/nullptr, 16751 /*DelayTypeCreation=*/true); 16752 Context.getTypeDeclType(InjectedClassName, Record); 16753 InjectedClassName->setImplicit(); 16754 InjectedClassName->setAccess(AS_public); 16755 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 16756 InjectedClassName->setDescribedClassTemplate(Template); 16757 PushOnScopeChains(InjectedClassName, S); 16758 assert(InjectedClassName->isInjectedClassName() && 16759 "Broken injected-class-name"); 16760 } 16761 16762 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 16763 SourceRange BraceRange) { 16764 AdjustDeclIfTemplate(TagD); 16765 TagDecl *Tag = cast<TagDecl>(TagD); 16766 Tag->setBraceRange(BraceRange); 16767 16768 // Make sure we "complete" the definition even it is invalid. 16769 if (Tag->isBeingDefined()) { 16770 assert(Tag->isInvalidDecl() && "We should already have completed it"); 16771 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16772 RD->completeDefinition(); 16773 } 16774 16775 if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) { 16776 FieldCollector->FinishClass(); 16777 if (RD->hasAttr<SYCLSpecialClassAttr>()) { 16778 auto *Def = RD->getDefinition(); 16779 assert(Def && "The record is expected to have a completed definition"); 16780 unsigned NumInitMethods = 0; 16781 for (auto *Method : Def->methods()) { 16782 if (!Method->getIdentifier()) 16783 continue; 16784 if (Method->getName() == "__init") 16785 NumInitMethods++; 16786 } 16787 if (NumInitMethods > 1 || !Def->hasInitMethod()) 16788 Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method); 16789 } 16790 } 16791 16792 // Exit this scope of this tag's definition. 16793 PopDeclContext(); 16794 16795 if (getCurLexicalContext()->isObjCContainer() && 16796 Tag->getDeclContext()->isFileContext()) 16797 Tag->setTopLevelDeclInObjCContainer(); 16798 16799 // Notify the consumer that we've defined a tag. 16800 if (!Tag->isInvalidDecl()) 16801 Consumer.HandleTagDeclDefinition(Tag); 16802 16803 // Clangs implementation of #pragma align(packed) differs in bitfield layout 16804 // from XLs and instead matches the XL #pragma pack(1) behavior. 16805 if (Context.getTargetInfo().getTriple().isOSAIX() && 16806 AlignPackStack.hasValue()) { 16807 AlignPackInfo APInfo = AlignPackStack.CurrentValue; 16808 // Only diagnose #pragma align(packed). 16809 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed) 16810 return; 16811 const RecordDecl *RD = dyn_cast<RecordDecl>(Tag); 16812 if (!RD) 16813 return; 16814 // Only warn if there is at least 1 bitfield member. 16815 if (llvm::any_of(RD->fields(), 16816 [](const FieldDecl *FD) { return FD->isBitField(); })) 16817 Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible); 16818 } 16819 } 16820 16821 void Sema::ActOnObjCContainerFinishDefinition() { 16822 // Exit this scope of this interface definition. 16823 PopDeclContext(); 16824 } 16825 16826 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 16827 assert(DC == CurContext && "Mismatch of container contexts"); 16828 OriginalLexicalContext = DC; 16829 ActOnObjCContainerFinishDefinition(); 16830 } 16831 16832 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 16833 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 16834 OriginalLexicalContext = nullptr; 16835 } 16836 16837 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 16838 AdjustDeclIfTemplate(TagD); 16839 TagDecl *Tag = cast<TagDecl>(TagD); 16840 Tag->setInvalidDecl(); 16841 16842 // Make sure we "complete" the definition even it is invalid. 16843 if (Tag->isBeingDefined()) { 16844 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16845 RD->completeDefinition(); 16846 } 16847 16848 // We're undoing ActOnTagStartDefinition here, not 16849 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 16850 // the FieldCollector. 16851 16852 PopDeclContext(); 16853 } 16854 16855 // Note that FieldName may be null for anonymous bitfields. 16856 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 16857 IdentifierInfo *FieldName, 16858 QualType FieldTy, bool IsMsStruct, 16859 Expr *BitWidth, bool *ZeroWidth) { 16860 assert(BitWidth); 16861 if (BitWidth->containsErrors()) 16862 return ExprError(); 16863 16864 // Default to true; that shouldn't confuse checks for emptiness 16865 if (ZeroWidth) 16866 *ZeroWidth = true; 16867 16868 // C99 6.7.2.1p4 - verify the field type. 16869 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 16870 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 16871 // Handle incomplete and sizeless types with a specific error. 16872 if (RequireCompleteSizedType(FieldLoc, FieldTy, 16873 diag::err_field_incomplete_or_sizeless)) 16874 return ExprError(); 16875 if (FieldName) 16876 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 16877 << FieldName << FieldTy << BitWidth->getSourceRange(); 16878 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 16879 << FieldTy << BitWidth->getSourceRange(); 16880 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 16881 UPPC_BitFieldWidth)) 16882 return ExprError(); 16883 16884 // If the bit-width is type- or value-dependent, don't try to check 16885 // it now. 16886 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 16887 return BitWidth; 16888 16889 llvm::APSInt Value; 16890 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold); 16891 if (ICE.isInvalid()) 16892 return ICE; 16893 BitWidth = ICE.get(); 16894 16895 if (Value != 0 && ZeroWidth) 16896 *ZeroWidth = false; 16897 16898 // Zero-width bitfield is ok for anonymous field. 16899 if (Value == 0 && FieldName) 16900 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 16901 16902 if (Value.isSigned() && Value.isNegative()) { 16903 if (FieldName) 16904 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 16905 << FieldName << toString(Value, 10); 16906 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 16907 << toString(Value, 10); 16908 } 16909 16910 // The size of the bit-field must not exceed our maximum permitted object 16911 // size. 16912 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) { 16913 return Diag(FieldLoc, diag::err_bitfield_too_wide) 16914 << !FieldName << FieldName << toString(Value, 10); 16915 } 16916 16917 if (!FieldTy->isDependentType()) { 16918 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 16919 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 16920 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 16921 16922 // Over-wide bitfields are an error in C or when using the MSVC bitfield 16923 // ABI. 16924 bool CStdConstraintViolation = 16925 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 16926 bool MSBitfieldViolation = 16927 Value.ugt(TypeStorageSize) && 16928 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 16929 if (CStdConstraintViolation || MSBitfieldViolation) { 16930 unsigned DiagWidth = 16931 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 16932 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 16933 << (bool)FieldName << FieldName << toString(Value, 10) 16934 << !CStdConstraintViolation << DiagWidth; 16935 } 16936 16937 // Warn on types where the user might conceivably expect to get all 16938 // specified bits as value bits: that's all integral types other than 16939 // 'bool'. 16940 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) { 16941 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 16942 << FieldName << toString(Value, 10) 16943 << (unsigned)TypeWidth; 16944 } 16945 } 16946 16947 return BitWidth; 16948 } 16949 16950 /// ActOnField - Each field of a C struct/union is passed into this in order 16951 /// to create a FieldDecl object for it. 16952 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 16953 Declarator &D, Expr *BitfieldWidth) { 16954 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 16955 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 16956 /*InitStyle=*/ICIS_NoInit, AS_public); 16957 return Res; 16958 } 16959 16960 /// HandleField - Analyze a field of a C struct or a C++ data member. 16961 /// 16962 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 16963 SourceLocation DeclStart, 16964 Declarator &D, Expr *BitWidth, 16965 InClassInitStyle InitStyle, 16966 AccessSpecifier AS) { 16967 if (D.isDecompositionDeclarator()) { 16968 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 16969 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 16970 << Decomp.getSourceRange(); 16971 return nullptr; 16972 } 16973 16974 IdentifierInfo *II = D.getIdentifier(); 16975 SourceLocation Loc = DeclStart; 16976 if (II) Loc = D.getIdentifierLoc(); 16977 16978 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16979 QualType T = TInfo->getType(); 16980 if (getLangOpts().CPlusPlus) { 16981 CheckExtraCXXDefaultArguments(D); 16982 16983 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 16984 UPPC_DataMemberType)) { 16985 D.setInvalidType(); 16986 T = Context.IntTy; 16987 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 16988 } 16989 } 16990 16991 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 16992 16993 if (D.getDeclSpec().isInlineSpecified()) 16994 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 16995 << getLangOpts().CPlusPlus17; 16996 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 16997 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 16998 diag::err_invalid_thread) 16999 << DeclSpec::getSpecifierName(TSCS); 17000 17001 // Check to see if this name was declared as a member previously 17002 NamedDecl *PrevDecl = nullptr; 17003 LookupResult Previous(*this, II, Loc, LookupMemberName, 17004 ForVisibleRedeclaration); 17005 LookupName(Previous, S); 17006 switch (Previous.getResultKind()) { 17007 case LookupResult::Found: 17008 case LookupResult::FoundUnresolvedValue: 17009 PrevDecl = Previous.getAsSingle<NamedDecl>(); 17010 break; 17011 17012 case LookupResult::FoundOverloaded: 17013 PrevDecl = Previous.getRepresentativeDecl(); 17014 break; 17015 17016 case LookupResult::NotFound: 17017 case LookupResult::NotFoundInCurrentInstantiation: 17018 case LookupResult::Ambiguous: 17019 break; 17020 } 17021 Previous.suppressDiagnostics(); 17022 17023 if (PrevDecl && PrevDecl->isTemplateParameter()) { 17024 // Maybe we will complain about the shadowed template parameter. 17025 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 17026 // Just pretend that we didn't see the previous declaration. 17027 PrevDecl = nullptr; 17028 } 17029 17030 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 17031 PrevDecl = nullptr; 17032 17033 bool Mutable 17034 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 17035 SourceLocation TSSL = D.getBeginLoc(); 17036 FieldDecl *NewFD 17037 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 17038 TSSL, AS, PrevDecl, &D); 17039 17040 if (NewFD->isInvalidDecl()) 17041 Record->setInvalidDecl(); 17042 17043 if (D.getDeclSpec().isModulePrivateSpecified()) 17044 NewFD->setModulePrivate(); 17045 17046 if (NewFD->isInvalidDecl() && PrevDecl) { 17047 // Don't introduce NewFD into scope; there's already something 17048 // with the same name in the same scope. 17049 } else if (II) { 17050 PushOnScopeChains(NewFD, S); 17051 } else 17052 Record->addDecl(NewFD); 17053 17054 return NewFD; 17055 } 17056 17057 /// Build a new FieldDecl and check its well-formedness. 17058 /// 17059 /// This routine builds a new FieldDecl given the fields name, type, 17060 /// record, etc. \p PrevDecl should refer to any previous declaration 17061 /// with the same name and in the same scope as the field to be 17062 /// created. 17063 /// 17064 /// \returns a new FieldDecl. 17065 /// 17066 /// \todo The Declarator argument is a hack. It will be removed once 17067 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 17068 TypeSourceInfo *TInfo, 17069 RecordDecl *Record, SourceLocation Loc, 17070 bool Mutable, Expr *BitWidth, 17071 InClassInitStyle InitStyle, 17072 SourceLocation TSSL, 17073 AccessSpecifier AS, NamedDecl *PrevDecl, 17074 Declarator *D) { 17075 IdentifierInfo *II = Name.getAsIdentifierInfo(); 17076 bool InvalidDecl = false; 17077 if (D) InvalidDecl = D->isInvalidType(); 17078 17079 // If we receive a broken type, recover by assuming 'int' and 17080 // marking this declaration as invalid. 17081 if (T.isNull() || T->containsErrors()) { 17082 InvalidDecl = true; 17083 T = Context.IntTy; 17084 } 17085 17086 QualType EltTy = Context.getBaseElementType(T); 17087 if (!EltTy->isDependentType() && !EltTy->containsErrors()) { 17088 if (RequireCompleteSizedType(Loc, EltTy, 17089 diag::err_field_incomplete_or_sizeless)) { 17090 // Fields of incomplete type force their record to be invalid. 17091 Record->setInvalidDecl(); 17092 InvalidDecl = true; 17093 } else { 17094 NamedDecl *Def; 17095 EltTy->isIncompleteType(&Def); 17096 if (Def && Def->isInvalidDecl()) { 17097 Record->setInvalidDecl(); 17098 InvalidDecl = true; 17099 } 17100 } 17101 } 17102 17103 // TR 18037 does not allow fields to be declared with address space 17104 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() || 17105 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { 17106 Diag(Loc, diag::err_field_with_address_space); 17107 Record->setInvalidDecl(); 17108 InvalidDecl = true; 17109 } 17110 17111 if (LangOpts.OpenCL) { 17112 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 17113 // used as structure or union field: image, sampler, event or block types. 17114 if (T->isEventT() || T->isImageType() || T->isSamplerT() || 17115 T->isBlockPointerType()) { 17116 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 17117 Record->setInvalidDecl(); 17118 InvalidDecl = true; 17119 } 17120 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension 17121 // is enabled. 17122 if (BitWidth && !getOpenCLOptions().isAvailableOption( 17123 "__cl_clang_bitfields", LangOpts)) { 17124 Diag(Loc, diag::err_opencl_bitfields); 17125 InvalidDecl = true; 17126 } 17127 } 17128 17129 // Anonymous bit-fields cannot be cv-qualified (CWG 2229). 17130 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && 17131 T.hasQualifiers()) { 17132 InvalidDecl = true; 17133 Diag(Loc, diag::err_anon_bitfield_qualifiers); 17134 } 17135 17136 // C99 6.7.2.1p8: A member of a structure or union may have any type other 17137 // than a variably modified type. 17138 if (!InvalidDecl && T->isVariablyModifiedType()) { 17139 if (!tryToFixVariablyModifiedVarType( 17140 TInfo, T, Loc, diag::err_typecheck_field_variable_size)) 17141 InvalidDecl = true; 17142 } 17143 17144 // Fields can not have abstract class types 17145 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 17146 diag::err_abstract_type_in_decl, 17147 AbstractFieldType)) 17148 InvalidDecl = true; 17149 17150 bool ZeroWidth = false; 17151 if (InvalidDecl) 17152 BitWidth = nullptr; 17153 // If this is declared as a bit-field, check the bit-field. 17154 if (BitWidth) { 17155 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 17156 &ZeroWidth).get(); 17157 if (!BitWidth) { 17158 InvalidDecl = true; 17159 BitWidth = nullptr; 17160 ZeroWidth = false; 17161 } 17162 } 17163 17164 // Check that 'mutable' is consistent with the type of the declaration. 17165 if (!InvalidDecl && Mutable) { 17166 unsigned DiagID = 0; 17167 if (T->isReferenceType()) 17168 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 17169 : diag::err_mutable_reference; 17170 else if (T.isConstQualified()) 17171 DiagID = diag::err_mutable_const; 17172 17173 if (DiagID) { 17174 SourceLocation ErrLoc = Loc; 17175 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 17176 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 17177 Diag(ErrLoc, DiagID); 17178 if (DiagID != diag::ext_mutable_reference) { 17179 Mutable = false; 17180 InvalidDecl = true; 17181 } 17182 } 17183 } 17184 17185 // C++11 [class.union]p8 (DR1460): 17186 // At most one variant member of a union may have a 17187 // brace-or-equal-initializer. 17188 if (InitStyle != ICIS_NoInit) 17189 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 17190 17191 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 17192 BitWidth, Mutable, InitStyle); 17193 if (InvalidDecl) 17194 NewFD->setInvalidDecl(); 17195 17196 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 17197 Diag(Loc, diag::err_duplicate_member) << II; 17198 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 17199 NewFD->setInvalidDecl(); 17200 } 17201 17202 if (!InvalidDecl && getLangOpts().CPlusPlus) { 17203 if (Record->isUnion()) { 17204 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 17205 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 17206 if (RDecl->getDefinition()) { 17207 // C++ [class.union]p1: An object of a class with a non-trivial 17208 // constructor, a non-trivial copy constructor, a non-trivial 17209 // destructor, or a non-trivial copy assignment operator 17210 // cannot be a member of a union, nor can an array of such 17211 // objects. 17212 if (CheckNontrivialField(NewFD)) 17213 NewFD->setInvalidDecl(); 17214 } 17215 } 17216 17217 // C++ [class.union]p1: If a union contains a member of reference type, 17218 // the program is ill-formed, except when compiling with MSVC extensions 17219 // enabled. 17220 if (EltTy->isReferenceType()) { 17221 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 17222 diag::ext_union_member_of_reference_type : 17223 diag::err_union_member_of_reference_type) 17224 << NewFD->getDeclName() << EltTy; 17225 if (!getLangOpts().MicrosoftExt) 17226 NewFD->setInvalidDecl(); 17227 } 17228 } 17229 } 17230 17231 // FIXME: We need to pass in the attributes given an AST 17232 // representation, not a parser representation. 17233 if (D) { 17234 // FIXME: The current scope is almost... but not entirely... correct here. 17235 ProcessDeclAttributes(getCurScope(), NewFD, *D); 17236 17237 if (NewFD->hasAttrs()) 17238 CheckAlignasUnderalignment(NewFD); 17239 } 17240 17241 // In auto-retain/release, infer strong retension for fields of 17242 // retainable type. 17243 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 17244 NewFD->setInvalidDecl(); 17245 17246 if (T.isObjCGCWeak()) 17247 Diag(Loc, diag::warn_attribute_weak_on_field); 17248 17249 // PPC MMA non-pointer types are not allowed as field types. 17250 if (Context.getTargetInfo().getTriple().isPPC64() && 17251 CheckPPCMMAType(T, NewFD->getLocation())) 17252 NewFD->setInvalidDecl(); 17253 17254 NewFD->setAccess(AS); 17255 return NewFD; 17256 } 17257 17258 bool Sema::CheckNontrivialField(FieldDecl *FD) { 17259 assert(FD); 17260 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 17261 17262 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 17263 return false; 17264 17265 QualType EltTy = Context.getBaseElementType(FD->getType()); 17266 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 17267 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 17268 if (RDecl->getDefinition()) { 17269 // We check for copy constructors before constructors 17270 // because otherwise we'll never get complaints about 17271 // copy constructors. 17272 17273 CXXSpecialMember member = CXXInvalid; 17274 // We're required to check for any non-trivial constructors. Since the 17275 // implicit default constructor is suppressed if there are any 17276 // user-declared constructors, we just need to check that there is a 17277 // trivial default constructor and a trivial copy constructor. (We don't 17278 // worry about move constructors here, since this is a C++98 check.) 17279 if (RDecl->hasNonTrivialCopyConstructor()) 17280 member = CXXCopyConstructor; 17281 else if (!RDecl->hasTrivialDefaultConstructor()) 17282 member = CXXDefaultConstructor; 17283 else if (RDecl->hasNonTrivialCopyAssignment()) 17284 member = CXXCopyAssignment; 17285 else if (RDecl->hasNonTrivialDestructor()) 17286 member = CXXDestructor; 17287 17288 if (member != CXXInvalid) { 17289 if (!getLangOpts().CPlusPlus11 && 17290 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 17291 // Objective-C++ ARC: it is an error to have a non-trivial field of 17292 // a union. However, system headers in Objective-C programs 17293 // occasionally have Objective-C lifetime objects within unions, 17294 // and rather than cause the program to fail, we make those 17295 // members unavailable. 17296 SourceLocation Loc = FD->getLocation(); 17297 if (getSourceManager().isInSystemHeader(Loc)) { 17298 if (!FD->hasAttr<UnavailableAttr>()) 17299 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 17300 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 17301 return false; 17302 } 17303 } 17304 17305 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 17306 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 17307 diag::err_illegal_union_or_anon_struct_member) 17308 << FD->getParent()->isUnion() << FD->getDeclName() << member; 17309 DiagnoseNontrivial(RDecl, member); 17310 return !getLangOpts().CPlusPlus11; 17311 } 17312 } 17313 } 17314 17315 return false; 17316 } 17317 17318 /// TranslateIvarVisibility - Translate visibility from a token ID to an 17319 /// AST enum value. 17320 static ObjCIvarDecl::AccessControl 17321 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 17322 switch (ivarVisibility) { 17323 default: llvm_unreachable("Unknown visitibility kind"); 17324 case tok::objc_private: return ObjCIvarDecl::Private; 17325 case tok::objc_public: return ObjCIvarDecl::Public; 17326 case tok::objc_protected: return ObjCIvarDecl::Protected; 17327 case tok::objc_package: return ObjCIvarDecl::Package; 17328 } 17329 } 17330 17331 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 17332 /// in order to create an IvarDecl object for it. 17333 Decl *Sema::ActOnIvar(Scope *S, 17334 SourceLocation DeclStart, 17335 Declarator &D, Expr *BitfieldWidth, 17336 tok::ObjCKeywordKind Visibility) { 17337 17338 IdentifierInfo *II = D.getIdentifier(); 17339 Expr *BitWidth = (Expr*)BitfieldWidth; 17340 SourceLocation Loc = DeclStart; 17341 if (II) Loc = D.getIdentifierLoc(); 17342 17343 // FIXME: Unnamed fields can be handled in various different ways, for 17344 // example, unnamed unions inject all members into the struct namespace! 17345 17346 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 17347 QualType T = TInfo->getType(); 17348 17349 if (BitWidth) { 17350 // 6.7.2.1p3, 6.7.2.1p4 17351 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 17352 if (!BitWidth) 17353 D.setInvalidType(); 17354 } else { 17355 // Not a bitfield. 17356 17357 // validate II. 17358 17359 } 17360 if (T->isReferenceType()) { 17361 Diag(Loc, diag::err_ivar_reference_type); 17362 D.setInvalidType(); 17363 } 17364 // C99 6.7.2.1p8: A member of a structure or union may have any type other 17365 // than a variably modified type. 17366 else if (T->isVariablyModifiedType()) { 17367 if (!tryToFixVariablyModifiedVarType( 17368 TInfo, T, Loc, diag::err_typecheck_ivar_variable_size)) 17369 D.setInvalidType(); 17370 } 17371 17372 // Get the visibility (access control) for this ivar. 17373 ObjCIvarDecl::AccessControl ac = 17374 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 17375 : ObjCIvarDecl::None; 17376 // Must set ivar's DeclContext to its enclosing interface. 17377 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 17378 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 17379 return nullptr; 17380 ObjCContainerDecl *EnclosingContext; 17381 if (ObjCImplementationDecl *IMPDecl = 17382 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 17383 if (LangOpts.ObjCRuntime.isFragile()) { 17384 // Case of ivar declared in an implementation. Context is that of its class. 17385 EnclosingContext = IMPDecl->getClassInterface(); 17386 assert(EnclosingContext && "Implementation has no class interface!"); 17387 } 17388 else 17389 EnclosingContext = EnclosingDecl; 17390 } else { 17391 if (ObjCCategoryDecl *CDecl = 17392 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 17393 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 17394 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 17395 return nullptr; 17396 } 17397 } 17398 EnclosingContext = EnclosingDecl; 17399 } 17400 17401 // Construct the decl. 17402 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 17403 DeclStart, Loc, II, T, 17404 TInfo, ac, (Expr *)BitfieldWidth); 17405 17406 if (II) { 17407 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 17408 ForVisibleRedeclaration); 17409 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 17410 && !isa<TagDecl>(PrevDecl)) { 17411 Diag(Loc, diag::err_duplicate_member) << II; 17412 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 17413 NewID->setInvalidDecl(); 17414 } 17415 } 17416 17417 // Process attributes attached to the ivar. 17418 ProcessDeclAttributes(S, NewID, D); 17419 17420 if (D.isInvalidType()) 17421 NewID->setInvalidDecl(); 17422 17423 // In ARC, infer 'retaining' for ivars of retainable type. 17424 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 17425 NewID->setInvalidDecl(); 17426 17427 if (D.getDeclSpec().isModulePrivateSpecified()) 17428 NewID->setModulePrivate(); 17429 17430 if (II) { 17431 // FIXME: When interfaces are DeclContexts, we'll need to add 17432 // these to the interface. 17433 S->AddDecl(NewID); 17434 IdResolver.AddDecl(NewID); 17435 } 17436 17437 if (LangOpts.ObjCRuntime.isNonFragile() && 17438 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 17439 Diag(Loc, diag::warn_ivars_in_interface); 17440 17441 return NewID; 17442 } 17443 17444 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 17445 /// class and class extensions. For every class \@interface and class 17446 /// extension \@interface, if the last ivar is a bitfield of any type, 17447 /// then add an implicit `char :0` ivar to the end of that interface. 17448 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 17449 SmallVectorImpl<Decl *> &AllIvarDecls) { 17450 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 17451 return; 17452 17453 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 17454 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 17455 17456 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) 17457 return; 17458 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 17459 if (!ID) { 17460 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 17461 if (!CD->IsClassExtension()) 17462 return; 17463 } 17464 // No need to add this to end of @implementation. 17465 else 17466 return; 17467 } 17468 // All conditions are met. Add a new bitfield to the tail end of ivars. 17469 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 17470 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 17471 17472 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 17473 DeclLoc, DeclLoc, nullptr, 17474 Context.CharTy, 17475 Context.getTrivialTypeSourceInfo(Context.CharTy, 17476 DeclLoc), 17477 ObjCIvarDecl::Private, BW, 17478 true); 17479 AllIvarDecls.push_back(Ivar); 17480 } 17481 17482 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 17483 ArrayRef<Decl *> Fields, SourceLocation LBrac, 17484 SourceLocation RBrac, 17485 const ParsedAttributesView &Attrs) { 17486 assert(EnclosingDecl && "missing record or interface decl"); 17487 17488 // If this is an Objective-C @implementation or category and we have 17489 // new fields here we should reset the layout of the interface since 17490 // it will now change. 17491 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 17492 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 17493 switch (DC->getKind()) { 17494 default: break; 17495 case Decl::ObjCCategory: 17496 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 17497 break; 17498 case Decl::ObjCImplementation: 17499 Context. 17500 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 17501 break; 17502 } 17503 } 17504 17505 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 17506 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl); 17507 17508 // Start counting up the number of named members; make sure to include 17509 // members of anonymous structs and unions in the total. 17510 unsigned NumNamedMembers = 0; 17511 if (Record) { 17512 for (const auto *I : Record->decls()) { 17513 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 17514 if (IFD->getDeclName()) 17515 ++NumNamedMembers; 17516 } 17517 } 17518 17519 // Verify that all the fields are okay. 17520 SmallVector<FieldDecl*, 32> RecFields; 17521 17522 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 17523 i != end; ++i) { 17524 FieldDecl *FD = cast<FieldDecl>(*i); 17525 17526 // Get the type for the field. 17527 const Type *FDTy = FD->getType().getTypePtr(); 17528 17529 if (!FD->isAnonymousStructOrUnion()) { 17530 // Remember all fields written by the user. 17531 RecFields.push_back(FD); 17532 } 17533 17534 // If the field is already invalid for some reason, don't emit more 17535 // diagnostics about it. 17536 if (FD->isInvalidDecl()) { 17537 EnclosingDecl->setInvalidDecl(); 17538 continue; 17539 } 17540 17541 // C99 6.7.2.1p2: 17542 // A structure or union shall not contain a member with 17543 // incomplete or function type (hence, a structure shall not 17544 // contain an instance of itself, but may contain a pointer to 17545 // an instance of itself), except that the last member of a 17546 // structure with more than one named member may have incomplete 17547 // array type; such a structure (and any union containing, 17548 // possibly recursively, a member that is such a structure) 17549 // shall not be a member of a structure or an element of an 17550 // array. 17551 bool IsLastField = (i + 1 == Fields.end()); 17552 if (FDTy->isFunctionType()) { 17553 // Field declared as a function. 17554 Diag(FD->getLocation(), diag::err_field_declared_as_function) 17555 << FD->getDeclName(); 17556 FD->setInvalidDecl(); 17557 EnclosingDecl->setInvalidDecl(); 17558 continue; 17559 } else if (FDTy->isIncompleteArrayType() && 17560 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { 17561 if (Record) { 17562 // Flexible array member. 17563 // Microsoft and g++ is more permissive regarding flexible array. 17564 // It will accept flexible array in union and also 17565 // as the sole element of a struct/class. 17566 unsigned DiagID = 0; 17567 if (!Record->isUnion() && !IsLastField) { 17568 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) 17569 << FD->getDeclName() << FD->getType() << Record->getTagKind(); 17570 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); 17571 FD->setInvalidDecl(); 17572 EnclosingDecl->setInvalidDecl(); 17573 continue; 17574 } else if (Record->isUnion()) 17575 DiagID = getLangOpts().MicrosoftExt 17576 ? diag::ext_flexible_array_union_ms 17577 : getLangOpts().CPlusPlus 17578 ? diag::ext_flexible_array_union_gnu 17579 : diag::err_flexible_array_union; 17580 else if (NumNamedMembers < 1) 17581 DiagID = getLangOpts().MicrosoftExt 17582 ? diag::ext_flexible_array_empty_aggregate_ms 17583 : getLangOpts().CPlusPlus 17584 ? diag::ext_flexible_array_empty_aggregate_gnu 17585 : diag::err_flexible_array_empty_aggregate; 17586 17587 if (DiagID) 17588 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 17589 << Record->getTagKind(); 17590 // While the layout of types that contain virtual bases is not specified 17591 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 17592 // virtual bases after the derived members. This would make a flexible 17593 // array member declared at the end of an object not adjacent to the end 17594 // of the type. 17595 if (CXXRecord && CXXRecord->getNumVBases() != 0) 17596 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 17597 << FD->getDeclName() << Record->getTagKind(); 17598 if (!getLangOpts().C99) 17599 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 17600 << FD->getDeclName() << Record->getTagKind(); 17601 17602 // If the element type has a non-trivial destructor, we would not 17603 // implicitly destroy the elements, so disallow it for now. 17604 // 17605 // FIXME: GCC allows this. We should probably either implicitly delete 17606 // the destructor of the containing class, or just allow this. 17607 QualType BaseElem = Context.getBaseElementType(FD->getType()); 17608 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 17609 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 17610 << FD->getDeclName() << FD->getType(); 17611 FD->setInvalidDecl(); 17612 EnclosingDecl->setInvalidDecl(); 17613 continue; 17614 } 17615 // Okay, we have a legal flexible array member at the end of the struct. 17616 Record->setHasFlexibleArrayMember(true); 17617 } else { 17618 // In ObjCContainerDecl ivars with incomplete array type are accepted, 17619 // unless they are followed by another ivar. That check is done 17620 // elsewhere, after synthesized ivars are known. 17621 } 17622 } else if (!FDTy->isDependentType() && 17623 RequireCompleteSizedType( 17624 FD->getLocation(), FD->getType(), 17625 diag::err_field_incomplete_or_sizeless)) { 17626 // Incomplete type 17627 FD->setInvalidDecl(); 17628 EnclosingDecl->setInvalidDecl(); 17629 continue; 17630 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 17631 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 17632 // A type which contains a flexible array member is considered to be a 17633 // flexible array member. 17634 Record->setHasFlexibleArrayMember(true); 17635 if (!Record->isUnion()) { 17636 // If this is a struct/class and this is not the last element, reject 17637 // it. Note that GCC supports variable sized arrays in the middle of 17638 // structures. 17639 if (!IsLastField) 17640 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 17641 << FD->getDeclName() << FD->getType(); 17642 else { 17643 // We support flexible arrays at the end of structs in 17644 // other structs as an extension. 17645 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 17646 << FD->getDeclName(); 17647 } 17648 } 17649 } 17650 if (isa<ObjCContainerDecl>(EnclosingDecl) && 17651 RequireNonAbstractType(FD->getLocation(), FD->getType(), 17652 diag::err_abstract_type_in_decl, 17653 AbstractIvarType)) { 17654 // Ivars can not have abstract class types 17655 FD->setInvalidDecl(); 17656 } 17657 if (Record && FDTTy->getDecl()->hasObjectMember()) 17658 Record->setHasObjectMember(true); 17659 if (Record && FDTTy->getDecl()->hasVolatileMember()) 17660 Record->setHasVolatileMember(true); 17661 } else if (FDTy->isObjCObjectType()) { 17662 /// A field cannot be an Objective-c object 17663 Diag(FD->getLocation(), diag::err_statically_allocated_object) 17664 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 17665 QualType T = Context.getObjCObjectPointerType(FD->getType()); 17666 FD->setType(T); 17667 } else if (Record && Record->isUnion() && 17668 FD->getType().hasNonTrivialObjCLifetime() && 17669 getSourceManager().isInSystemHeader(FD->getLocation()) && 17670 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() && 17671 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong || 17672 !Context.hasDirectOwnershipQualifier(FD->getType()))) { 17673 // For backward compatibility, fields of C unions declared in system 17674 // headers that have non-trivial ObjC ownership qualifications are marked 17675 // as unavailable unless the qualifier is explicit and __strong. This can 17676 // break ABI compatibility between programs compiled with ARC and MRR, but 17677 // is a better option than rejecting programs using those unions under 17678 // ARC. 17679 FD->addAttr(UnavailableAttr::CreateImplicit( 17680 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, 17681 FD->getLocation())); 17682 } else if (getLangOpts().ObjC && 17683 getLangOpts().getGC() != LangOptions::NonGC && Record && 17684 !Record->hasObjectMember()) { 17685 if (FD->getType()->isObjCObjectPointerType() || 17686 FD->getType().isObjCGCStrong()) 17687 Record->setHasObjectMember(true); 17688 else if (Context.getAsArrayType(FD->getType())) { 17689 QualType BaseType = Context.getBaseElementType(FD->getType()); 17690 if (BaseType->isRecordType() && 17691 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember()) 17692 Record->setHasObjectMember(true); 17693 else if (BaseType->isObjCObjectPointerType() || 17694 BaseType.isObjCGCStrong()) 17695 Record->setHasObjectMember(true); 17696 } 17697 } 17698 17699 if (Record && !getLangOpts().CPlusPlus && 17700 !shouldIgnoreForRecordTriviality(FD)) { 17701 QualType FT = FD->getType(); 17702 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) { 17703 Record->setNonTrivialToPrimitiveDefaultInitialize(true); 17704 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 17705 Record->isUnion()) 17706 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true); 17707 } 17708 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); 17709 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) { 17710 Record->setNonTrivialToPrimitiveCopy(true); 17711 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion()) 17712 Record->setHasNonTrivialToPrimitiveCopyCUnion(true); 17713 } 17714 if (FT.isDestructedType()) { 17715 Record->setNonTrivialToPrimitiveDestroy(true); 17716 Record->setParamDestroyedInCallee(true); 17717 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion()) 17718 Record->setHasNonTrivialToPrimitiveDestructCUnion(true); 17719 } 17720 17721 if (const auto *RT = FT->getAs<RecordType>()) { 17722 if (RT->getDecl()->getArgPassingRestrictions() == 17723 RecordDecl::APK_CanNeverPassInRegs) 17724 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17725 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) 17726 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17727 } 17728 17729 if (Record && FD->getType().isVolatileQualified()) 17730 Record->setHasVolatileMember(true); 17731 // Keep track of the number of named members. 17732 if (FD->getIdentifier()) 17733 ++NumNamedMembers; 17734 } 17735 17736 // Okay, we successfully defined 'Record'. 17737 if (Record) { 17738 bool Completed = false; 17739 if (CXXRecord) { 17740 if (!CXXRecord->isInvalidDecl()) { 17741 // Set access bits correctly on the directly-declared conversions. 17742 for (CXXRecordDecl::conversion_iterator 17743 I = CXXRecord->conversion_begin(), 17744 E = CXXRecord->conversion_end(); I != E; ++I) 17745 I.setAccess((*I)->getAccess()); 17746 } 17747 17748 // Add any implicitly-declared members to this class. 17749 AddImplicitlyDeclaredMembersToClass(CXXRecord); 17750 17751 if (!CXXRecord->isDependentType()) { 17752 if (!CXXRecord->isInvalidDecl()) { 17753 // If we have virtual base classes, we may end up finding multiple 17754 // final overriders for a given virtual function. Check for this 17755 // problem now. 17756 if (CXXRecord->getNumVBases()) { 17757 CXXFinalOverriderMap FinalOverriders; 17758 CXXRecord->getFinalOverriders(FinalOverriders); 17759 17760 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 17761 MEnd = FinalOverriders.end(); 17762 M != MEnd; ++M) { 17763 for (OverridingMethods::iterator SO = M->second.begin(), 17764 SOEnd = M->second.end(); 17765 SO != SOEnd; ++SO) { 17766 assert(SO->second.size() > 0 && 17767 "Virtual function without overriding functions?"); 17768 if (SO->second.size() == 1) 17769 continue; 17770 17771 // C++ [class.virtual]p2: 17772 // In a derived class, if a virtual member function of a base 17773 // class subobject has more than one final overrider the 17774 // program is ill-formed. 17775 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 17776 << (const NamedDecl *)M->first << Record; 17777 Diag(M->first->getLocation(), 17778 diag::note_overridden_virtual_function); 17779 for (OverridingMethods::overriding_iterator 17780 OM = SO->second.begin(), 17781 OMEnd = SO->second.end(); 17782 OM != OMEnd; ++OM) 17783 Diag(OM->Method->getLocation(), diag::note_final_overrider) 17784 << (const NamedDecl *)M->first << OM->Method->getParent(); 17785 17786 Record->setInvalidDecl(); 17787 } 17788 } 17789 CXXRecord->completeDefinition(&FinalOverriders); 17790 Completed = true; 17791 } 17792 } 17793 } 17794 } 17795 17796 if (!Completed) 17797 Record->completeDefinition(); 17798 17799 // Handle attributes before checking the layout. 17800 ProcessDeclAttributeList(S, Record, Attrs); 17801 17802 // We may have deferred checking for a deleted destructor. Check now. 17803 if (CXXRecord) { 17804 auto *Dtor = CXXRecord->getDestructor(); 17805 if (Dtor && Dtor->isImplicit() && 17806 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { 17807 CXXRecord->setImplicitDestructorIsDeleted(); 17808 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 17809 } 17810 } 17811 17812 if (Record->hasAttrs()) { 17813 CheckAlignasUnderalignment(Record); 17814 17815 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 17816 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 17817 IA->getRange(), IA->getBestCase(), 17818 IA->getInheritanceModel()); 17819 } 17820 17821 // Check if the structure/union declaration is a type that can have zero 17822 // size in C. For C this is a language extension, for C++ it may cause 17823 // compatibility problems. 17824 bool CheckForZeroSize; 17825 if (!getLangOpts().CPlusPlus) { 17826 CheckForZeroSize = true; 17827 } else { 17828 // For C++ filter out types that cannot be referenced in C code. 17829 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 17830 CheckForZeroSize = 17831 CXXRecord->getLexicalDeclContext()->isExternCContext() && 17832 !CXXRecord->isDependentType() && !inTemplateInstantiation() && 17833 CXXRecord->isCLike(); 17834 } 17835 if (CheckForZeroSize) { 17836 bool ZeroSize = true; 17837 bool IsEmpty = true; 17838 unsigned NonBitFields = 0; 17839 for (RecordDecl::field_iterator I = Record->field_begin(), 17840 E = Record->field_end(); 17841 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 17842 IsEmpty = false; 17843 if (I->isUnnamedBitfield()) { 17844 if (!I->isZeroLengthBitField(Context)) 17845 ZeroSize = false; 17846 } else { 17847 ++NonBitFields; 17848 QualType FieldType = I->getType(); 17849 if (FieldType->isIncompleteType() || 17850 !Context.getTypeSizeInChars(FieldType).isZero()) 17851 ZeroSize = false; 17852 } 17853 } 17854 17855 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 17856 // allowed in C++, but warn if its declaration is inside 17857 // extern "C" block. 17858 if (ZeroSize) { 17859 Diag(RecLoc, getLangOpts().CPlusPlus ? 17860 diag::warn_zero_size_struct_union_in_extern_c : 17861 diag::warn_zero_size_struct_union_compat) 17862 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 17863 } 17864 17865 // Structs without named members are extension in C (C99 6.7.2.1p7), 17866 // but are accepted by GCC. 17867 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 17868 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 17869 diag::ext_no_named_members_in_struct_union) 17870 << Record->isUnion(); 17871 } 17872 } 17873 } else { 17874 ObjCIvarDecl **ClsFields = 17875 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 17876 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 17877 ID->setEndOfDefinitionLoc(RBrac); 17878 // Add ivar's to class's DeclContext. 17879 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17880 ClsFields[i]->setLexicalDeclContext(ID); 17881 ID->addDecl(ClsFields[i]); 17882 } 17883 // Must enforce the rule that ivars in the base classes may not be 17884 // duplicates. 17885 if (ID->getSuperClass()) 17886 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 17887 } else if (ObjCImplementationDecl *IMPDecl = 17888 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 17889 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 17890 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 17891 // Ivar declared in @implementation never belongs to the implementation. 17892 // Only it is in implementation's lexical context. 17893 ClsFields[I]->setLexicalDeclContext(IMPDecl); 17894 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 17895 IMPDecl->setIvarLBraceLoc(LBrac); 17896 IMPDecl->setIvarRBraceLoc(RBrac); 17897 } else if (ObjCCategoryDecl *CDecl = 17898 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 17899 // case of ivars in class extension; all other cases have been 17900 // reported as errors elsewhere. 17901 // FIXME. Class extension does not have a LocEnd field. 17902 // CDecl->setLocEnd(RBrac); 17903 // Add ivar's to class extension's DeclContext. 17904 // Diagnose redeclaration of private ivars. 17905 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 17906 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17907 if (IDecl) { 17908 if (const ObjCIvarDecl *ClsIvar = 17909 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 17910 Diag(ClsFields[i]->getLocation(), 17911 diag::err_duplicate_ivar_declaration); 17912 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 17913 continue; 17914 } 17915 for (const auto *Ext : IDecl->known_extensions()) { 17916 if (const ObjCIvarDecl *ClsExtIvar 17917 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 17918 Diag(ClsFields[i]->getLocation(), 17919 diag::err_duplicate_ivar_declaration); 17920 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 17921 continue; 17922 } 17923 } 17924 } 17925 ClsFields[i]->setLexicalDeclContext(CDecl); 17926 CDecl->addDecl(ClsFields[i]); 17927 } 17928 CDecl->setIvarLBraceLoc(LBrac); 17929 CDecl->setIvarRBraceLoc(RBrac); 17930 } 17931 } 17932 } 17933 17934 /// Determine whether the given integral value is representable within 17935 /// the given type T. 17936 static bool isRepresentableIntegerValue(ASTContext &Context, 17937 llvm::APSInt &Value, 17938 QualType T) { 17939 assert((T->isIntegralType(Context) || T->isEnumeralType()) && 17940 "Integral type required!"); 17941 unsigned BitWidth = Context.getIntWidth(T); 17942 17943 if (Value.isUnsigned() || Value.isNonNegative()) { 17944 if (T->isSignedIntegerOrEnumerationType()) 17945 --BitWidth; 17946 return Value.getActiveBits() <= BitWidth; 17947 } 17948 return Value.getMinSignedBits() <= BitWidth; 17949 } 17950 17951 // Given an integral type, return the next larger integral type 17952 // (or a NULL type of no such type exists). 17953 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 17954 // FIXME: Int128/UInt128 support, which also needs to be introduced into 17955 // enum checking below. 17956 assert((T->isIntegralType(Context) || 17957 T->isEnumeralType()) && "Integral type required!"); 17958 const unsigned NumTypes = 4; 17959 QualType SignedIntegralTypes[NumTypes] = { 17960 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 17961 }; 17962 QualType UnsignedIntegralTypes[NumTypes] = { 17963 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 17964 Context.UnsignedLongLongTy 17965 }; 17966 17967 unsigned BitWidth = Context.getTypeSize(T); 17968 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 17969 : UnsignedIntegralTypes; 17970 for (unsigned I = 0; I != NumTypes; ++I) 17971 if (Context.getTypeSize(Types[I]) > BitWidth) 17972 return Types[I]; 17973 17974 return QualType(); 17975 } 17976 17977 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 17978 EnumConstantDecl *LastEnumConst, 17979 SourceLocation IdLoc, 17980 IdentifierInfo *Id, 17981 Expr *Val) { 17982 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 17983 llvm::APSInt EnumVal(IntWidth); 17984 QualType EltTy; 17985 17986 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 17987 Val = nullptr; 17988 17989 if (Val) 17990 Val = DefaultLvalueConversion(Val).get(); 17991 17992 if (Val) { 17993 if (Enum->isDependentType() || Val->isTypeDependent() || 17994 Val->containsErrors()) 17995 EltTy = Context.DependentTy; 17996 else { 17997 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed 17998 // underlying type, but do allow it in all other contexts. 17999 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) { 18000 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 18001 // constant-expression in the enumerator-definition shall be a converted 18002 // constant expression of the underlying type. 18003 EltTy = Enum->getIntegerType(); 18004 ExprResult Converted = 18005 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 18006 CCEK_Enumerator); 18007 if (Converted.isInvalid()) 18008 Val = nullptr; 18009 else 18010 Val = Converted.get(); 18011 } else if (!Val->isValueDependent() && 18012 !(Val = 18013 VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold) 18014 .get())) { 18015 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 18016 } else { 18017 if (Enum->isComplete()) { 18018 EltTy = Enum->getIntegerType(); 18019 18020 // In Obj-C and Microsoft mode, require the enumeration value to be 18021 // representable in the underlying type of the enumeration. In C++11, 18022 // we perform a non-narrowing conversion as part of converted constant 18023 // expression checking. 18024 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 18025 if (Context.getTargetInfo() 18026 .getTriple() 18027 .isWindowsMSVCEnvironment()) { 18028 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 18029 } else { 18030 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 18031 } 18032 } 18033 18034 // Cast to the underlying type. 18035 Val = ImpCastExprToType(Val, EltTy, 18036 EltTy->isBooleanType() ? CK_IntegralToBoolean 18037 : CK_IntegralCast) 18038 .get(); 18039 } else if (getLangOpts().CPlusPlus) { 18040 // C++11 [dcl.enum]p5: 18041 // If the underlying type is not fixed, the type of each enumerator 18042 // is the type of its initializing value: 18043 // - If an initializer is specified for an enumerator, the 18044 // initializing value has the same type as the expression. 18045 EltTy = Val->getType(); 18046 } else { 18047 // C99 6.7.2.2p2: 18048 // The expression that defines the value of an enumeration constant 18049 // shall be an integer constant expression that has a value 18050 // representable as an int. 18051 18052 // Complain if the value is not representable in an int. 18053 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 18054 Diag(IdLoc, diag::ext_enum_value_not_int) 18055 << toString(EnumVal, 10) << Val->getSourceRange() 18056 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 18057 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 18058 // Force the type of the expression to 'int'. 18059 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 18060 } 18061 EltTy = Val->getType(); 18062 } 18063 } 18064 } 18065 } 18066 18067 if (!Val) { 18068 if (Enum->isDependentType()) 18069 EltTy = Context.DependentTy; 18070 else if (!LastEnumConst) { 18071 // C++0x [dcl.enum]p5: 18072 // If the underlying type is not fixed, the type of each enumerator 18073 // is the type of its initializing value: 18074 // - If no initializer is specified for the first enumerator, the 18075 // initializing value has an unspecified integral type. 18076 // 18077 // GCC uses 'int' for its unspecified integral type, as does 18078 // C99 6.7.2.2p3. 18079 if (Enum->isFixed()) { 18080 EltTy = Enum->getIntegerType(); 18081 } 18082 else { 18083 EltTy = Context.IntTy; 18084 } 18085 } else { 18086 // Assign the last value + 1. 18087 EnumVal = LastEnumConst->getInitVal(); 18088 ++EnumVal; 18089 EltTy = LastEnumConst->getType(); 18090 18091 // Check for overflow on increment. 18092 if (EnumVal < LastEnumConst->getInitVal()) { 18093 // C++0x [dcl.enum]p5: 18094 // If the underlying type is not fixed, the type of each enumerator 18095 // is the type of its initializing value: 18096 // 18097 // - Otherwise the type of the initializing value is the same as 18098 // the type of the initializing value of the preceding enumerator 18099 // unless the incremented value is not representable in that type, 18100 // in which case the type is an unspecified integral type 18101 // sufficient to contain the incremented value. If no such type 18102 // exists, the program is ill-formed. 18103 QualType T = getNextLargerIntegralType(Context, EltTy); 18104 if (T.isNull() || Enum->isFixed()) { 18105 // There is no integral type larger enough to represent this 18106 // value. Complain, then allow the value to wrap around. 18107 EnumVal = LastEnumConst->getInitVal(); 18108 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 18109 ++EnumVal; 18110 if (Enum->isFixed()) 18111 // When the underlying type is fixed, this is ill-formed. 18112 Diag(IdLoc, diag::err_enumerator_wrapped) 18113 << toString(EnumVal, 10) 18114 << EltTy; 18115 else 18116 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 18117 << toString(EnumVal, 10); 18118 } else { 18119 EltTy = T; 18120 } 18121 18122 // Retrieve the last enumerator's value, extent that type to the 18123 // type that is supposed to be large enough to represent the incremented 18124 // value, then increment. 18125 EnumVal = LastEnumConst->getInitVal(); 18126 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 18127 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 18128 ++EnumVal; 18129 18130 // If we're not in C++, diagnose the overflow of enumerator values, 18131 // which in C99 means that the enumerator value is not representable in 18132 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 18133 // permits enumerator values that are representable in some larger 18134 // integral type. 18135 if (!getLangOpts().CPlusPlus && !T.isNull()) 18136 Diag(IdLoc, diag::warn_enum_value_overflow); 18137 } else if (!getLangOpts().CPlusPlus && 18138 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 18139 // Enforce C99 6.7.2.2p2 even when we compute the next value. 18140 Diag(IdLoc, diag::ext_enum_value_not_int) 18141 << toString(EnumVal, 10) << 1; 18142 } 18143 } 18144 } 18145 18146 if (!EltTy->isDependentType()) { 18147 // Make the enumerator value match the signedness and size of the 18148 // enumerator's type. 18149 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 18150 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 18151 } 18152 18153 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 18154 Val, EnumVal); 18155 } 18156 18157 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 18158 SourceLocation IILoc) { 18159 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 18160 !getLangOpts().CPlusPlus) 18161 return SkipBodyInfo(); 18162 18163 // We have an anonymous enum definition. Look up the first enumerator to 18164 // determine if we should merge the definition with an existing one and 18165 // skip the body. 18166 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 18167 forRedeclarationInCurContext()); 18168 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 18169 if (!PrevECD) 18170 return SkipBodyInfo(); 18171 18172 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 18173 NamedDecl *Hidden; 18174 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 18175 SkipBodyInfo Skip; 18176 Skip.Previous = Hidden; 18177 return Skip; 18178 } 18179 18180 return SkipBodyInfo(); 18181 } 18182 18183 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 18184 SourceLocation IdLoc, IdentifierInfo *Id, 18185 const ParsedAttributesView &Attrs, 18186 SourceLocation EqualLoc, Expr *Val) { 18187 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 18188 EnumConstantDecl *LastEnumConst = 18189 cast_or_null<EnumConstantDecl>(lastEnumConst); 18190 18191 // The scope passed in may not be a decl scope. Zip up the scope tree until 18192 // we find one that is. 18193 S = getNonFieldDeclScope(S); 18194 18195 // Verify that there isn't already something declared with this name in this 18196 // scope. 18197 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration); 18198 LookupName(R, S); 18199 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>(); 18200 18201 if (PrevDecl && PrevDecl->isTemplateParameter()) { 18202 // Maybe we will complain about the shadowed template parameter. 18203 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 18204 // Just pretend that we didn't see the previous declaration. 18205 PrevDecl = nullptr; 18206 } 18207 18208 // C++ [class.mem]p15: 18209 // If T is the name of a class, then each of the following shall have a name 18210 // different from T: 18211 // - every enumerator of every member of class T that is an unscoped 18212 // enumerated type 18213 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) 18214 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 18215 DeclarationNameInfo(Id, IdLoc)); 18216 18217 EnumConstantDecl *New = 18218 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 18219 if (!New) 18220 return nullptr; 18221 18222 if (PrevDecl) { 18223 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) { 18224 // Check for other kinds of shadowing not already handled. 18225 CheckShadow(New, PrevDecl, R); 18226 } 18227 18228 // When in C++, we may get a TagDecl with the same name; in this case the 18229 // enum constant will 'hide' the tag. 18230 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 18231 "Received TagDecl when not in C++!"); 18232 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 18233 if (isa<EnumConstantDecl>(PrevDecl)) 18234 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 18235 else 18236 Diag(IdLoc, diag::err_redefinition) << Id; 18237 notePreviousDefinition(PrevDecl, IdLoc); 18238 return nullptr; 18239 } 18240 } 18241 18242 // Process attributes. 18243 ProcessDeclAttributeList(S, New, Attrs); 18244 AddPragmaAttributes(S, New); 18245 18246 // Register this decl in the current scope stack. 18247 New->setAccess(TheEnumDecl->getAccess()); 18248 PushOnScopeChains(New, S); 18249 18250 ActOnDocumentableDecl(New); 18251 18252 return New; 18253 } 18254 18255 // Returns true when the enum initial expression does not trigger the 18256 // duplicate enum warning. A few common cases are exempted as follows: 18257 // Element2 = Element1 18258 // Element2 = Element1 + 1 18259 // Element2 = Element1 - 1 18260 // Where Element2 and Element1 are from the same enum. 18261 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 18262 Expr *InitExpr = ECD->getInitExpr(); 18263 if (!InitExpr) 18264 return true; 18265 InitExpr = InitExpr->IgnoreImpCasts(); 18266 18267 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 18268 if (!BO->isAdditiveOp()) 18269 return true; 18270 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 18271 if (!IL) 18272 return true; 18273 if (IL->getValue() != 1) 18274 return true; 18275 18276 InitExpr = BO->getLHS(); 18277 } 18278 18279 // This checks if the elements are from the same enum. 18280 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 18281 if (!DRE) 18282 return true; 18283 18284 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 18285 if (!EnumConstant) 18286 return true; 18287 18288 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 18289 Enum) 18290 return true; 18291 18292 return false; 18293 } 18294 18295 // Emits a warning when an element is implicitly set a value that 18296 // a previous element has already been set to. 18297 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 18298 EnumDecl *Enum, QualType EnumType) { 18299 // Avoid anonymous enums 18300 if (!Enum->getIdentifier()) 18301 return; 18302 18303 // Only check for small enums. 18304 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 18305 return; 18306 18307 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 18308 return; 18309 18310 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 18311 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; 18312 18313 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 18314 18315 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map. 18316 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap; 18317 18318 // Use int64_t as a key to avoid needing special handling for map keys. 18319 auto EnumConstantToKey = [](const EnumConstantDecl *D) { 18320 llvm::APSInt Val = D->getInitVal(); 18321 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); 18322 }; 18323 18324 DuplicatesVector DupVector; 18325 ValueToVectorMap EnumMap; 18326 18327 // Populate the EnumMap with all values represented by enum constants without 18328 // an initializer. 18329 for (auto *Element : Elements) { 18330 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); 18331 18332 // Null EnumConstantDecl means a previous diagnostic has been emitted for 18333 // this constant. Skip this enum since it may be ill-formed. 18334 if (!ECD) { 18335 return; 18336 } 18337 18338 // Constants with initalizers are handled in the next loop. 18339 if (ECD->getInitExpr()) 18340 continue; 18341 18342 // Duplicate values are handled in the next loop. 18343 EnumMap.insert({EnumConstantToKey(ECD), ECD}); 18344 } 18345 18346 if (EnumMap.size() == 0) 18347 return; 18348 18349 // Create vectors for any values that has duplicates. 18350 for (auto *Element : Elements) { 18351 // The last loop returned if any constant was null. 18352 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); 18353 if (!ValidDuplicateEnum(ECD, Enum)) 18354 continue; 18355 18356 auto Iter = EnumMap.find(EnumConstantToKey(ECD)); 18357 if (Iter == EnumMap.end()) 18358 continue; 18359 18360 DeclOrVector& Entry = Iter->second; 18361 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 18362 // Ensure constants are different. 18363 if (D == ECD) 18364 continue; 18365 18366 // Create new vector and push values onto it. 18367 auto Vec = std::make_unique<ECDVector>(); 18368 Vec->push_back(D); 18369 Vec->push_back(ECD); 18370 18371 // Update entry to point to the duplicates vector. 18372 Entry = Vec.get(); 18373 18374 // Store the vector somewhere we can consult later for quick emission of 18375 // diagnostics. 18376 DupVector.emplace_back(std::move(Vec)); 18377 continue; 18378 } 18379 18380 ECDVector *Vec = Entry.get<ECDVector*>(); 18381 // Make sure constants are not added more than once. 18382 if (*Vec->begin() == ECD) 18383 continue; 18384 18385 Vec->push_back(ECD); 18386 } 18387 18388 // Emit diagnostics. 18389 for (const auto &Vec : DupVector) { 18390 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 18391 18392 // Emit warning for one enum constant. 18393 auto *FirstECD = Vec->front(); 18394 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) 18395 << FirstECD << toString(FirstECD->getInitVal(), 10) 18396 << FirstECD->getSourceRange(); 18397 18398 // Emit one note for each of the remaining enum constants with 18399 // the same value. 18400 for (auto *ECD : llvm::drop_begin(*Vec)) 18401 S.Diag(ECD->getLocation(), diag::note_duplicate_element) 18402 << ECD << toString(ECD->getInitVal(), 10) 18403 << ECD->getSourceRange(); 18404 } 18405 } 18406 18407 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 18408 bool AllowMask) const { 18409 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 18410 assert(ED->isCompleteDefinition() && "expected enum definition"); 18411 18412 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 18413 llvm::APInt &FlagBits = R.first->second; 18414 18415 if (R.second) { 18416 for (auto *E : ED->enumerators()) { 18417 const auto &EVal = E->getInitVal(); 18418 // Only single-bit enumerators introduce new flag values. 18419 if (EVal.isPowerOf2()) 18420 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 18421 } 18422 } 18423 18424 // A value is in a flag enum if either its bits are a subset of the enum's 18425 // flag bits (the first condition) or we are allowing masks and the same is 18426 // true of its complement (the second condition). When masks are allowed, we 18427 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 18428 // 18429 // While it's true that any value could be used as a mask, the assumption is 18430 // that a mask will have all of the insignificant bits set. Anything else is 18431 // likely a logic error. 18432 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 18433 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 18434 } 18435 18436 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 18437 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S, 18438 const ParsedAttributesView &Attrs) { 18439 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 18440 QualType EnumType = Context.getTypeDeclType(Enum); 18441 18442 ProcessDeclAttributeList(S, Enum, Attrs); 18443 18444 if (Enum->isDependentType()) { 18445 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 18446 EnumConstantDecl *ECD = 18447 cast_or_null<EnumConstantDecl>(Elements[i]); 18448 if (!ECD) continue; 18449 18450 ECD->setType(EnumType); 18451 } 18452 18453 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 18454 return; 18455 } 18456 18457 // TODO: If the result value doesn't fit in an int, it must be a long or long 18458 // long value. ISO C does not support this, but GCC does as an extension, 18459 // emit a warning. 18460 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 18461 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 18462 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 18463 18464 // Verify that all the values are okay, compute the size of the values, and 18465 // reverse the list. 18466 unsigned NumNegativeBits = 0; 18467 unsigned NumPositiveBits = 0; 18468 18469 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 18470 EnumConstantDecl *ECD = 18471 cast_or_null<EnumConstantDecl>(Elements[i]); 18472 if (!ECD) continue; // Already issued a diagnostic. 18473 18474 const llvm::APSInt &InitVal = ECD->getInitVal(); 18475 18476 // Keep track of the size of positive and negative values. 18477 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 18478 NumPositiveBits = std::max(NumPositiveBits, 18479 (unsigned)InitVal.getActiveBits()); 18480 else 18481 NumNegativeBits = std::max(NumNegativeBits, 18482 (unsigned)InitVal.getMinSignedBits()); 18483 } 18484 18485 // Figure out the type that should be used for this enum. 18486 QualType BestType; 18487 unsigned BestWidth; 18488 18489 // C++0x N3000 [conv.prom]p3: 18490 // An rvalue of an unscoped enumeration type whose underlying 18491 // type is not fixed can be converted to an rvalue of the first 18492 // of the following types that can represent all the values of 18493 // the enumeration: int, unsigned int, long int, unsigned long 18494 // int, long long int, or unsigned long long int. 18495 // C99 6.4.4.3p2: 18496 // An identifier declared as an enumeration constant has type int. 18497 // The C99 rule is modified by a gcc extension 18498 QualType BestPromotionType; 18499 18500 bool Packed = Enum->hasAttr<PackedAttr>(); 18501 // -fshort-enums is the equivalent to specifying the packed attribute on all 18502 // enum definitions. 18503 if (LangOpts.ShortEnums) 18504 Packed = true; 18505 18506 // If the enum already has a type because it is fixed or dictated by the 18507 // target, promote that type instead of analyzing the enumerators. 18508 if (Enum->isComplete()) { 18509 BestType = Enum->getIntegerType(); 18510 if (BestType->isPromotableIntegerType()) 18511 BestPromotionType = Context.getPromotedIntegerType(BestType); 18512 else 18513 BestPromotionType = BestType; 18514 18515 BestWidth = Context.getIntWidth(BestType); 18516 } 18517 else if (NumNegativeBits) { 18518 // If there is a negative value, figure out the smallest integer type (of 18519 // int/long/longlong) that fits. 18520 // If it's packed, check also if it fits a char or a short. 18521 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 18522 BestType = Context.SignedCharTy; 18523 BestWidth = CharWidth; 18524 } else if (Packed && NumNegativeBits <= ShortWidth && 18525 NumPositiveBits < ShortWidth) { 18526 BestType = Context.ShortTy; 18527 BestWidth = ShortWidth; 18528 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 18529 BestType = Context.IntTy; 18530 BestWidth = IntWidth; 18531 } else { 18532 BestWidth = Context.getTargetInfo().getLongWidth(); 18533 18534 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 18535 BestType = Context.LongTy; 18536 } else { 18537 BestWidth = Context.getTargetInfo().getLongLongWidth(); 18538 18539 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 18540 Diag(Enum->getLocation(), diag::ext_enum_too_large); 18541 BestType = Context.LongLongTy; 18542 } 18543 } 18544 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 18545 } else { 18546 // If there is no negative value, figure out the smallest type that fits 18547 // all of the enumerator values. 18548 // If it's packed, check also if it fits a char or a short. 18549 if (Packed && NumPositiveBits <= CharWidth) { 18550 BestType = Context.UnsignedCharTy; 18551 BestPromotionType = Context.IntTy; 18552 BestWidth = CharWidth; 18553 } else if (Packed && NumPositiveBits <= ShortWidth) { 18554 BestType = Context.UnsignedShortTy; 18555 BestPromotionType = Context.IntTy; 18556 BestWidth = ShortWidth; 18557 } else if (NumPositiveBits <= IntWidth) { 18558 BestType = Context.UnsignedIntTy; 18559 BestWidth = IntWidth; 18560 BestPromotionType 18561 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18562 ? Context.UnsignedIntTy : Context.IntTy; 18563 } else if (NumPositiveBits <= 18564 (BestWidth = Context.getTargetInfo().getLongWidth())) { 18565 BestType = Context.UnsignedLongTy; 18566 BestPromotionType 18567 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18568 ? Context.UnsignedLongTy : Context.LongTy; 18569 } else { 18570 BestWidth = Context.getTargetInfo().getLongLongWidth(); 18571 assert(NumPositiveBits <= BestWidth && 18572 "How could an initializer get larger than ULL?"); 18573 BestType = Context.UnsignedLongLongTy; 18574 BestPromotionType 18575 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18576 ? Context.UnsignedLongLongTy : Context.LongLongTy; 18577 } 18578 } 18579 18580 // Loop over all of the enumerator constants, changing their types to match 18581 // the type of the enum if needed. 18582 for (auto *D : Elements) { 18583 auto *ECD = cast_or_null<EnumConstantDecl>(D); 18584 if (!ECD) continue; // Already issued a diagnostic. 18585 18586 // Standard C says the enumerators have int type, but we allow, as an 18587 // extension, the enumerators to be larger than int size. If each 18588 // enumerator value fits in an int, type it as an int, otherwise type it the 18589 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 18590 // that X has type 'int', not 'unsigned'. 18591 18592 // Determine whether the value fits into an int. 18593 llvm::APSInt InitVal = ECD->getInitVal(); 18594 18595 // If it fits into an integer type, force it. Otherwise force it to match 18596 // the enum decl type. 18597 QualType NewTy; 18598 unsigned NewWidth; 18599 bool NewSign; 18600 if (!getLangOpts().CPlusPlus && 18601 !Enum->isFixed() && 18602 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 18603 NewTy = Context.IntTy; 18604 NewWidth = IntWidth; 18605 NewSign = true; 18606 } else if (ECD->getType() == BestType) { 18607 // Already the right type! 18608 if (getLangOpts().CPlusPlus) 18609 // C++ [dcl.enum]p4: Following the closing brace of an 18610 // enum-specifier, each enumerator has the type of its 18611 // enumeration. 18612 ECD->setType(EnumType); 18613 continue; 18614 } else { 18615 NewTy = BestType; 18616 NewWidth = BestWidth; 18617 NewSign = BestType->isSignedIntegerOrEnumerationType(); 18618 } 18619 18620 // Adjust the APSInt value. 18621 InitVal = InitVal.extOrTrunc(NewWidth); 18622 InitVal.setIsSigned(NewSign); 18623 ECD->setInitVal(InitVal); 18624 18625 // Adjust the Expr initializer and type. 18626 if (ECD->getInitExpr() && 18627 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 18628 ECD->setInitExpr(ImplicitCastExpr::Create( 18629 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(), 18630 /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride())); 18631 if (getLangOpts().CPlusPlus) 18632 // C++ [dcl.enum]p4: Following the closing brace of an 18633 // enum-specifier, each enumerator has the type of its 18634 // enumeration. 18635 ECD->setType(EnumType); 18636 else 18637 ECD->setType(NewTy); 18638 } 18639 18640 Enum->completeDefinition(BestType, BestPromotionType, 18641 NumPositiveBits, NumNegativeBits); 18642 18643 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 18644 18645 if (Enum->isClosedFlag()) { 18646 for (Decl *D : Elements) { 18647 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 18648 if (!ECD) continue; // Already issued a diagnostic. 18649 18650 llvm::APSInt InitVal = ECD->getInitVal(); 18651 if (InitVal != 0 && !InitVal.isPowerOf2() && 18652 !IsValueInFlagEnum(Enum, InitVal, true)) 18653 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 18654 << ECD << Enum; 18655 } 18656 } 18657 18658 // Now that the enum type is defined, ensure it's not been underaligned. 18659 if (Enum->hasAttrs()) 18660 CheckAlignasUnderalignment(Enum); 18661 } 18662 18663 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 18664 SourceLocation StartLoc, 18665 SourceLocation EndLoc) { 18666 StringLiteral *AsmString = cast<StringLiteral>(expr); 18667 18668 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 18669 AsmString, StartLoc, 18670 EndLoc); 18671 CurContext->addDecl(New); 18672 return New; 18673 } 18674 18675 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 18676 IdentifierInfo* AliasName, 18677 SourceLocation PragmaLoc, 18678 SourceLocation NameLoc, 18679 SourceLocation AliasNameLoc) { 18680 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 18681 LookupOrdinaryName); 18682 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc), 18683 AttributeCommonInfo::AS_Pragma); 18684 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit( 18685 Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info); 18686 18687 // If a declaration that: 18688 // 1) declares a function or a variable 18689 // 2) has external linkage 18690 // already exists, add a label attribute to it. 18691 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18692 if (isDeclExternC(PrevDecl)) 18693 PrevDecl->addAttr(Attr); 18694 else 18695 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 18696 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 18697 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 18698 } else 18699 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 18700 } 18701 18702 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 18703 SourceLocation PragmaLoc, 18704 SourceLocation NameLoc) { 18705 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 18706 18707 if (PrevDecl) { 18708 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma)); 18709 } else { 18710 (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc)); 18711 } 18712 } 18713 18714 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 18715 IdentifierInfo* AliasName, 18716 SourceLocation PragmaLoc, 18717 SourceLocation NameLoc, 18718 SourceLocation AliasNameLoc) { 18719 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 18720 LookupOrdinaryName); 18721 WeakInfo W = WeakInfo(Name, NameLoc); 18722 18723 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18724 if (!PrevDecl->hasAttr<AliasAttr>()) 18725 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 18726 DeclApplyPragmaWeak(TUScope, ND, W); 18727 } else { 18728 (void)WeakUndeclaredIdentifiers[AliasName].insert(W); 18729 } 18730 } 18731 18732 Decl *Sema::getObjCDeclContext() const { 18733 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 18734 } 18735 18736 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD, 18737 bool Final) { 18738 assert(FD && "Expected non-null FunctionDecl"); 18739 18740 // SYCL functions can be template, so we check if they have appropriate 18741 // attribute prior to checking if it is a template. 18742 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>()) 18743 return FunctionEmissionStatus::Emitted; 18744 18745 // Templates are emitted when they're instantiated. 18746 if (FD->isDependentContext()) 18747 return FunctionEmissionStatus::TemplateDiscarded; 18748 18749 // Check whether this function is an externally visible definition. 18750 auto IsEmittedForExternalSymbol = [this, FD]() { 18751 // We have to check the GVA linkage of the function's *definition* -- if we 18752 // only have a declaration, we don't know whether or not the function will 18753 // be emitted, because (say) the definition could include "inline". 18754 FunctionDecl *Def = FD->getDefinition(); 18755 18756 return Def && !isDiscardableGVALinkage( 18757 getASTContext().GetGVALinkageForFunction(Def)); 18758 }; 18759 18760 if (LangOpts.OpenMPIsDevice) { 18761 // In OpenMP device mode we will not emit host only functions, or functions 18762 // we don't need due to their linkage. 18763 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18764 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18765 // DevTy may be changed later by 18766 // #pragma omp declare target to(*) device_type(*). 18767 // Therefore DevTy having no value does not imply host. The emission status 18768 // will be checked again at the end of compilation unit with Final = true. 18769 if (DevTy.hasValue()) 18770 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host) 18771 return FunctionEmissionStatus::OMPDiscarded; 18772 // If we have an explicit value for the device type, or we are in a target 18773 // declare context, we need to emit all extern and used symbols. 18774 if (isInOpenMPDeclareTargetContext() || DevTy.hasValue()) 18775 if (IsEmittedForExternalSymbol()) 18776 return FunctionEmissionStatus::Emitted; 18777 // Device mode only emits what it must, if it wasn't tagged yet and needed, 18778 // we'll omit it. 18779 if (Final) 18780 return FunctionEmissionStatus::OMPDiscarded; 18781 } else if (LangOpts.OpenMP > 45) { 18782 // In OpenMP host compilation prior to 5.0 everything was an emitted host 18783 // function. In 5.0, no_host was introduced which might cause a function to 18784 // be ommitted. 18785 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18786 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18787 if (DevTy.hasValue()) 18788 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) 18789 return FunctionEmissionStatus::OMPDiscarded; 18790 } 18791 18792 if (Final && LangOpts.OpenMP && !LangOpts.CUDA) 18793 return FunctionEmissionStatus::Emitted; 18794 18795 if (LangOpts.CUDA) { 18796 // When compiling for device, host functions are never emitted. Similarly, 18797 // when compiling for host, device and global functions are never emitted. 18798 // (Technically, we do emit a host-side stub for global functions, but this 18799 // doesn't count for our purposes here.) 18800 Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD); 18801 if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host) 18802 return FunctionEmissionStatus::CUDADiscarded; 18803 if (!LangOpts.CUDAIsDevice && 18804 (T == Sema::CFT_Device || T == Sema::CFT_Global)) 18805 return FunctionEmissionStatus::CUDADiscarded; 18806 18807 if (IsEmittedForExternalSymbol()) 18808 return FunctionEmissionStatus::Emitted; 18809 } 18810 18811 // Otherwise, the function is known-emitted if it's in our set of 18812 // known-emitted functions. 18813 return FunctionEmissionStatus::Unknown; 18814 } 18815 18816 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) { 18817 // Host-side references to a __global__ function refer to the stub, so the 18818 // function itself is never emitted and therefore should not be marked. 18819 // If we have host fn calls kernel fn calls host+device, the HD function 18820 // does not get instantiated on the host. We model this by omitting at the 18821 // call to the kernel from the callgraph. This ensures that, when compiling 18822 // for host, only HD functions actually called from the host get marked as 18823 // known-emitted. 18824 return LangOpts.CUDA && !LangOpts.CUDAIsDevice && 18825 IdentifyCUDATarget(Callee) == CFT_Global; 18826 } 18827