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/Randstruct.h" 28 #include "clang/AST/StmtCXX.h" 29 #include "clang/Basic/Builtins.h" 30 #include "clang/Basic/PartialDiagnostic.h" 31 #include "clang/Basic/SourceManager.h" 32 #include "clang/Basic/TargetInfo.h" 33 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex 34 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 35 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex 36 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled() 37 #include "clang/Sema/CXXFieldCollector.h" 38 #include "clang/Sema/DeclSpec.h" 39 #include "clang/Sema/DelayedDiagnostic.h" 40 #include "clang/Sema/Initialization.h" 41 #include "clang/Sema/Lookup.h" 42 #include "clang/Sema/ParsedTemplate.h" 43 #include "clang/Sema/Scope.h" 44 #include "clang/Sema/ScopeInfo.h" 45 #include "clang/Sema/SemaInternal.h" 46 #include "clang/Sema/Template.h" 47 #include "llvm/ADT/SmallString.h" 48 #include "llvm/ADT/Triple.h" 49 #include <algorithm> 50 #include <cstring> 51 #include <functional> 52 #include <unordered_map> 53 54 using namespace clang; 55 using namespace sema; 56 57 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { 58 if (OwnedType) { 59 Decl *Group[2] = { OwnedType, Ptr }; 60 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); 61 } 62 63 return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); 64 } 65 66 namespace { 67 68 class TypeNameValidatorCCC final : public CorrectionCandidateCallback { 69 public: 70 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false, 71 bool AllowTemplates = false, 72 bool AllowNonTemplates = true) 73 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass), 74 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) { 75 WantExpressionKeywords = false; 76 WantCXXNamedCasts = false; 77 WantRemainingKeywords = false; 78 } 79 80 bool ValidateCandidate(const TypoCorrection &candidate) override { 81 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 82 if (!AllowInvalidDecl && ND->isInvalidDecl()) 83 return false; 84 85 if (getAsTypeTemplateDecl(ND)) 86 return AllowTemplates; 87 88 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 89 if (!IsType) 90 return false; 91 92 if (AllowNonTemplates) 93 return true; 94 95 // An injected-class-name of a class template (specialization) is valid 96 // as a template or as a non-template. 97 if (AllowTemplates) { 98 auto *RD = dyn_cast<CXXRecordDecl>(ND); 99 if (!RD || !RD->isInjectedClassName()) 100 return false; 101 RD = cast<CXXRecordDecl>(RD->getDeclContext()); 102 return RD->getDescribedClassTemplate() || 103 isa<ClassTemplateSpecializationDecl>(RD); 104 } 105 106 return false; 107 } 108 109 return !WantClassName && candidate.isKeyword(); 110 } 111 112 std::unique_ptr<CorrectionCandidateCallback> clone() override { 113 return std::make_unique<TypeNameValidatorCCC>(*this); 114 } 115 116 private: 117 bool AllowInvalidDecl; 118 bool WantClassName; 119 bool AllowTemplates; 120 bool AllowNonTemplates; 121 }; 122 123 } // end anonymous namespace 124 125 /// Determine whether the token kind starts a simple-type-specifier. 126 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { 127 switch (Kind) { 128 // FIXME: Take into account the current language when deciding whether a 129 // token kind is a valid type specifier 130 case tok::kw_short: 131 case tok::kw_long: 132 case tok::kw___int64: 133 case tok::kw___int128: 134 case tok::kw_signed: 135 case tok::kw_unsigned: 136 case tok::kw_void: 137 case tok::kw_char: 138 case tok::kw_int: 139 case tok::kw_half: 140 case tok::kw_float: 141 case tok::kw_double: 142 case tok::kw___bf16: 143 case tok::kw__Float16: 144 case tok::kw___float128: 145 case tok::kw___ibm128: 146 case tok::kw_wchar_t: 147 case tok::kw_bool: 148 case tok::kw___underlying_type: 149 case tok::kw___auto_type: 150 return true; 151 152 case tok::annot_typename: 153 case tok::kw_char16_t: 154 case tok::kw_char32_t: 155 case tok::kw_typeof: 156 case tok::annot_decltype: 157 case tok::kw_decltype: 158 return getLangOpts().CPlusPlus; 159 160 case tok::kw_char8_t: 161 return getLangOpts().Char8; 162 163 default: 164 break; 165 } 166 167 return false; 168 } 169 170 namespace { 171 enum class UnqualifiedTypeNameLookupResult { 172 NotFound, 173 FoundNonType, 174 FoundType 175 }; 176 } // end anonymous namespace 177 178 /// Tries to perform unqualified lookup of the type decls in bases for 179 /// dependent class. 180 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a 181 /// type decl, \a FoundType if only type decls are found. 182 static UnqualifiedTypeNameLookupResult 183 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, 184 SourceLocation NameLoc, 185 const CXXRecordDecl *RD) { 186 if (!RD->hasDefinition()) 187 return UnqualifiedTypeNameLookupResult::NotFound; 188 // Look for type decls in base classes. 189 UnqualifiedTypeNameLookupResult FoundTypeDecl = 190 UnqualifiedTypeNameLookupResult::NotFound; 191 for (const auto &Base : RD->bases()) { 192 const CXXRecordDecl *BaseRD = nullptr; 193 if (auto *BaseTT = Base.getType()->getAs<TagType>()) 194 BaseRD = BaseTT->getAsCXXRecordDecl(); 195 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { 196 // Look for type decls in dependent base classes that have known primary 197 // templates. 198 if (!TST || !TST->isDependentType()) 199 continue; 200 auto *TD = TST->getTemplateName().getAsTemplateDecl(); 201 if (!TD) 202 continue; 203 if (auto *BasePrimaryTemplate = 204 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) { 205 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl()) 206 BaseRD = BasePrimaryTemplate; 207 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) { 208 if (const ClassTemplatePartialSpecializationDecl *PS = 209 CTD->findPartialSpecialization(Base.getType())) 210 if (PS->getCanonicalDecl() != RD->getCanonicalDecl()) 211 BaseRD = PS; 212 } 213 } 214 } 215 if (BaseRD) { 216 for (NamedDecl *ND : BaseRD->lookup(&II)) { 217 if (!isa<TypeDecl>(ND)) 218 return UnqualifiedTypeNameLookupResult::FoundNonType; 219 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 220 } 221 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { 222 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { 223 case UnqualifiedTypeNameLookupResult::FoundNonType: 224 return UnqualifiedTypeNameLookupResult::FoundNonType; 225 case UnqualifiedTypeNameLookupResult::FoundType: 226 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 227 break; 228 case UnqualifiedTypeNameLookupResult::NotFound: 229 break; 230 } 231 } 232 } 233 } 234 235 return FoundTypeDecl; 236 } 237 238 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, 239 const IdentifierInfo &II, 240 SourceLocation NameLoc) { 241 // Lookup in the parent class template context, if any. 242 const CXXRecordDecl *RD = nullptr; 243 UnqualifiedTypeNameLookupResult FoundTypeDecl = 244 UnqualifiedTypeNameLookupResult::NotFound; 245 for (DeclContext *DC = S.CurContext; 246 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; 247 DC = DC->getParent()) { 248 // Look for type decls in dependent base classes that have known primary 249 // templates. 250 RD = dyn_cast<CXXRecordDecl>(DC); 251 if (RD && RD->getDescribedClassTemplate()) 252 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); 253 } 254 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) 255 return nullptr; 256 257 // We found some types in dependent base classes. Recover as if the user 258 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the 259 // lookup during template instantiation. 260 S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II; 261 262 ASTContext &Context = S.Context; 263 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, 264 cast<Type>(Context.getRecordType(RD))); 265 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); 266 267 CXXScopeSpec SS; 268 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 269 270 TypeLocBuilder Builder; 271 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 272 DepTL.setNameLoc(NameLoc); 273 DepTL.setElaboratedKeywordLoc(SourceLocation()); 274 DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); 275 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 276 } 277 278 /// If the identifier refers to a type name within this scope, 279 /// return the declaration of that type. 280 /// 281 /// This routine performs ordinary name lookup of the identifier II 282 /// within the given scope, with optional C++ scope specifier SS, to 283 /// determine whether the name refers to a type. If so, returns an 284 /// opaque pointer (actually a QualType) corresponding to that 285 /// type. Otherwise, returns NULL. 286 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 287 Scope *S, CXXScopeSpec *SS, 288 bool isClassName, bool HasTrailingDot, 289 ParsedType ObjectTypePtr, 290 bool IsCtorOrDtorName, 291 bool WantNontrivialTypeSourceInfo, 292 bool IsClassTemplateDeductionContext, 293 IdentifierInfo **CorrectedII) { 294 // FIXME: Consider allowing this outside C++1z mode as an extension. 295 bool AllowDeducedTemplate = IsClassTemplateDeductionContext && 296 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName && 297 !isClassName && !HasTrailingDot; 298 299 // Determine where we will perform name lookup. 300 DeclContext *LookupCtx = nullptr; 301 if (ObjectTypePtr) { 302 QualType ObjectType = ObjectTypePtr.get(); 303 if (ObjectType->isRecordType()) 304 LookupCtx = computeDeclContext(ObjectType); 305 } else if (SS && SS->isNotEmpty()) { 306 LookupCtx = computeDeclContext(*SS, false); 307 308 if (!LookupCtx) { 309 if (isDependentScopeSpecifier(*SS)) { 310 // C++ [temp.res]p3: 311 // A qualified-id that refers to a type and in which the 312 // nested-name-specifier depends on a template-parameter (14.6.2) 313 // shall be prefixed by the keyword typename to indicate that the 314 // qualified-id denotes a type, forming an 315 // elaborated-type-specifier (7.1.5.3). 316 // 317 // We therefore do not perform any name lookup if the result would 318 // refer to a member of an unknown specialization. 319 if (!isClassName && !IsCtorOrDtorName) 320 return nullptr; 321 322 // We know from the grammar that this name refers to a type, 323 // so build a dependent node to describe the type. 324 if (WantNontrivialTypeSourceInfo) 325 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 326 327 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 328 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 329 II, NameLoc); 330 return ParsedType::make(T); 331 } 332 333 return nullptr; 334 } 335 336 if (!LookupCtx->isDependentContext() && 337 RequireCompleteDeclContext(*SS, LookupCtx)) 338 return nullptr; 339 } 340 341 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 342 // lookup for class-names. 343 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 344 LookupOrdinaryName; 345 LookupResult Result(*this, &II, NameLoc, Kind); 346 if (LookupCtx) { 347 // Perform "qualified" name lookup into the declaration context we 348 // computed, which is either the type of the base of a member access 349 // expression or the declaration context associated with a prior 350 // nested-name-specifier. 351 LookupQualifiedName(Result, LookupCtx); 352 353 if (ObjectTypePtr && Result.empty()) { 354 // C++ [basic.lookup.classref]p3: 355 // If the unqualified-id is ~type-name, the type-name is looked up 356 // in the context of the entire postfix-expression. If the type T of 357 // the object expression is of a class type C, the type-name is also 358 // looked up in the scope of class C. At least one of the lookups shall 359 // find a name that refers to (possibly cv-qualified) T. 360 LookupName(Result, S); 361 } 362 } else { 363 // Perform unqualified name lookup. 364 LookupName(Result, S); 365 366 // For unqualified lookup in a class template in MSVC mode, look into 367 // dependent base classes where the primary class template is known. 368 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { 369 if (ParsedType TypeInBase = 370 recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) 371 return TypeInBase; 372 } 373 } 374 375 NamedDecl *IIDecl = nullptr; 376 UsingShadowDecl *FoundUsingShadow = nullptr; 377 switch (Result.getResultKind()) { 378 case LookupResult::NotFound: 379 case LookupResult::NotFoundInCurrentInstantiation: 380 if (CorrectedII) { 381 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName, 382 AllowDeducedTemplate); 383 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind, 384 S, SS, CCC, CTK_ErrorRecovery); 385 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 386 TemplateTy Template; 387 bool MemberOfUnknownSpecialization; 388 UnqualifiedId TemplateName; 389 TemplateName.setIdentifier(NewII, NameLoc); 390 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 391 CXXScopeSpec NewSS, *NewSSPtr = SS; 392 if (SS && NNS) { 393 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 394 NewSSPtr = &NewSS; 395 } 396 if (Correction && (NNS || NewII != &II) && 397 // Ignore a correction to a template type as the to-be-corrected 398 // identifier is not a template (typo correction for template names 399 // is handled elsewhere). 400 !(getLangOpts().CPlusPlus && NewSSPtr && 401 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false, 402 Template, MemberOfUnknownSpecialization))) { 403 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 404 isClassName, HasTrailingDot, ObjectTypePtr, 405 IsCtorOrDtorName, 406 WantNontrivialTypeSourceInfo, 407 IsClassTemplateDeductionContext); 408 if (Ty) { 409 diagnoseTypo(Correction, 410 PDiag(diag::err_unknown_type_or_class_name_suggest) 411 << Result.getLookupName() << isClassName); 412 if (SS && NNS) 413 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 414 *CorrectedII = NewII; 415 return Ty; 416 } 417 } 418 } 419 // If typo correction failed or was not performed, fall through 420 LLVM_FALLTHROUGH; 421 case LookupResult::FoundOverloaded: 422 case LookupResult::FoundUnresolvedValue: 423 Result.suppressDiagnostics(); 424 return nullptr; 425 426 case LookupResult::Ambiguous: 427 // Recover from type-hiding ambiguities by hiding the type. We'll 428 // do the lookup again when looking for an object, and we can 429 // diagnose the error then. If we don't do this, then the error 430 // about hiding the type will be immediately followed by an error 431 // that only makes sense if the identifier was treated like a type. 432 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 433 Result.suppressDiagnostics(); 434 return nullptr; 435 } 436 437 // Look to see if we have a type anywhere in the list of results. 438 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 439 Res != ResEnd; ++Res) { 440 NamedDecl *RealRes = (*Res)->getUnderlyingDecl(); 441 if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>( 442 RealRes) || 443 (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) { 444 if (!IIDecl || 445 // Make the selection of the recovery decl deterministic. 446 RealRes->getLocation() < IIDecl->getLocation()) { 447 IIDecl = RealRes; 448 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res); 449 } 450 } 451 } 452 453 if (!IIDecl) { 454 // None of the entities we found is a type, so there is no way 455 // to even assume that the result is a type. In this case, don't 456 // complain about the ambiguity. The parser will either try to 457 // perform this lookup again (e.g., as an object name), which 458 // will produce the ambiguity, or will complain that it expected 459 // a type name. 460 Result.suppressDiagnostics(); 461 return nullptr; 462 } 463 464 // We found a type within the ambiguous lookup; diagnose the 465 // ambiguity and then return that type. This might be the right 466 // answer, or it might not be, but it suppresses any attempt to 467 // perform the name lookup again. 468 break; 469 470 case LookupResult::Found: 471 IIDecl = Result.getFoundDecl(); 472 FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin()); 473 break; 474 } 475 476 assert(IIDecl && "Didn't find decl"); 477 478 QualType T; 479 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 480 // C++ [class.qual]p2: A lookup that would find the injected-class-name 481 // instead names the constructors of the class, except when naming a class. 482 // This is ill-formed when we're not actually forming a ctor or dtor name. 483 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); 484 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD); 485 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD && 486 FoundRD->isInjectedClassName() && 487 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) 488 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor) 489 << &II << /*Type*/1; 490 491 DiagnoseUseOfDecl(IIDecl, NameLoc); 492 493 T = Context.getTypeDeclType(TD); 494 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); 495 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 496 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 497 if (!HasTrailingDot) 498 T = Context.getObjCInterfaceType(IDecl); 499 FoundUsingShadow = nullptr; // FIXME: Target must be a TypeDecl. 500 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) { 501 (void)DiagnoseUseOfDecl(UD, NameLoc); 502 // Recover with 'int' 503 T = Context.IntTy; 504 FoundUsingShadow = nullptr; 505 } else if (AllowDeducedTemplate) { 506 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) { 507 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD); 508 TemplateName Template = 509 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD); 510 T = Context.getDeducedTemplateSpecializationType(Template, QualType(), 511 false); 512 // Don't wrap in a further UsingType. 513 FoundUsingShadow = nullptr; 514 } 515 } 516 517 if (T.isNull()) { 518 // If it's not plausibly a type, suppress diagnostics. 519 Result.suppressDiagnostics(); 520 return nullptr; 521 } 522 523 if (FoundUsingShadow) 524 T = Context.getUsingType(FoundUsingShadow, T); 525 526 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 527 // constructor or destructor name (in such a case, the scope specifier 528 // will be attached to the enclosing Expr or Decl node). 529 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName && 530 !isa<ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(IIDecl)) { 531 if (WantNontrivialTypeSourceInfo) { 532 // Construct a type with type-source information. 533 TypeLocBuilder Builder; 534 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 535 536 T = getElaboratedType(ETK_None, *SS, T); 537 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 538 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 539 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 540 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 541 } else { 542 T = getElaboratedType(ETK_None, *SS, T); 543 } 544 } 545 546 return ParsedType::make(T); 547 } 548 549 // Builds a fake NNS for the given decl context. 550 static NestedNameSpecifier * 551 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { 552 for (;; DC = DC->getLookupParent()) { 553 DC = DC->getPrimaryContext(); 554 auto *ND = dyn_cast<NamespaceDecl>(DC); 555 if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) 556 return NestedNameSpecifier::Create(Context, nullptr, ND); 557 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) 558 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 559 RD->getTypeForDecl()); 560 else if (isa<TranslationUnitDecl>(DC)) 561 return NestedNameSpecifier::GlobalSpecifier(Context); 562 } 563 llvm_unreachable("something isn't in TU scope?"); 564 } 565 566 /// Find the parent class with dependent bases of the innermost enclosing method 567 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end 568 /// up allowing unqualified dependent type names at class-level, which MSVC 569 /// correctly rejects. 570 static const CXXRecordDecl * 571 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) { 572 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) { 573 DC = DC->getPrimaryContext(); 574 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 575 if (MD->getParent()->hasAnyDependentBases()) 576 return MD->getParent(); 577 } 578 return nullptr; 579 } 580 581 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II, 582 SourceLocation NameLoc, 583 bool IsTemplateTypeArg) { 584 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode"); 585 586 NestedNameSpecifier *NNS = nullptr; 587 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) { 588 // If we weren't able to parse a default template argument, delay lookup 589 // until instantiation time by making a non-dependent DependentTypeName. We 590 // pretend we saw a NestedNameSpecifier referring to the current scope, and 591 // lookup is retried. 592 // FIXME: This hurts our diagnostic quality, since we get errors like "no 593 // type named 'Foo' in 'current_namespace'" when the user didn't write any 594 // name specifiers. 595 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext); 596 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; 597 } else if (const CXXRecordDecl *RD = 598 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) { 599 // Build a DependentNameType that will perform lookup into RD at 600 // instantiation time. 601 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 602 RD->getTypeForDecl()); 603 604 // Diagnose that this identifier was undeclared, and retry the lookup during 605 // template instantiation. 606 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II 607 << RD; 608 } else { 609 // This is not a situation that we should recover from. 610 return ParsedType(); 611 } 612 613 QualType T = Context.getDependentNameType(ETK_None, NNS, &II); 614 615 // Build type location information. We synthesized the qualifier, so we have 616 // to build a fake NestedNameSpecifierLoc. 617 NestedNameSpecifierLocBuilder NNSLocBuilder; 618 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 619 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); 620 621 TypeLocBuilder Builder; 622 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 623 DepTL.setNameLoc(NameLoc); 624 DepTL.setElaboratedKeywordLoc(SourceLocation()); 625 DepTL.setQualifierLoc(QualifierLoc); 626 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 627 } 628 629 /// isTagName() - This method is called *for error recovery purposes only* 630 /// to determine if the specified name is a valid tag name ("struct foo"). If 631 /// so, this returns the TST for the tag corresponding to it (TST_enum, 632 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 633 /// cases in C where the user forgot to specify the tag. 634 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 635 // Do a tag name lookup in this scope. 636 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 637 LookupName(R, S, false); 638 R.suppressDiagnostics(); 639 if (R.getResultKind() == LookupResult::Found) 640 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 641 switch (TD->getTagKind()) { 642 case TTK_Struct: return DeclSpec::TST_struct; 643 case TTK_Interface: return DeclSpec::TST_interface; 644 case TTK_Union: return DeclSpec::TST_union; 645 case TTK_Class: return DeclSpec::TST_class; 646 case TTK_Enum: return DeclSpec::TST_enum; 647 } 648 } 649 650 return DeclSpec::TST_unspecified; 651 } 652 653 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 654 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 655 /// then downgrade the missing typename error to a warning. 656 /// This is needed for MSVC compatibility; Example: 657 /// @code 658 /// template<class T> class A { 659 /// public: 660 /// typedef int TYPE; 661 /// }; 662 /// template<class T> class B : public A<T> { 663 /// public: 664 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 665 /// }; 666 /// @endcode 667 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 668 if (CurContext->isRecord()) { 669 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) 670 return true; 671 672 const Type *Ty = SS->getScopeRep()->getAsType(); 673 674 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 675 for (const auto &Base : RD->bases()) 676 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 677 return true; 678 return S->isFunctionPrototypeScope(); 679 } 680 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 681 } 682 683 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 684 SourceLocation IILoc, 685 Scope *S, 686 CXXScopeSpec *SS, 687 ParsedType &SuggestedType, 688 bool IsTemplateName) { 689 // Don't report typename errors for editor placeholders. 690 if (II->isEditorPlaceholder()) 691 return; 692 // We don't have anything to suggest (yet). 693 SuggestedType = nullptr; 694 695 // There may have been a typo in the name of the type. Look up typo 696 // results, in case we have something that we can suggest. 697 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false, 698 /*AllowTemplates=*/IsTemplateName, 699 /*AllowNonTemplates=*/!IsTemplateName); 700 if (TypoCorrection Corrected = 701 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, 702 CCC, CTK_ErrorRecovery)) { 703 // FIXME: Support error recovery for the template-name case. 704 bool CanRecover = !IsTemplateName; 705 if (Corrected.isKeyword()) { 706 // We corrected to a keyword. 707 diagnoseTypo(Corrected, 708 PDiag(IsTemplateName ? diag::err_no_template_suggest 709 : diag::err_unknown_typename_suggest) 710 << II); 711 II = Corrected.getCorrectionAsIdentifierInfo(); 712 } else { 713 // We found a similarly-named type or interface; suggest that. 714 if (!SS || !SS->isSet()) { 715 diagnoseTypo(Corrected, 716 PDiag(IsTemplateName ? diag::err_no_template_suggest 717 : diag::err_unknown_typename_suggest) 718 << II, CanRecover); 719 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 720 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 721 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 722 II->getName().equals(CorrectedStr); 723 diagnoseTypo(Corrected, 724 PDiag(IsTemplateName 725 ? diag::err_no_member_template_suggest 726 : diag::err_unknown_nested_typename_suggest) 727 << II << DC << DroppedSpecifier << SS->getRange(), 728 CanRecover); 729 } else { 730 llvm_unreachable("could not have corrected a typo here"); 731 } 732 733 if (!CanRecover) 734 return; 735 736 CXXScopeSpec tmpSS; 737 if (Corrected.getCorrectionSpecifier()) 738 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 739 SourceRange(IILoc)); 740 // FIXME: Support class template argument deduction here. 741 SuggestedType = 742 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S, 743 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr, 744 /*IsCtorOrDtorName=*/false, 745 /*WantNontrivialTypeSourceInfo=*/true); 746 } 747 return; 748 } 749 750 if (getLangOpts().CPlusPlus && !IsTemplateName) { 751 // See if II is a class template that the user forgot to pass arguments to. 752 UnqualifiedId Name; 753 Name.setIdentifier(II, IILoc); 754 CXXScopeSpec EmptySS; 755 TemplateTy TemplateResult; 756 bool MemberOfUnknownSpecialization; 757 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 758 Name, nullptr, true, TemplateResult, 759 MemberOfUnknownSpecialization) == TNK_Type_template) { 760 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc); 761 return; 762 } 763 } 764 765 // FIXME: Should we move the logic that tries to recover from a missing tag 766 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 767 768 if (!SS || (!SS->isSet() && !SS->isInvalid())) 769 Diag(IILoc, IsTemplateName ? diag::err_no_template 770 : diag::err_unknown_typename) 771 << II; 772 else if (DeclContext *DC = computeDeclContext(*SS, false)) 773 Diag(IILoc, IsTemplateName ? diag::err_no_member_template 774 : diag::err_typename_nested_not_found) 775 << II << DC << SS->getRange(); 776 else if (SS->isValid() && SS->getScopeRep()->containsErrors()) { 777 SuggestedType = 778 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get(); 779 } else if (isDependentScopeSpecifier(*SS)) { 780 unsigned DiagID = diag::err_typename_missing; 781 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 782 DiagID = diag::ext_typename_missing; 783 784 Diag(SS->getRange().getBegin(), DiagID) 785 << SS->getScopeRep() << II->getName() 786 << SourceRange(SS->getRange().getBegin(), IILoc) 787 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 788 SuggestedType = ActOnTypenameType(S, SourceLocation(), 789 *SS, *II, IILoc).get(); 790 } else { 791 assert(SS && SS->isInvalid() && 792 "Invalid scope specifier has already been diagnosed"); 793 } 794 } 795 796 /// Determine whether the given result set contains either a type name 797 /// or 798 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 799 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 800 NextToken.is(tok::less); 801 802 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 803 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 804 return true; 805 806 if (CheckTemplate && isa<TemplateDecl>(*I)) 807 return true; 808 } 809 810 return false; 811 } 812 813 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 814 Scope *S, CXXScopeSpec &SS, 815 IdentifierInfo *&Name, 816 SourceLocation NameLoc) { 817 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 818 SemaRef.LookupParsedName(R, S, &SS); 819 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 820 StringRef FixItTagName; 821 switch (Tag->getTagKind()) { 822 case TTK_Class: 823 FixItTagName = "class "; 824 break; 825 826 case TTK_Enum: 827 FixItTagName = "enum "; 828 break; 829 830 case TTK_Struct: 831 FixItTagName = "struct "; 832 break; 833 834 case TTK_Interface: 835 FixItTagName = "__interface "; 836 break; 837 838 case TTK_Union: 839 FixItTagName = "union "; 840 break; 841 } 842 843 StringRef TagName = FixItTagName.drop_back(); 844 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 845 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 846 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 847 848 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 849 I != IEnd; ++I) 850 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 851 << Name << TagName; 852 853 // Replace lookup results with just the tag decl. 854 Result.clear(Sema::LookupTagName); 855 SemaRef.LookupParsedName(Result, S, &SS); 856 return true; 857 } 858 859 return false; 860 } 861 862 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, 863 IdentifierInfo *&Name, 864 SourceLocation NameLoc, 865 const Token &NextToken, 866 CorrectionCandidateCallback *CCC) { 867 DeclarationNameInfo NameInfo(Name, NameLoc); 868 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 869 870 assert(NextToken.isNot(tok::coloncolon) && 871 "parse nested name specifiers before calling ClassifyName"); 872 if (getLangOpts().CPlusPlus && SS.isSet() && 873 isCurrentClassName(*Name, S, &SS)) { 874 // Per [class.qual]p2, this names the constructors of SS, not the 875 // injected-class-name. We don't have a classification for that. 876 // There's not much point caching this result, since the parser 877 // will reject it later. 878 return NameClassification::Unknown(); 879 } 880 881 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 882 LookupParsedName(Result, S, &SS, !CurMethod); 883 884 if (SS.isInvalid()) 885 return NameClassification::Error(); 886 887 // For unqualified lookup in a class template in MSVC mode, look into 888 // dependent base classes where the primary class template is known. 889 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { 890 if (ParsedType TypeInBase = 891 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) 892 return TypeInBase; 893 } 894 895 // Perform lookup for Objective-C instance variables (including automatically 896 // synthesized instance variables), if we're in an Objective-C method. 897 // FIXME: This lookup really, really needs to be folded in to the normal 898 // unqualified lookup mechanism. 899 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 900 DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name); 901 if (Ivar.isInvalid()) 902 return NameClassification::Error(); 903 if (Ivar.isUsable()) 904 return NameClassification::NonType(cast<NamedDecl>(Ivar.get())); 905 906 // We defer builtin creation until after ivar lookup inside ObjC methods. 907 if (Result.empty()) 908 LookupBuiltin(Result); 909 } 910 911 bool SecondTry = false; 912 bool IsFilteredTemplateName = false; 913 914 Corrected: 915 switch (Result.getResultKind()) { 916 case LookupResult::NotFound: 917 // If an unqualified-id is followed by a '(', then we have a function 918 // call. 919 if (SS.isEmpty() && NextToken.is(tok::l_paren)) { 920 // In C++, this is an ADL-only call. 921 // FIXME: Reference? 922 if (getLangOpts().CPlusPlus) 923 return NameClassification::UndeclaredNonType(); 924 925 // C90 6.3.2.2: 926 // If the expression that precedes the parenthesized argument list in a 927 // function call consists solely of an identifier, and if no 928 // declaration is visible for this identifier, the identifier is 929 // implicitly declared exactly as if, in the innermost block containing 930 // the function call, the declaration 931 // 932 // extern int identifier (); 933 // 934 // appeared. 935 // 936 // We also allow this in C99 as an extension. However, this is not 937 // allowed in all language modes as functions without prototypes may not 938 // be supported. 939 if (getLangOpts().implicitFunctionsAllowed()) { 940 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) 941 return NameClassification::NonType(D); 942 } 943 } 944 945 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) { 946 // In C++20 onwards, this could be an ADL-only call to a function 947 // template, and we're required to assume that this is a template name. 948 // 949 // FIXME: Find a way to still do typo correction in this case. 950 TemplateName Template = 951 Context.getAssumedTemplateName(NameInfo.getName()); 952 return NameClassification::UndeclaredTemplate(Template); 953 } 954 955 // In C, we first see whether there is a tag type by the same name, in 956 // which case it's likely that the user just forgot to write "enum", 957 // "struct", or "union". 958 if (!getLangOpts().CPlusPlus && !SecondTry && 959 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 960 break; 961 } 962 963 // Perform typo correction to determine if there is another name that is 964 // close to this name. 965 if (!SecondTry && CCC) { 966 SecondTry = true; 967 if (TypoCorrection Corrected = 968 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S, 969 &SS, *CCC, CTK_ErrorRecovery)) { 970 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 971 unsigned QualifiedDiag = diag::err_no_member_suggest; 972 973 NamedDecl *FirstDecl = Corrected.getFoundDecl(); 974 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); 975 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 976 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 977 UnqualifiedDiag = diag::err_no_template_suggest; 978 QualifiedDiag = diag::err_no_member_template_suggest; 979 } else if (UnderlyingFirstDecl && 980 (isa<TypeDecl>(UnderlyingFirstDecl) || 981 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 982 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 983 UnqualifiedDiag = diag::err_unknown_typename_suggest; 984 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 985 } 986 987 if (SS.isEmpty()) { 988 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 989 } else {// FIXME: is this even reachable? Test it. 990 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 991 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 992 Name->getName().equals(CorrectedStr); 993 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 994 << Name << computeDeclContext(SS, false) 995 << DroppedSpecifier << SS.getRange()); 996 } 997 998 // Update the name, so that the caller has the new name. 999 Name = Corrected.getCorrectionAsIdentifierInfo(); 1000 1001 // Typo correction corrected to a keyword. 1002 if (Corrected.isKeyword()) 1003 return Name; 1004 1005 // Also update the LookupResult... 1006 // FIXME: This should probably go away at some point 1007 Result.clear(); 1008 Result.setLookupName(Corrected.getCorrection()); 1009 if (FirstDecl) 1010 Result.addDecl(FirstDecl); 1011 1012 // If we found an Objective-C instance variable, let 1013 // LookupInObjCMethod build the appropriate expression to 1014 // reference the ivar. 1015 // FIXME: This is a gross hack. 1016 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 1017 DeclResult R = 1018 LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier()); 1019 if (R.isInvalid()) 1020 return NameClassification::Error(); 1021 if (R.isUsable()) 1022 return NameClassification::NonType(Ivar); 1023 } 1024 1025 goto Corrected; 1026 } 1027 } 1028 1029 // We failed to correct; just fall through and let the parser deal with it. 1030 Result.suppressDiagnostics(); 1031 return NameClassification::Unknown(); 1032 1033 case LookupResult::NotFoundInCurrentInstantiation: { 1034 // We performed name lookup into the current instantiation, and there were 1035 // dependent bases, so we treat this result the same way as any other 1036 // dependent nested-name-specifier. 1037 1038 // C++ [temp.res]p2: 1039 // A name used in a template declaration or definition and that is 1040 // dependent on a template-parameter is assumed not to name a type 1041 // unless the applicable name lookup finds a type name or the name is 1042 // qualified by the keyword typename. 1043 // 1044 // FIXME: If the next token is '<', we might want to ask the parser to 1045 // perform some heroics to see if we actually have a 1046 // template-argument-list, which would indicate a missing 'template' 1047 // keyword here. 1048 return NameClassification::DependentNonType(); 1049 } 1050 1051 case LookupResult::Found: 1052 case LookupResult::FoundOverloaded: 1053 case LookupResult::FoundUnresolvedValue: 1054 break; 1055 1056 case LookupResult::Ambiguous: 1057 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1058 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true, 1059 /*AllowDependent=*/false)) { 1060 // C++ [temp.local]p3: 1061 // A lookup that finds an injected-class-name (10.2) can result in an 1062 // ambiguity in certain cases (for example, if it is found in more than 1063 // one base class). If all of the injected-class-names that are found 1064 // refer to specializations of the same class template, and if the name 1065 // is followed by a template-argument-list, the reference refers to the 1066 // class template itself and not a specialization thereof, and is not 1067 // ambiguous. 1068 // 1069 // This filtering can make an ambiguous result into an unambiguous one, 1070 // so try again after filtering out template names. 1071 FilterAcceptableTemplateNames(Result); 1072 if (!Result.isAmbiguous()) { 1073 IsFilteredTemplateName = true; 1074 break; 1075 } 1076 } 1077 1078 // Diagnose the ambiguity and return an error. 1079 return NameClassification::Error(); 1080 } 1081 1082 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1083 (IsFilteredTemplateName || 1084 hasAnyAcceptableTemplateNames( 1085 Result, /*AllowFunctionTemplates=*/true, 1086 /*AllowDependent=*/false, 1087 /*AllowNonTemplateFunctions*/ SS.isEmpty() && 1088 getLangOpts().CPlusPlus20))) { 1089 // C++ [temp.names]p3: 1090 // After name lookup (3.4) finds that a name is a template-name or that 1091 // an operator-function-id or a literal- operator-id refers to a set of 1092 // overloaded functions any member of which is a function template if 1093 // this is followed by a <, the < is always taken as the delimiter of a 1094 // template-argument-list and never as the less-than operator. 1095 // C++2a [temp.names]p2: 1096 // A name is also considered to refer to a template if it is an 1097 // unqualified-id followed by a < and name lookup finds either one 1098 // or more functions or finds nothing. 1099 if (!IsFilteredTemplateName) 1100 FilterAcceptableTemplateNames(Result); 1101 1102 bool IsFunctionTemplate; 1103 bool IsVarTemplate; 1104 TemplateName Template; 1105 if (Result.end() - Result.begin() > 1) { 1106 IsFunctionTemplate = true; 1107 Template = Context.getOverloadedTemplateName(Result.begin(), 1108 Result.end()); 1109 } else if (!Result.empty()) { 1110 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl( 1111 *Result.begin(), /*AllowFunctionTemplates=*/true, 1112 /*AllowDependent=*/false)); 1113 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 1114 IsVarTemplate = isa<VarTemplateDecl>(TD); 1115 1116 UsingShadowDecl *FoundUsingShadow = 1117 dyn_cast<UsingShadowDecl>(*Result.begin()); 1118 assert(!FoundUsingShadow || 1119 TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl())); 1120 Template = 1121 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD); 1122 if (SS.isNotEmpty()) 1123 Template = Context.getQualifiedTemplateName(SS.getScopeRep(), 1124 /*TemplateKeyword=*/false, 1125 Template); 1126 } else { 1127 // All results were non-template functions. This is a function template 1128 // name. 1129 IsFunctionTemplate = true; 1130 Template = Context.getAssumedTemplateName(NameInfo.getName()); 1131 } 1132 1133 if (IsFunctionTemplate) { 1134 // Function templates always go through overload resolution, at which 1135 // point we'll perform the various checks (e.g., accessibility) we need 1136 // to based on which function we selected. 1137 Result.suppressDiagnostics(); 1138 1139 return NameClassification::FunctionTemplate(Template); 1140 } 1141 1142 return IsVarTemplate ? NameClassification::VarTemplate(Template) 1143 : NameClassification::TypeTemplate(Template); 1144 } 1145 1146 auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) { 1147 QualType T = Context.getTypeDeclType(Type); 1148 if (const auto *USD = dyn_cast<UsingShadowDecl>(Found)) 1149 T = Context.getUsingType(USD, T); 1150 1151 if (SS.isEmpty()) // No elaborated type, trivial location info 1152 return ParsedType::make(T); 1153 1154 TypeLocBuilder Builder; 1155 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 1156 T = getElaboratedType(ETK_None, SS, T); 1157 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 1158 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 1159 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 1160 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 1161 }; 1162 1163 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 1164 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 1165 DiagnoseUseOfDecl(Type, NameLoc); 1166 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 1167 return BuildTypeFor(Type, *Result.begin()); 1168 } 1169 1170 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 1171 if (!Class) { 1172 // FIXME: It's unfortunate that we don't have a Type node for handling this. 1173 if (ObjCCompatibleAliasDecl *Alias = 1174 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 1175 Class = Alias->getClassInterface(); 1176 } 1177 1178 if (Class) { 1179 DiagnoseUseOfDecl(Class, NameLoc); 1180 1181 if (NextToken.is(tok::period)) { 1182 // Interface. <something> is parsed as a property reference expression. 1183 // Just return "unknown" as a fall-through for now. 1184 Result.suppressDiagnostics(); 1185 return NameClassification::Unknown(); 1186 } 1187 1188 QualType T = Context.getObjCInterfaceType(Class); 1189 return ParsedType::make(T); 1190 } 1191 1192 if (isa<ConceptDecl>(FirstDecl)) 1193 return NameClassification::Concept( 1194 TemplateName(cast<TemplateDecl>(FirstDecl))); 1195 1196 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) { 1197 (void)DiagnoseUseOfDecl(EmptyD, NameLoc); 1198 return NameClassification::Error(); 1199 } 1200 1201 // We can have a type template here if we're classifying a template argument. 1202 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) && 1203 !isa<VarTemplateDecl>(FirstDecl)) 1204 return NameClassification::TypeTemplate( 1205 TemplateName(cast<TemplateDecl>(FirstDecl))); 1206 1207 // Check for a tag type hidden by a non-type decl in a few cases where it 1208 // seems likely a type is wanted instead of the non-type that was found. 1209 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); 1210 if ((NextToken.is(tok::identifier) || 1211 (NextIsOp && 1212 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 1213 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 1214 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 1215 DiagnoseUseOfDecl(Type, NameLoc); 1216 return BuildTypeFor(Type, *Result.begin()); 1217 } 1218 1219 // If we already know which single declaration is referenced, just annotate 1220 // that declaration directly. Defer resolving even non-overloaded class 1221 // member accesses, as we need to defer certain access checks until we know 1222 // the context. 1223 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1224 if (Result.isSingleResult() && !ADL && !FirstDecl->isCXXClassMember()) 1225 return NameClassification::NonType(Result.getRepresentativeDecl()); 1226 1227 // Otherwise, this is an overload set that we will need to resolve later. 1228 Result.suppressDiagnostics(); 1229 return NameClassification::OverloadSet(UnresolvedLookupExpr::Create( 1230 Context, Result.getNamingClass(), SS.getWithLocInContext(Context), 1231 Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(), 1232 Result.begin(), Result.end())); 1233 } 1234 1235 ExprResult 1236 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, 1237 SourceLocation NameLoc) { 1238 assert(getLangOpts().CPlusPlus && "ADL-only call in C?"); 1239 CXXScopeSpec SS; 1240 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 1241 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 1242 } 1243 1244 ExprResult 1245 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, 1246 IdentifierInfo *Name, 1247 SourceLocation NameLoc, 1248 bool IsAddressOfOperand) { 1249 DeclarationNameInfo NameInfo(Name, NameLoc); 1250 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 1251 NameInfo, IsAddressOfOperand, 1252 /*TemplateArgs=*/nullptr); 1253 } 1254 1255 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, 1256 NamedDecl *Found, 1257 SourceLocation NameLoc, 1258 const Token &NextToken) { 1259 if (getCurMethodDecl() && SS.isEmpty()) 1260 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl())) 1261 return BuildIvarRefExpr(S, NameLoc, Ivar); 1262 1263 // Reconstruct the lookup result. 1264 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName); 1265 Result.addDecl(Found); 1266 Result.resolveKind(); 1267 1268 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1269 return BuildDeclarationNameExpr(SS, Result, ADL); 1270 } 1271 1272 ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) { 1273 // For an implicit class member access, transform the result into a member 1274 // access expression if necessary. 1275 auto *ULE = cast<UnresolvedLookupExpr>(E); 1276 if ((*ULE->decls_begin())->isCXXClassMember()) { 1277 CXXScopeSpec SS; 1278 SS.Adopt(ULE->getQualifierLoc()); 1279 1280 // Reconstruct the lookup result. 1281 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(), 1282 LookupOrdinaryName); 1283 Result.setNamingClass(ULE->getNamingClass()); 1284 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I) 1285 Result.addDecl(*I, I.getAccess()); 1286 Result.resolveKind(); 1287 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 1288 nullptr, S); 1289 } 1290 1291 // Otherwise, this is already in the form we needed, and no further checks 1292 // are necessary. 1293 return ULE; 1294 } 1295 1296 Sema::TemplateNameKindForDiagnostics 1297 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) { 1298 auto *TD = Name.getAsTemplateDecl(); 1299 if (!TD) 1300 return TemplateNameKindForDiagnostics::DependentTemplate; 1301 if (isa<ClassTemplateDecl>(TD)) 1302 return TemplateNameKindForDiagnostics::ClassTemplate; 1303 if (isa<FunctionTemplateDecl>(TD)) 1304 return TemplateNameKindForDiagnostics::FunctionTemplate; 1305 if (isa<VarTemplateDecl>(TD)) 1306 return TemplateNameKindForDiagnostics::VarTemplate; 1307 if (isa<TypeAliasTemplateDecl>(TD)) 1308 return TemplateNameKindForDiagnostics::AliasTemplate; 1309 if (isa<TemplateTemplateParmDecl>(TD)) 1310 return TemplateNameKindForDiagnostics::TemplateTemplateParam; 1311 if (isa<ConceptDecl>(TD)) 1312 return TemplateNameKindForDiagnostics::Concept; 1313 return TemplateNameKindForDiagnostics::DependentTemplate; 1314 } 1315 1316 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 1317 assert(DC->getLexicalParent() == CurContext && 1318 "The next DeclContext should be lexically contained in the current one."); 1319 CurContext = DC; 1320 S->setEntity(DC); 1321 } 1322 1323 void Sema::PopDeclContext() { 1324 assert(CurContext && "DeclContext imbalance!"); 1325 1326 CurContext = CurContext->getLexicalParent(); 1327 assert(CurContext && "Popped translation unit!"); 1328 } 1329 1330 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, 1331 Decl *D) { 1332 // Unlike PushDeclContext, the context to which we return is not necessarily 1333 // the containing DC of TD, because the new context will be some pre-existing 1334 // TagDecl definition instead of a fresh one. 1335 auto Result = static_cast<SkippedDefinitionContext>(CurContext); 1336 CurContext = cast<TagDecl>(D)->getDefinition(); 1337 assert(CurContext && "skipping definition of undefined tag"); 1338 // Start lookups from the parent of the current context; we don't want to look 1339 // into the pre-existing complete definition. 1340 S->setEntity(CurContext->getLookupParent()); 1341 return Result; 1342 } 1343 1344 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { 1345 CurContext = static_cast<decltype(CurContext)>(Context); 1346 } 1347 1348 /// EnterDeclaratorContext - Used when we must lookup names in the context 1349 /// of a declarator's nested name specifier. 1350 /// 1351 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1352 // C++0x [basic.lookup.unqual]p13: 1353 // A name used in the definition of a static data member of class 1354 // X (after the qualified-id of the static member) is looked up as 1355 // if the name was used in a member function of X. 1356 // C++0x [basic.lookup.unqual]p14: 1357 // If a variable member of a namespace is defined outside of the 1358 // scope of its namespace then any name used in the definition of 1359 // the variable member (after the declarator-id) is looked up as 1360 // if the definition of the variable member occurred in its 1361 // namespace. 1362 // Both of these imply that we should push a scope whose context 1363 // is the semantic context of the declaration. We can't use 1364 // PushDeclContext here because that context is not necessarily 1365 // lexically contained in the current context. Fortunately, 1366 // the containing scope should have the appropriate information. 1367 1368 assert(!S->getEntity() && "scope already has entity"); 1369 1370 #ifndef NDEBUG 1371 Scope *Ancestor = S->getParent(); 1372 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1373 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1374 #endif 1375 1376 CurContext = DC; 1377 S->setEntity(DC); 1378 1379 if (S->getParent()->isTemplateParamScope()) { 1380 // Also set the corresponding entities for all immediately-enclosing 1381 // template parameter scopes. 1382 EnterTemplatedContext(S->getParent(), DC); 1383 } 1384 } 1385 1386 void Sema::ExitDeclaratorContext(Scope *S) { 1387 assert(S->getEntity() == CurContext && "Context imbalance!"); 1388 1389 // Switch back to the lexical context. The safety of this is 1390 // enforced by an assert in EnterDeclaratorContext. 1391 Scope *Ancestor = S->getParent(); 1392 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1393 CurContext = Ancestor->getEntity(); 1394 1395 // We don't need to do anything with the scope, which is going to 1396 // disappear. 1397 } 1398 1399 void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) { 1400 assert(S->isTemplateParamScope() && 1401 "expected to be initializing a template parameter scope"); 1402 1403 // C++20 [temp.local]p7: 1404 // In the definition of a member of a class template that appears outside 1405 // of the class template definition, the name of a member of the class 1406 // template hides the name of a template-parameter of any enclosing class 1407 // templates (but not a template-parameter of the member if the member is a 1408 // class or function template). 1409 // C++20 [temp.local]p9: 1410 // In the definition of a class template or in the definition of a member 1411 // of such a template that appears outside of the template definition, for 1412 // each non-dependent base class (13.8.2.1), if the name of the base class 1413 // or the name of a member of the base class is the same as the name of a 1414 // template-parameter, the base class name or member name hides the 1415 // template-parameter name (6.4.10). 1416 // 1417 // This means that a template parameter scope should be searched immediately 1418 // after searching the DeclContext for which it is a template parameter 1419 // scope. For example, for 1420 // template<typename T> template<typename U> template<typename V> 1421 // void N::A<T>::B<U>::f(...) 1422 // we search V then B<U> (and base classes) then U then A<T> (and base 1423 // classes) then T then N then ::. 1424 unsigned ScopeDepth = getTemplateDepth(S); 1425 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) { 1426 DeclContext *SearchDCAfterScope = DC; 1427 for (; DC; DC = DC->getLookupParent()) { 1428 if (const TemplateParameterList *TPL = 1429 cast<Decl>(DC)->getDescribedTemplateParams()) { 1430 unsigned DCDepth = TPL->getDepth() + 1; 1431 if (DCDepth > ScopeDepth) 1432 continue; 1433 if (ScopeDepth == DCDepth) 1434 SearchDCAfterScope = DC = DC->getLookupParent(); 1435 break; 1436 } 1437 } 1438 S->setLookupEntity(SearchDCAfterScope); 1439 } 1440 } 1441 1442 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1443 // We assume that the caller has already called 1444 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1445 FunctionDecl *FD = D->getAsFunction(); 1446 if (!FD) 1447 return; 1448 1449 // Same implementation as PushDeclContext, but enters the context 1450 // from the lexical parent, rather than the top-level class. 1451 assert(CurContext == FD->getLexicalParent() && 1452 "The next DeclContext should be lexically contained in the current one."); 1453 CurContext = FD; 1454 S->setEntity(CurContext); 1455 1456 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1457 ParmVarDecl *Param = FD->getParamDecl(P); 1458 // If the parameter has an identifier, then add it to the scope 1459 if (Param->getIdentifier()) { 1460 S->AddDecl(Param); 1461 IdResolver.AddDecl(Param); 1462 } 1463 } 1464 } 1465 1466 void Sema::ActOnExitFunctionContext() { 1467 // Same implementation as PopDeclContext, but returns to the lexical parent, 1468 // rather than the top-level class. 1469 assert(CurContext && "DeclContext imbalance!"); 1470 CurContext = CurContext->getLexicalParent(); 1471 assert(CurContext && "Popped translation unit!"); 1472 } 1473 1474 /// Determine whether overloading is allowed for a new function 1475 /// declaration considering prior declarations of the same name. 1476 /// 1477 /// This routine determines whether overloading is possible, not 1478 /// whether a new declaration actually overloads a previous one. 1479 /// It will return true in C++ (where overloads are alway permitted) 1480 /// or, as a C extension, when either the new declaration or a 1481 /// previous one is declared with the 'overloadable' attribute. 1482 static bool AllowOverloadingOfFunction(const LookupResult &Previous, 1483 ASTContext &Context, 1484 const FunctionDecl *New) { 1485 if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>()) 1486 return true; 1487 1488 // Multiversion function declarations are not overloads in the 1489 // usual sense of that term, but lookup will report that an 1490 // overload set was found if more than one multiversion function 1491 // declaration is present for the same name. It is therefore 1492 // inadequate to assume that some prior declaration(s) had 1493 // the overloadable attribute; checking is required. Since one 1494 // declaration is permitted to omit the attribute, it is necessary 1495 // to check at least two; hence the 'any_of' check below. Note that 1496 // the overloadable attribute is implicitly added to declarations 1497 // that were required to have it but did not. 1498 if (Previous.getResultKind() == LookupResult::FoundOverloaded) { 1499 return llvm::any_of(Previous, [](const NamedDecl *ND) { 1500 return ND->hasAttr<OverloadableAttr>(); 1501 }); 1502 } else if (Previous.getResultKind() == LookupResult::Found) 1503 return Previous.getFoundDecl()->hasAttr<OverloadableAttr>(); 1504 1505 return false; 1506 } 1507 1508 /// Add this decl to the scope shadowed decl chains. 1509 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1510 // Move up the scope chain until we find the nearest enclosing 1511 // non-transparent context. The declaration will be introduced into this 1512 // scope. 1513 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1514 S = S->getParent(); 1515 1516 // Add scoped declarations into their context, so that they can be 1517 // found later. Declarations without a context won't be inserted 1518 // into any context. 1519 if (AddToContext) 1520 CurContext->addDecl(D); 1521 1522 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1523 // are function-local declarations. 1524 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent()) 1525 return; 1526 1527 // Template instantiations should also not be pushed into scope. 1528 if (isa<FunctionDecl>(D) && 1529 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1530 return; 1531 1532 // If this replaces anything in the current scope, 1533 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1534 IEnd = IdResolver.end(); 1535 for (; I != IEnd; ++I) { 1536 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1537 S->RemoveDecl(*I); 1538 IdResolver.RemoveDecl(*I); 1539 1540 // Should only need to replace one decl. 1541 break; 1542 } 1543 } 1544 1545 S->AddDecl(D); 1546 1547 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1548 // Implicitly-generated labels may end up getting generated in an order that 1549 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1550 // the label at the appropriate place in the identifier chain. 1551 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1552 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1553 if (IDC == CurContext) { 1554 if (!S->isDeclScope(*I)) 1555 continue; 1556 } else if (IDC->Encloses(CurContext)) 1557 break; 1558 } 1559 1560 IdResolver.InsertDeclAfter(I, D); 1561 } else { 1562 IdResolver.AddDecl(D); 1563 } 1564 warnOnReservedIdentifier(D); 1565 } 1566 1567 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1568 bool AllowInlineNamespace) { 1569 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1570 } 1571 1572 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1573 DeclContext *TargetDC = DC->getPrimaryContext(); 1574 do { 1575 if (DeclContext *ScopeDC = S->getEntity()) 1576 if (ScopeDC->getPrimaryContext() == TargetDC) 1577 return S; 1578 } while ((S = S->getParent())); 1579 1580 return nullptr; 1581 } 1582 1583 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1584 DeclContext*, 1585 ASTContext&); 1586 1587 /// Filters out lookup results that don't fall within the given scope 1588 /// as determined by isDeclInScope. 1589 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1590 bool ConsiderLinkage, 1591 bool AllowInlineNamespace) { 1592 LookupResult::Filter F = R.makeFilter(); 1593 while (F.hasNext()) { 1594 NamedDecl *D = F.next(); 1595 1596 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1597 continue; 1598 1599 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1600 continue; 1601 1602 F.erase(); 1603 } 1604 1605 F.done(); 1606 } 1607 1608 /// We've determined that \p New is a redeclaration of \p Old. Check that they 1609 /// have compatible owning modules. 1610 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) { 1611 // [module.interface]p7: 1612 // A declaration is attached to a module as follows: 1613 // - If the declaration is a non-dependent friend declaration that nominates a 1614 // function with a declarator-id that is a qualified-id or template-id or that 1615 // nominates a class other than with an elaborated-type-specifier with neither 1616 // a nested-name-specifier nor a simple-template-id, it is attached to the 1617 // module to which the friend is attached ([basic.link]). 1618 if (New->getFriendObjectKind() && 1619 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) { 1620 New->setLocalOwningModule(Old->getOwningModule()); 1621 makeMergedDefinitionVisible(New); 1622 return false; 1623 } 1624 1625 Module *NewM = New->getOwningModule(); 1626 Module *OldM = Old->getOwningModule(); 1627 1628 if (NewM && NewM->isPrivateModule()) 1629 NewM = NewM->Parent; 1630 if (OldM && OldM->isPrivateModule()) 1631 OldM = OldM->Parent; 1632 1633 if (NewM == OldM) 1634 return false; 1635 1636 // Partitions are part of the module, but a partition could import another 1637 // module, so verify that the PMIs agree. 1638 if (NewM && OldM && (NewM->isModulePartition() || OldM->isModulePartition())) 1639 return NewM->getPrimaryModuleInterfaceName() == 1640 OldM->getPrimaryModuleInterfaceName(); 1641 1642 bool NewIsModuleInterface = NewM && NewM->isModulePurview(); 1643 bool OldIsModuleInterface = OldM && OldM->isModulePurview(); 1644 if (NewIsModuleInterface || OldIsModuleInterface) { 1645 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]: 1646 // if a declaration of D [...] appears in the purview of a module, all 1647 // other such declarations shall appear in the purview of the same module 1648 Diag(New->getLocation(), diag::err_mismatched_owning_module) 1649 << New 1650 << NewIsModuleInterface 1651 << (NewIsModuleInterface ? NewM->getFullModuleName() : "") 1652 << OldIsModuleInterface 1653 << (OldIsModuleInterface ? OldM->getFullModuleName() : ""); 1654 Diag(Old->getLocation(), diag::note_previous_declaration); 1655 New->setInvalidDecl(); 1656 return true; 1657 } 1658 1659 return false; 1660 } 1661 1662 // [module.interface]p6: 1663 // A redeclaration of an entity X is implicitly exported if X was introduced by 1664 // an exported declaration; otherwise it shall not be exported. 1665 bool Sema::CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old) { 1666 // [module.interface]p1: 1667 // An export-declaration shall inhabit a namespace scope. 1668 // 1669 // So it is meaningless to talk about redeclaration which is not at namespace 1670 // scope. 1671 if (!New->getLexicalDeclContext() 1672 ->getNonTransparentContext() 1673 ->isFileContext() || 1674 !Old->getLexicalDeclContext() 1675 ->getNonTransparentContext() 1676 ->isFileContext()) 1677 return false; 1678 1679 bool IsNewExported = New->isInExportDeclContext(); 1680 bool IsOldExported = Old->isInExportDeclContext(); 1681 1682 // It should be irrevelant if both of them are not exported. 1683 if (!IsNewExported && !IsOldExported) 1684 return false; 1685 1686 if (IsOldExported) 1687 return false; 1688 1689 assert(IsNewExported); 1690 1691 auto Lk = Old->getFormalLinkage(); 1692 int S = 0; 1693 if (Lk == Linkage::InternalLinkage) 1694 S = 1; 1695 else if (Lk == Linkage::ModuleLinkage) 1696 S = 2; 1697 Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S; 1698 Diag(Old->getLocation(), diag::note_previous_declaration); 1699 return true; 1700 } 1701 1702 // A wrapper function for checking the semantic restrictions of 1703 // a redeclaration within a module. 1704 bool Sema::CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old) { 1705 if (CheckRedeclarationModuleOwnership(New, Old)) 1706 return true; 1707 1708 if (CheckRedeclarationExported(New, Old)) 1709 return true; 1710 1711 return false; 1712 } 1713 1714 static bool isUsingDecl(NamedDecl *D) { 1715 return isa<UsingShadowDecl>(D) || 1716 isa<UnresolvedUsingTypenameDecl>(D) || 1717 isa<UnresolvedUsingValueDecl>(D); 1718 } 1719 1720 /// Removes using shadow declarations from the lookup results. 1721 static void RemoveUsingDecls(LookupResult &R) { 1722 LookupResult::Filter F = R.makeFilter(); 1723 while (F.hasNext()) 1724 if (isUsingDecl(F.next())) 1725 F.erase(); 1726 1727 F.done(); 1728 } 1729 1730 /// Check for this common pattern: 1731 /// @code 1732 /// class S { 1733 /// S(const S&); // DO NOT IMPLEMENT 1734 /// void operator=(const S&); // DO NOT IMPLEMENT 1735 /// }; 1736 /// @endcode 1737 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1738 // FIXME: Should check for private access too but access is set after we get 1739 // the decl here. 1740 if (D->doesThisDeclarationHaveABody()) 1741 return false; 1742 1743 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1744 return CD->isCopyConstructor(); 1745 return D->isCopyAssignmentOperator(); 1746 } 1747 1748 // We need this to handle 1749 // 1750 // typedef struct { 1751 // void *foo() { return 0; } 1752 // } A; 1753 // 1754 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1755 // for example. If 'A', foo will have external linkage. If we have '*A', 1756 // foo will have no linkage. Since we can't know until we get to the end 1757 // of the typedef, this function finds out if D might have non-external linkage. 1758 // Callers should verify at the end of the TU if it D has external linkage or 1759 // not. 1760 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1761 const DeclContext *DC = D->getDeclContext(); 1762 while (!DC->isTranslationUnit()) { 1763 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1764 if (!RD->hasNameForLinkage()) 1765 return true; 1766 } 1767 DC = DC->getParent(); 1768 } 1769 1770 return !D->isExternallyVisible(); 1771 } 1772 1773 // FIXME: This needs to be refactored; some other isInMainFile users want 1774 // these semantics. 1775 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1776 if (S.TUKind != TU_Complete) 1777 return false; 1778 return S.SourceMgr.isInMainFile(Loc); 1779 } 1780 1781 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1782 assert(D); 1783 1784 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1785 return false; 1786 1787 // Ignore all entities declared within templates, and out-of-line definitions 1788 // of members of class templates. 1789 if (D->getDeclContext()->isDependentContext() || 1790 D->getLexicalDeclContext()->isDependentContext()) 1791 return false; 1792 1793 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1794 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1795 return false; 1796 // A non-out-of-line declaration of a member specialization was implicitly 1797 // instantiated; it's the out-of-line declaration that we're interested in. 1798 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1799 FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) 1800 return false; 1801 1802 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1803 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1804 return false; 1805 } else { 1806 // 'static inline' functions are defined in headers; don't warn. 1807 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1808 return false; 1809 } 1810 1811 if (FD->doesThisDeclarationHaveABody() && 1812 Context.DeclMustBeEmitted(FD)) 1813 return false; 1814 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1815 // Constants and utility variables are defined in headers with internal 1816 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1817 // like "inline".) 1818 if (!isMainFileLoc(*this, VD->getLocation())) 1819 return false; 1820 1821 if (Context.DeclMustBeEmitted(VD)) 1822 return false; 1823 1824 if (VD->isStaticDataMember() && 1825 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1826 return false; 1827 if (VD->isStaticDataMember() && 1828 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1829 VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) 1830 return false; 1831 1832 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) 1833 return false; 1834 } else { 1835 return false; 1836 } 1837 1838 // Only warn for unused decls internal to the translation unit. 1839 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1840 // for inline functions defined in the main source file, for instance. 1841 return mightHaveNonExternalLinkage(D); 1842 } 1843 1844 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1845 if (!D) 1846 return; 1847 1848 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1849 const FunctionDecl *First = FD->getFirstDecl(); 1850 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1851 return; // First should already be in the vector. 1852 } 1853 1854 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1855 const VarDecl *First = VD->getFirstDecl(); 1856 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1857 return; // First should already be in the vector. 1858 } 1859 1860 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1861 UnusedFileScopedDecls.push_back(D); 1862 } 1863 1864 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1865 if (D->isInvalidDecl()) 1866 return false; 1867 1868 if (auto *DD = dyn_cast<DecompositionDecl>(D)) { 1869 // For a decomposition declaration, warn if none of the bindings are 1870 // referenced, instead of if the variable itself is referenced (which 1871 // it is, by the bindings' expressions). 1872 for (auto *BD : DD->bindings()) 1873 if (BD->isReferenced()) 1874 return false; 1875 } else if (!D->getDeclName()) { 1876 return false; 1877 } else if (D->isReferenced() || D->isUsed()) { 1878 return false; 1879 } 1880 1881 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>()) 1882 return false; 1883 1884 if (isa<LabelDecl>(D)) 1885 return true; 1886 1887 // Except for labels, we only care about unused decls that are local to 1888 // functions. 1889 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1890 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1891 // For dependent types, the diagnostic is deferred. 1892 WithinFunction = 1893 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1894 if (!WithinFunction) 1895 return false; 1896 1897 if (isa<TypedefNameDecl>(D)) 1898 return true; 1899 1900 // White-list anything that isn't a local variable. 1901 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1902 return false; 1903 1904 // Types of valid local variables should be complete, so this should succeed. 1905 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1906 1907 const Expr *Init = VD->getInit(); 1908 if (const auto *Cleanups = dyn_cast_or_null<ExprWithCleanups>(Init)) 1909 Init = Cleanups->getSubExpr(); 1910 1911 const auto *Ty = VD->getType().getTypePtr(); 1912 1913 // Only look at the outermost level of typedef. 1914 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1915 // Allow anything marked with __attribute__((unused)). 1916 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1917 return false; 1918 } 1919 1920 // Warn for reference variables whose initializtion performs lifetime 1921 // extension. 1922 if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>(Init)) { 1923 if (MTE->getExtendingDecl()) { 1924 Ty = VD->getType().getNonReferenceType().getTypePtr(); 1925 Init = MTE->getSubExpr()->IgnoreImplicitAsWritten(); 1926 } 1927 } 1928 1929 // If we failed to complete the type for some reason, or if the type is 1930 // dependent, don't diagnose the variable. 1931 if (Ty->isIncompleteType() || Ty->isDependentType()) 1932 return false; 1933 1934 // Look at the element type to ensure that the warning behaviour is 1935 // consistent for both scalars and arrays. 1936 Ty = Ty->getBaseElementTypeUnsafe(); 1937 1938 if (const TagType *TT = Ty->getAs<TagType>()) { 1939 const TagDecl *Tag = TT->getDecl(); 1940 if (Tag->hasAttr<UnusedAttr>()) 1941 return false; 1942 1943 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1944 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1945 return false; 1946 1947 if (Init) { 1948 const CXXConstructExpr *Construct = 1949 dyn_cast<CXXConstructExpr>(Init); 1950 if (Construct && !Construct->isElidable()) { 1951 CXXConstructorDecl *CD = Construct->getConstructor(); 1952 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() && 1953 (VD->getInit()->isValueDependent() || !VD->evaluateValue())) 1954 return false; 1955 } 1956 1957 // Suppress the warning if we don't know how this is constructed, and 1958 // it could possibly be non-trivial constructor. 1959 if (Init->isTypeDependent()) { 1960 for (const CXXConstructorDecl *Ctor : RD->ctors()) 1961 if (!Ctor->isTrivial()) 1962 return false; 1963 } 1964 1965 // Suppress the warning if the constructor is unresolved because 1966 // its arguments are dependent. 1967 if (isa<CXXUnresolvedConstructExpr>(Init)) 1968 return false; 1969 } 1970 } 1971 } 1972 1973 // TODO: __attribute__((unused)) templates? 1974 } 1975 1976 return true; 1977 } 1978 1979 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1980 FixItHint &Hint) { 1981 if (isa<LabelDecl>(D)) { 1982 SourceLocation AfterColon = Lexer::findLocationAfterToken( 1983 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), 1984 true); 1985 if (AfterColon.isInvalid()) 1986 return; 1987 Hint = FixItHint::CreateRemoval( 1988 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon)); 1989 } 1990 } 1991 1992 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1993 if (D->getTypeForDecl()->isDependentType()) 1994 return; 1995 1996 for (auto *TmpD : D->decls()) { 1997 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1998 DiagnoseUnusedDecl(T); 1999 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 2000 DiagnoseUnusedNestedTypedefs(R); 2001 } 2002 } 2003 2004 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 2005 /// unless they are marked attr(unused). 2006 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 2007 if (!ShouldDiagnoseUnusedDecl(D)) 2008 return; 2009 2010 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 2011 // typedefs can be referenced later on, so the diagnostics are emitted 2012 // at end-of-translation-unit. 2013 UnusedLocalTypedefNameCandidates.insert(TD); 2014 return; 2015 } 2016 2017 FixItHint Hint; 2018 GenerateFixForUnusedDecl(D, Context, Hint); 2019 2020 unsigned DiagID; 2021 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 2022 DiagID = diag::warn_unused_exception_param; 2023 else if (isa<LabelDecl>(D)) 2024 DiagID = diag::warn_unused_label; 2025 else 2026 DiagID = diag::warn_unused_variable; 2027 2028 Diag(D->getLocation(), DiagID) << D << Hint; 2029 } 2030 2031 void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD) { 2032 // If it's not referenced, it can't be set. If it has the Cleanup attribute, 2033 // it's not really unused. 2034 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<UnusedAttr>() || 2035 VD->hasAttr<CleanupAttr>()) 2036 return; 2037 2038 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe(); 2039 2040 if (Ty->isReferenceType() || Ty->isDependentType()) 2041 return; 2042 2043 if (const TagType *TT = Ty->getAs<TagType>()) { 2044 const TagDecl *Tag = TT->getDecl(); 2045 if (Tag->hasAttr<UnusedAttr>()) 2046 return; 2047 // In C++, don't warn for record types that don't have WarnUnusedAttr, to 2048 // mimic gcc's behavior. 2049 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 2050 if (!RD->hasAttr<WarnUnusedAttr>()) 2051 return; 2052 } 2053 } 2054 2055 // Don't warn about __block Objective-C pointer variables, as they might 2056 // be assigned in the block but not used elsewhere for the purpose of lifetime 2057 // extension. 2058 if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType()) 2059 return; 2060 2061 // Don't warn about Objective-C pointer variables with precise lifetime 2062 // semantics; they can be used to ensure ARC releases the object at a known 2063 // time, which may mean assignment but no other references. 2064 if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType()) 2065 return; 2066 2067 auto iter = RefsMinusAssignments.find(VD); 2068 if (iter == RefsMinusAssignments.end()) 2069 return; 2070 2071 assert(iter->getSecond() >= 0 && 2072 "Found a negative number of references to a VarDecl"); 2073 if (iter->getSecond() != 0) 2074 return; 2075 unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter 2076 : diag::warn_unused_but_set_variable; 2077 Diag(VD->getLocation(), DiagID) << VD; 2078 } 2079 2080 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 2081 // Verify that we have no forward references left. If so, there was a goto 2082 // or address of a label taken, but no definition of it. Label fwd 2083 // definitions are indicated with a null substmt which is also not a resolved 2084 // MS inline assembly label name. 2085 bool Diagnose = false; 2086 if (L->isMSAsmLabel()) 2087 Diagnose = !L->isResolvedMSAsmLabel(); 2088 else 2089 Diagnose = L->getStmt() == nullptr; 2090 if (Diagnose) 2091 S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L; 2092 } 2093 2094 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 2095 S->mergeNRVOIntoParent(); 2096 2097 if (S->decl_empty()) return; 2098 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 2099 "Scope shouldn't contain decls!"); 2100 2101 for (auto *TmpD : S->decls()) { 2102 assert(TmpD && "This decl didn't get pushed??"); 2103 2104 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 2105 NamedDecl *D = cast<NamedDecl>(TmpD); 2106 2107 // Diagnose unused variables in this scope. 2108 if (!S->hasUnrecoverableErrorOccurred()) { 2109 DiagnoseUnusedDecl(D); 2110 if (const auto *RD = dyn_cast<RecordDecl>(D)) 2111 DiagnoseUnusedNestedTypedefs(RD); 2112 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 2113 DiagnoseUnusedButSetDecl(VD); 2114 RefsMinusAssignments.erase(VD); 2115 } 2116 } 2117 2118 if (!D->getDeclName()) continue; 2119 2120 // If this was a forward reference to a label, verify it was defined. 2121 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 2122 CheckPoppedLabel(LD, *this); 2123 2124 // Remove this name from our lexical scope, and warn on it if we haven't 2125 // already. 2126 IdResolver.RemoveDecl(D); 2127 auto ShadowI = ShadowingDecls.find(D); 2128 if (ShadowI != ShadowingDecls.end()) { 2129 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { 2130 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) 2131 << D << FD << FD->getParent(); 2132 Diag(FD->getLocation(), diag::note_previous_declaration); 2133 } 2134 ShadowingDecls.erase(ShadowI); 2135 } 2136 } 2137 } 2138 2139 /// Look for an Objective-C class in the translation unit. 2140 /// 2141 /// \param Id The name of the Objective-C class we're looking for. If 2142 /// typo-correction fixes this name, the Id will be updated 2143 /// to the fixed name. 2144 /// 2145 /// \param IdLoc The location of the name in the translation unit. 2146 /// 2147 /// \param DoTypoCorrection If true, this routine will attempt typo correction 2148 /// if there is no class with the given name. 2149 /// 2150 /// \returns The declaration of the named Objective-C class, or NULL if the 2151 /// class could not be found. 2152 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 2153 SourceLocation IdLoc, 2154 bool DoTypoCorrection) { 2155 // The third "scope" argument is 0 since we aren't enabling lazy built-in 2156 // creation from this context. 2157 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 2158 2159 if (!IDecl && DoTypoCorrection) { 2160 // Perform typo correction at the given location, but only if we 2161 // find an Objective-C class name. 2162 DeclFilterCCC<ObjCInterfaceDecl> CCC{}; 2163 if (TypoCorrection C = 2164 CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, 2165 TUScope, nullptr, CCC, CTK_ErrorRecovery)) { 2166 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 2167 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 2168 Id = IDecl->getIdentifier(); 2169 } 2170 } 2171 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 2172 // This routine must always return a class definition, if any. 2173 if (Def && Def->getDefinition()) 2174 Def = Def->getDefinition(); 2175 return Def; 2176 } 2177 2178 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 2179 /// from S, where a non-field would be declared. This routine copes 2180 /// with the difference between C and C++ scoping rules in structs and 2181 /// unions. For example, the following code is well-formed in C but 2182 /// ill-formed in C++: 2183 /// @code 2184 /// struct S6 { 2185 /// enum { BAR } e; 2186 /// }; 2187 /// 2188 /// void test_S6() { 2189 /// struct S6 a; 2190 /// a.e = BAR; 2191 /// } 2192 /// @endcode 2193 /// For the declaration of BAR, this routine will return a different 2194 /// scope. The scope S will be the scope of the unnamed enumeration 2195 /// within S6. In C++, this routine will return the scope associated 2196 /// with S6, because the enumeration's scope is a transparent 2197 /// context but structures can contain non-field names. In C, this 2198 /// routine will return the translation unit scope, since the 2199 /// enumeration's scope is a transparent context and structures cannot 2200 /// contain non-field names. 2201 Scope *Sema::getNonFieldDeclScope(Scope *S) { 2202 while (((S->getFlags() & Scope::DeclScope) == 0) || 2203 (S->getEntity() && S->getEntity()->isTransparentContext()) || 2204 (S->isClassScope() && !getLangOpts().CPlusPlus)) 2205 S = S->getParent(); 2206 return S; 2207 } 2208 2209 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, 2210 ASTContext::GetBuiltinTypeError Error) { 2211 switch (Error) { 2212 case ASTContext::GE_None: 2213 return ""; 2214 case ASTContext::GE_Missing_type: 2215 return BuiltinInfo.getHeaderName(ID); 2216 case ASTContext::GE_Missing_stdio: 2217 return "stdio.h"; 2218 case ASTContext::GE_Missing_setjmp: 2219 return "setjmp.h"; 2220 case ASTContext::GE_Missing_ucontext: 2221 return "ucontext.h"; 2222 } 2223 llvm_unreachable("unhandled error kind"); 2224 } 2225 2226 FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type, 2227 unsigned ID, SourceLocation Loc) { 2228 DeclContext *Parent = Context.getTranslationUnitDecl(); 2229 2230 if (getLangOpts().CPlusPlus) { 2231 LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create( 2232 Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false); 2233 CLinkageDecl->setImplicit(); 2234 Parent->addDecl(CLinkageDecl); 2235 Parent = CLinkageDecl; 2236 } 2237 2238 FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type, 2239 /*TInfo=*/nullptr, SC_Extern, 2240 getCurFPFeatures().isFPConstrained(), 2241 false, Type->isFunctionProtoType()); 2242 New->setImplicit(); 2243 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID)); 2244 2245 // Create Decl objects for each parameter, adding them to the 2246 // FunctionDecl. 2247 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) { 2248 SmallVector<ParmVarDecl *, 16> Params; 2249 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 2250 ParmVarDecl *parm = ParmVarDecl::Create( 2251 Context, New, SourceLocation(), SourceLocation(), nullptr, 2252 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr); 2253 parm->setScopeInfo(0, i); 2254 Params.push_back(parm); 2255 } 2256 New->setParams(Params); 2257 } 2258 2259 AddKnownFunctionAttributes(New); 2260 return New; 2261 } 2262 2263 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 2264 /// file scope. lazily create a decl for it. ForRedeclaration is true 2265 /// if we're creating this built-in in anticipation of redeclaring the 2266 /// built-in. 2267 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 2268 Scope *S, bool ForRedeclaration, 2269 SourceLocation Loc) { 2270 LookupNecessaryTypesForBuiltin(S, ID); 2271 2272 ASTContext::GetBuiltinTypeError Error; 2273 QualType R = Context.GetBuiltinType(ID, Error); 2274 if (Error) { 2275 if (!ForRedeclaration) 2276 return nullptr; 2277 2278 // If we have a builtin without an associated type we should not emit a 2279 // warning when we were not able to find a type for it. 2280 if (Error == ASTContext::GE_Missing_type || 2281 Context.BuiltinInfo.allowTypeMismatch(ID)) 2282 return nullptr; 2283 2284 // If we could not find a type for setjmp it is because the jmp_buf type was 2285 // not defined prior to the setjmp declaration. 2286 if (Error == ASTContext::GE_Missing_setjmp) { 2287 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf) 2288 << Context.BuiltinInfo.getName(ID); 2289 return nullptr; 2290 } 2291 2292 // Generally, we emit a warning that the declaration requires the 2293 // appropriate header. 2294 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 2295 << getHeaderName(Context.BuiltinInfo, ID, Error) 2296 << Context.BuiltinInfo.getName(ID); 2297 return nullptr; 2298 } 2299 2300 if (!ForRedeclaration && 2301 (Context.BuiltinInfo.isPredefinedLibFunction(ID) || 2302 Context.BuiltinInfo.isHeaderDependentFunction(ID))) { 2303 Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99 2304 : diag::ext_implicit_lib_function_decl) 2305 << Context.BuiltinInfo.getName(ID) << R; 2306 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID)) 2307 Diag(Loc, diag::note_include_header_or_declare) 2308 << Header << Context.BuiltinInfo.getName(ID); 2309 } 2310 2311 if (R.isNull()) 2312 return nullptr; 2313 2314 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc); 2315 RegisterLocallyScopedExternCDecl(New, S); 2316 2317 // TUScope is the translation-unit scope to insert this function into. 2318 // FIXME: This is hideous. We need to teach PushOnScopeChains to 2319 // relate Scopes to DeclContexts, and probably eliminate CurContext 2320 // entirely, but we're not there yet. 2321 DeclContext *SavedContext = CurContext; 2322 CurContext = New->getDeclContext(); 2323 PushOnScopeChains(New, TUScope); 2324 CurContext = SavedContext; 2325 return New; 2326 } 2327 2328 /// Typedef declarations don't have linkage, but they still denote the same 2329 /// entity if their types are the same. 2330 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 2331 /// isSameEntity. 2332 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 2333 TypedefNameDecl *Decl, 2334 LookupResult &Previous) { 2335 // This is only interesting when modules are enabled. 2336 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 2337 return; 2338 2339 // Empty sets are uninteresting. 2340 if (Previous.empty()) 2341 return; 2342 2343 LookupResult::Filter Filter = Previous.makeFilter(); 2344 while (Filter.hasNext()) { 2345 NamedDecl *Old = Filter.next(); 2346 2347 // Non-hidden declarations are never ignored. 2348 if (S.isVisible(Old)) 2349 continue; 2350 2351 // Declarations of the same entity are not ignored, even if they have 2352 // different linkages. 2353 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2354 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 2355 Decl->getUnderlyingType())) 2356 continue; 2357 2358 // If both declarations give a tag declaration a typedef name for linkage 2359 // purposes, then they declare the same entity. 2360 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 2361 Decl->getAnonDeclWithTypedefName()) 2362 continue; 2363 } 2364 2365 Filter.erase(); 2366 } 2367 2368 Filter.done(); 2369 } 2370 2371 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 2372 QualType OldType; 2373 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 2374 OldType = OldTypedef->getUnderlyingType(); 2375 else 2376 OldType = Context.getTypeDeclType(Old); 2377 QualType NewType = New->getUnderlyingType(); 2378 2379 if (NewType->isVariablyModifiedType()) { 2380 // Must not redefine a typedef with a variably-modified type. 2381 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2382 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 2383 << Kind << NewType; 2384 if (Old->getLocation().isValid()) 2385 notePreviousDefinition(Old, New->getLocation()); 2386 New->setInvalidDecl(); 2387 return true; 2388 } 2389 2390 if (OldType != NewType && 2391 !OldType->isDependentType() && 2392 !NewType->isDependentType() && 2393 !Context.hasSameType(OldType, NewType)) { 2394 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2395 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 2396 << Kind << NewType << OldType; 2397 if (Old->getLocation().isValid()) 2398 notePreviousDefinition(Old, New->getLocation()); 2399 New->setInvalidDecl(); 2400 return true; 2401 } 2402 return false; 2403 } 2404 2405 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 2406 /// same name and scope as a previous declaration 'Old'. Figure out 2407 /// how to resolve this situation, merging decls or emitting 2408 /// diagnostics as appropriate. If there was an error, set New to be invalid. 2409 /// 2410 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 2411 LookupResult &OldDecls) { 2412 // If the new decl is known invalid already, don't bother doing any 2413 // merging checks. 2414 if (New->isInvalidDecl()) return; 2415 2416 // Allow multiple definitions for ObjC built-in typedefs. 2417 // FIXME: Verify the underlying types are equivalent! 2418 if (getLangOpts().ObjC) { 2419 const IdentifierInfo *TypeID = New->getIdentifier(); 2420 switch (TypeID->getLength()) { 2421 default: break; 2422 case 2: 2423 { 2424 if (!TypeID->isStr("id")) 2425 break; 2426 QualType T = New->getUnderlyingType(); 2427 if (!T->isPointerType()) 2428 break; 2429 if (!T->isVoidPointerType()) { 2430 QualType PT = T->castAs<PointerType>()->getPointeeType(); 2431 if (!PT->isStructureType()) 2432 break; 2433 } 2434 Context.setObjCIdRedefinitionType(T); 2435 // Install the built-in type for 'id', ignoring the current definition. 2436 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 2437 return; 2438 } 2439 case 5: 2440 if (!TypeID->isStr("Class")) 2441 break; 2442 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 2443 // Install the built-in type for 'Class', ignoring the current definition. 2444 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 2445 return; 2446 case 3: 2447 if (!TypeID->isStr("SEL")) 2448 break; 2449 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 2450 // Install the built-in type for 'SEL', ignoring the current definition. 2451 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 2452 return; 2453 } 2454 // Fall through - the typedef name was not a builtin type. 2455 } 2456 2457 // Verify the old decl was also a type. 2458 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 2459 if (!Old) { 2460 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2461 << New->getDeclName(); 2462 2463 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 2464 if (OldD->getLocation().isValid()) 2465 notePreviousDefinition(OldD, New->getLocation()); 2466 2467 return New->setInvalidDecl(); 2468 } 2469 2470 // If the old declaration is invalid, just give up here. 2471 if (Old->isInvalidDecl()) 2472 return New->setInvalidDecl(); 2473 2474 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2475 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2476 auto *NewTag = New->getAnonDeclWithTypedefName(); 2477 NamedDecl *Hidden = nullptr; 2478 if (OldTag && NewTag && 2479 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 2480 !hasVisibleDefinition(OldTag, &Hidden)) { 2481 // There is a definition of this tag, but it is not visible. Use it 2482 // instead of our tag. 2483 New->setTypeForDecl(OldTD->getTypeForDecl()); 2484 if (OldTD->isModed()) 2485 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 2486 OldTD->getUnderlyingType()); 2487 else 2488 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 2489 2490 // Make the old tag definition visible. 2491 makeMergedDefinitionVisible(Hidden); 2492 2493 // If this was an unscoped enumeration, yank all of its enumerators 2494 // out of the scope. 2495 if (isa<EnumDecl>(NewTag)) { 2496 Scope *EnumScope = getNonFieldDeclScope(S); 2497 for (auto *D : NewTag->decls()) { 2498 auto *ED = cast<EnumConstantDecl>(D); 2499 assert(EnumScope->isDeclScope(ED)); 2500 EnumScope->RemoveDecl(ED); 2501 IdResolver.RemoveDecl(ED); 2502 ED->getLexicalDeclContext()->removeDecl(ED); 2503 } 2504 } 2505 } 2506 } 2507 2508 // If the typedef types are not identical, reject them in all languages and 2509 // with any extensions enabled. 2510 if (isIncompatibleTypedef(Old, New)) 2511 return; 2512 2513 // The types match. Link up the redeclaration chain and merge attributes if 2514 // the old declaration was a typedef. 2515 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2516 New->setPreviousDecl(Typedef); 2517 mergeDeclAttributes(New, Old); 2518 } 2519 2520 if (getLangOpts().MicrosoftExt) 2521 return; 2522 2523 if (getLangOpts().CPlusPlus) { 2524 // C++ [dcl.typedef]p2: 2525 // In a given non-class scope, a typedef specifier can be used to 2526 // redefine the name of any type declared in that scope to refer 2527 // to the type to which it already refers. 2528 if (!isa<CXXRecordDecl>(CurContext)) 2529 return; 2530 2531 // C++0x [dcl.typedef]p4: 2532 // In a given class scope, a typedef specifier can be used to redefine 2533 // any class-name declared in that scope that is not also a typedef-name 2534 // to refer to the type to which it already refers. 2535 // 2536 // This wording came in via DR424, which was a correction to the 2537 // wording in DR56, which accidentally banned code like: 2538 // 2539 // struct S { 2540 // typedef struct A { } A; 2541 // }; 2542 // 2543 // in the C++03 standard. We implement the C++0x semantics, which 2544 // allow the above but disallow 2545 // 2546 // struct S { 2547 // typedef int I; 2548 // typedef int I; 2549 // }; 2550 // 2551 // since that was the intent of DR56. 2552 if (!isa<TypedefNameDecl>(Old)) 2553 return; 2554 2555 Diag(New->getLocation(), diag::err_redefinition) 2556 << New->getDeclName(); 2557 notePreviousDefinition(Old, New->getLocation()); 2558 return New->setInvalidDecl(); 2559 } 2560 2561 // Modules always permit redefinition of typedefs, as does C11. 2562 if (getLangOpts().Modules || getLangOpts().C11) 2563 return; 2564 2565 // If we have a redefinition of a typedef in C, emit a warning. This warning 2566 // is normally mapped to an error, but can be controlled with 2567 // -Wtypedef-redefinition. If either the original or the redefinition is 2568 // in a system header, don't emit this for compatibility with GCC. 2569 if (getDiagnostics().getSuppressSystemWarnings() && 2570 // Some standard types are defined implicitly in Clang (e.g. OpenCL). 2571 (Old->isImplicit() || 2572 Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2573 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2574 return; 2575 2576 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2577 << New->getDeclName(); 2578 notePreviousDefinition(Old, New->getLocation()); 2579 } 2580 2581 /// DeclhasAttr - returns true if decl Declaration already has the target 2582 /// attribute. 2583 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2584 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2585 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2586 for (const auto *i : D->attrs()) 2587 if (i->getKind() == A->getKind()) { 2588 if (Ann) { 2589 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2590 return true; 2591 continue; 2592 } 2593 // FIXME: Don't hardcode this check 2594 if (OA && isa<OwnershipAttr>(i)) 2595 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2596 return true; 2597 } 2598 2599 return false; 2600 } 2601 2602 static bool isAttributeTargetADefinition(Decl *D) { 2603 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2604 return VD->isThisDeclarationADefinition(); 2605 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2606 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2607 return true; 2608 } 2609 2610 /// Merge alignment attributes from \p Old to \p New, taking into account the 2611 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2612 /// 2613 /// \return \c true if any attributes were added to \p New. 2614 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2615 // Look for alignas attributes on Old, and pick out whichever attribute 2616 // specifies the strictest alignment requirement. 2617 AlignedAttr *OldAlignasAttr = nullptr; 2618 AlignedAttr *OldStrictestAlignAttr = nullptr; 2619 unsigned OldAlign = 0; 2620 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2621 // FIXME: We have no way of representing inherited dependent alignments 2622 // in a case like: 2623 // template<int A, int B> struct alignas(A) X; 2624 // template<int A, int B> struct alignas(B) X {}; 2625 // For now, we just ignore any alignas attributes which are not on the 2626 // definition in such a case. 2627 if (I->isAlignmentDependent()) 2628 return false; 2629 2630 if (I->isAlignas()) 2631 OldAlignasAttr = I; 2632 2633 unsigned Align = I->getAlignment(S.Context); 2634 if (Align > OldAlign) { 2635 OldAlign = Align; 2636 OldStrictestAlignAttr = I; 2637 } 2638 } 2639 2640 // Look for alignas attributes on New. 2641 AlignedAttr *NewAlignasAttr = nullptr; 2642 unsigned NewAlign = 0; 2643 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2644 if (I->isAlignmentDependent()) 2645 return false; 2646 2647 if (I->isAlignas()) 2648 NewAlignasAttr = I; 2649 2650 unsigned Align = I->getAlignment(S.Context); 2651 if (Align > NewAlign) 2652 NewAlign = Align; 2653 } 2654 2655 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2656 // Both declarations have 'alignas' attributes. We require them to match. 2657 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2658 // fall short. (If two declarations both have alignas, they must both match 2659 // every definition, and so must match each other if there is a definition.) 2660 2661 // If either declaration only contains 'alignas(0)' specifiers, then it 2662 // specifies the natural alignment for the type. 2663 if (OldAlign == 0 || NewAlign == 0) { 2664 QualType Ty; 2665 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2666 Ty = VD->getType(); 2667 else 2668 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2669 2670 if (OldAlign == 0) 2671 OldAlign = S.Context.getTypeAlign(Ty); 2672 if (NewAlign == 0) 2673 NewAlign = S.Context.getTypeAlign(Ty); 2674 } 2675 2676 if (OldAlign != NewAlign) { 2677 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2678 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2679 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2680 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2681 } 2682 } 2683 2684 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2685 // C++11 [dcl.align]p6: 2686 // if any declaration of an entity has an alignment-specifier, 2687 // every defining declaration of that entity shall specify an 2688 // equivalent alignment. 2689 // C11 6.7.5/7: 2690 // If the definition of an object does not have an alignment 2691 // specifier, any other declaration of that object shall also 2692 // have no alignment specifier. 2693 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2694 << OldAlignasAttr; 2695 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2696 << OldAlignasAttr; 2697 } 2698 2699 bool AnyAdded = false; 2700 2701 // Ensure we have an attribute representing the strictest alignment. 2702 if (OldAlign > NewAlign) { 2703 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2704 Clone->setInherited(true); 2705 New->addAttr(Clone); 2706 AnyAdded = true; 2707 } 2708 2709 // Ensure we have an alignas attribute if the old declaration had one. 2710 if (OldAlignasAttr && !NewAlignasAttr && 2711 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2712 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2713 Clone->setInherited(true); 2714 New->addAttr(Clone); 2715 AnyAdded = true; 2716 } 2717 2718 return AnyAdded; 2719 } 2720 2721 #define WANT_DECL_MERGE_LOGIC 2722 #include "clang/Sema/AttrParsedAttrImpl.inc" 2723 #undef WANT_DECL_MERGE_LOGIC 2724 2725 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2726 const InheritableAttr *Attr, 2727 Sema::AvailabilityMergeKind AMK) { 2728 // Diagnose any mutual exclusions between the attribute that we want to add 2729 // and attributes that already exist on the declaration. 2730 if (!DiagnoseMutualExclusions(S, D, Attr)) 2731 return false; 2732 2733 // This function copies an attribute Attr from a previous declaration to the 2734 // new declaration D if the new declaration doesn't itself have that attribute 2735 // yet or if that attribute allows duplicates. 2736 // If you're adding a new attribute that requires logic different from 2737 // "use explicit attribute on decl if present, else use attribute from 2738 // previous decl", for example if the attribute needs to be consistent 2739 // between redeclarations, you need to call a custom merge function here. 2740 InheritableAttr *NewAttr = nullptr; 2741 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2742 NewAttr = S.mergeAvailabilityAttr( 2743 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(), 2744 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(), 2745 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK, 2746 AA->getPriority()); 2747 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2748 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility()); 2749 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2750 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility()); 2751 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2752 NewAttr = S.mergeDLLImportAttr(D, *ImportA); 2753 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2754 NewAttr = S.mergeDLLExportAttr(D, *ExportA); 2755 else if (const auto *EA = dyn_cast<ErrorAttr>(Attr)) 2756 NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic()); 2757 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2758 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(), 2759 FA->getFirstArg()); 2760 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2761 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName()); 2762 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr)) 2763 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName()); 2764 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2765 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(), 2766 IA->getInheritanceModel()); 2767 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2768 NewAttr = S.mergeAlwaysInlineAttr(D, *AA, 2769 &S.Context.Idents.get(AA->getSpelling())); 2770 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2771 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2772 isa<CUDAGlobalAttr>(Attr))) { 2773 // CUDA target attributes are part of function signature for 2774 // overloading purposes and must not be merged. 2775 return false; 2776 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2777 NewAttr = S.mergeMinSizeAttr(D, *MA); 2778 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr)) 2779 NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName()); 2780 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2781 NewAttr = S.mergeOptimizeNoneAttr(D, *OA); 2782 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2783 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA); 2784 else if (isa<AlignedAttr>(Attr)) 2785 // AlignedAttrs are handled separately, because we need to handle all 2786 // such attributes on a declaration at the same time. 2787 NewAttr = nullptr; 2788 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2789 (AMK == Sema::AMK_Override || 2790 AMK == Sema::AMK_ProtocolImplementation || 2791 AMK == Sema::AMK_OptionalProtocolImplementation)) 2792 NewAttr = nullptr; 2793 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2794 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl()); 2795 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr)) 2796 NewAttr = S.mergeImportModuleAttr(D, *IMA); 2797 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr)) 2798 NewAttr = S.mergeImportNameAttr(D, *INA); 2799 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr)) 2800 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA); 2801 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr)) 2802 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA); 2803 else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr)) 2804 NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA); 2805 else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr)) 2806 NewAttr = 2807 S.mergeHLSLNumThreadsAttr(D, *NT, NT->getX(), NT->getY(), NT->getZ()); 2808 else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr)) 2809 NewAttr = S.mergeHLSLShaderAttr(D, *SA, SA->getType()); 2810 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr)) 2811 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2812 2813 if (NewAttr) { 2814 NewAttr->setInherited(true); 2815 D->addAttr(NewAttr); 2816 if (isa<MSInheritanceAttr>(NewAttr)) 2817 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2818 return true; 2819 } 2820 2821 return false; 2822 } 2823 2824 static const NamedDecl *getDefinition(const Decl *D) { 2825 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2826 return TD->getDefinition(); 2827 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2828 const VarDecl *Def = VD->getDefinition(); 2829 if (Def) 2830 return Def; 2831 return VD->getActingDefinition(); 2832 } 2833 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2834 const FunctionDecl *Def = nullptr; 2835 if (FD->isDefined(Def, true)) 2836 return Def; 2837 } 2838 return nullptr; 2839 } 2840 2841 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2842 for (const auto *Attribute : D->attrs()) 2843 if (Attribute->getKind() == Kind) 2844 return true; 2845 return false; 2846 } 2847 2848 /// checkNewAttributesAfterDef - If we already have a definition, check that 2849 /// there are no new attributes in this declaration. 2850 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2851 if (!New->hasAttrs()) 2852 return; 2853 2854 const NamedDecl *Def = getDefinition(Old); 2855 if (!Def || Def == New) 2856 return; 2857 2858 AttrVec &NewAttributes = New->getAttrs(); 2859 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2860 const Attr *NewAttribute = NewAttributes[I]; 2861 2862 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 2863 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2864 Sema::SkipBodyInfo SkipBody; 2865 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2866 2867 // If we're skipping this definition, drop the "alias" attribute. 2868 if (SkipBody.ShouldSkip) { 2869 NewAttributes.erase(NewAttributes.begin() + I); 2870 --E; 2871 continue; 2872 } 2873 } else { 2874 VarDecl *VD = cast<VarDecl>(New); 2875 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2876 VarDecl::TentativeDefinition 2877 ? diag::err_alias_after_tentative 2878 : diag::err_redefinition; 2879 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2880 if (Diag == diag::err_redefinition) 2881 S.notePreviousDefinition(Def, VD->getLocation()); 2882 else 2883 S.Diag(Def->getLocation(), diag::note_previous_definition); 2884 VD->setInvalidDecl(); 2885 } 2886 ++I; 2887 continue; 2888 } 2889 2890 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2891 // Tentative definitions are only interesting for the alias check above. 2892 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2893 ++I; 2894 continue; 2895 } 2896 } 2897 2898 if (hasAttribute(Def, NewAttribute->getKind())) { 2899 ++I; 2900 continue; // regular attr merging will take care of validating this. 2901 } 2902 2903 if (isa<C11NoReturnAttr>(NewAttribute)) { 2904 // C's _Noreturn is allowed to be added to a function after it is defined. 2905 ++I; 2906 continue; 2907 } else if (isa<UuidAttr>(NewAttribute)) { 2908 // msvc will allow a subsequent definition to add an uuid to a class 2909 ++I; 2910 continue; 2911 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2912 if (AA->isAlignas()) { 2913 // C++11 [dcl.align]p6: 2914 // if any declaration of an entity has an alignment-specifier, 2915 // every defining declaration of that entity shall specify an 2916 // equivalent alignment. 2917 // C11 6.7.5/7: 2918 // If the definition of an object does not have an alignment 2919 // specifier, any other declaration of that object shall also 2920 // have no alignment specifier. 2921 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2922 << AA; 2923 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2924 << AA; 2925 NewAttributes.erase(NewAttributes.begin() + I); 2926 --E; 2927 continue; 2928 } 2929 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) { 2930 // If there is a C definition followed by a redeclaration with this 2931 // attribute then there are two different definitions. In C++, prefer the 2932 // standard diagnostics. 2933 if (!S.getLangOpts().CPlusPlus) { 2934 S.Diag(NewAttribute->getLocation(), 2935 diag::err_loader_uninitialized_redeclaration); 2936 S.Diag(Def->getLocation(), diag::note_previous_definition); 2937 NewAttributes.erase(NewAttributes.begin() + I); 2938 --E; 2939 continue; 2940 } 2941 } else if (isa<SelectAnyAttr>(NewAttribute) && 2942 cast<VarDecl>(New)->isInline() && 2943 !cast<VarDecl>(New)->isInlineSpecified()) { 2944 // Don't warn about applying selectany to implicitly inline variables. 2945 // Older compilers and language modes would require the use of selectany 2946 // to make such variables inline, and it would have no effect if we 2947 // honored it. 2948 ++I; 2949 continue; 2950 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) { 2951 // We allow to add OMP[Begin]DeclareVariantAttr to be added to 2952 // declarations after defintions. 2953 ++I; 2954 continue; 2955 } 2956 2957 S.Diag(NewAttribute->getLocation(), 2958 diag::warn_attribute_precede_definition); 2959 S.Diag(Def->getLocation(), diag::note_previous_definition); 2960 NewAttributes.erase(NewAttributes.begin() + I); 2961 --E; 2962 } 2963 } 2964 2965 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, 2966 const ConstInitAttr *CIAttr, 2967 bool AttrBeforeInit) { 2968 SourceLocation InsertLoc = InitDecl->getInnerLocStart(); 2969 2970 // Figure out a good way to write this specifier on the old declaration. 2971 // FIXME: We should just use the spelling of CIAttr, but we don't preserve 2972 // enough of the attribute list spelling information to extract that without 2973 // heroics. 2974 std::string SuitableSpelling; 2975 if (S.getLangOpts().CPlusPlus20) 2976 SuitableSpelling = std::string( 2977 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit})); 2978 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2979 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2980 InsertLoc, {tok::l_square, tok::l_square, 2981 S.PP.getIdentifierInfo("clang"), tok::coloncolon, 2982 S.PP.getIdentifierInfo("require_constant_initialization"), 2983 tok::r_square, tok::r_square})); 2984 if (SuitableSpelling.empty()) 2985 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2986 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren, 2987 S.PP.getIdentifierInfo("require_constant_initialization"), 2988 tok::r_paren, tok::r_paren})); 2989 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20) 2990 SuitableSpelling = "constinit"; 2991 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2992 SuitableSpelling = "[[clang::require_constant_initialization]]"; 2993 if (SuitableSpelling.empty()) 2994 SuitableSpelling = "__attribute__((require_constant_initialization))"; 2995 SuitableSpelling += " "; 2996 2997 if (AttrBeforeInit) { 2998 // extern constinit int a; 2999 // int a = 0; // error (missing 'constinit'), accepted as extension 3000 assert(CIAttr->isConstinit() && "should not diagnose this for attribute"); 3001 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing) 3002 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 3003 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here); 3004 } else { 3005 // int a = 0; 3006 // constinit extern int a; // error (missing 'constinit') 3007 S.Diag(CIAttr->getLocation(), 3008 CIAttr->isConstinit() ? diag::err_constinit_added_too_late 3009 : diag::warn_require_const_init_added_too_late) 3010 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation())); 3011 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here) 3012 << CIAttr->isConstinit() 3013 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 3014 } 3015 } 3016 3017 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 3018 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 3019 AvailabilityMergeKind AMK) { 3020 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 3021 UsedAttr *NewAttr = OldAttr->clone(Context); 3022 NewAttr->setInherited(true); 3023 New->addAttr(NewAttr); 3024 } 3025 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) { 3026 RetainAttr *NewAttr = OldAttr->clone(Context); 3027 NewAttr->setInherited(true); 3028 New->addAttr(NewAttr); 3029 } 3030 3031 if (!Old->hasAttrs() && !New->hasAttrs()) 3032 return; 3033 3034 // [dcl.constinit]p1: 3035 // If the [constinit] specifier is applied to any declaration of a 3036 // variable, it shall be applied to the initializing declaration. 3037 const auto *OldConstInit = Old->getAttr<ConstInitAttr>(); 3038 const auto *NewConstInit = New->getAttr<ConstInitAttr>(); 3039 if (bool(OldConstInit) != bool(NewConstInit)) { 3040 const auto *OldVD = cast<VarDecl>(Old); 3041 auto *NewVD = cast<VarDecl>(New); 3042 3043 // Find the initializing declaration. Note that we might not have linked 3044 // the new declaration into the redeclaration chain yet. 3045 const VarDecl *InitDecl = OldVD->getInitializingDeclaration(); 3046 if (!InitDecl && 3047 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition())) 3048 InitDecl = NewVD; 3049 3050 if (InitDecl == NewVD) { 3051 // This is the initializing declaration. If it would inherit 'constinit', 3052 // that's ill-formed. (Note that we do not apply this to the attribute 3053 // form). 3054 if (OldConstInit && OldConstInit->isConstinit()) 3055 diagnoseMissingConstinit(*this, NewVD, OldConstInit, 3056 /*AttrBeforeInit=*/true); 3057 } else if (NewConstInit) { 3058 // This is the first time we've been told that this declaration should 3059 // have a constant initializer. If we already saw the initializing 3060 // declaration, this is too late. 3061 if (InitDecl && InitDecl != NewVD) { 3062 diagnoseMissingConstinit(*this, InitDecl, NewConstInit, 3063 /*AttrBeforeInit=*/false); 3064 NewVD->dropAttr<ConstInitAttr>(); 3065 } 3066 } 3067 } 3068 3069 // Attributes declared post-definition are currently ignored. 3070 checkNewAttributesAfterDef(*this, New, Old); 3071 3072 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 3073 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 3074 if (!OldA->isEquivalent(NewA)) { 3075 // This redeclaration changes __asm__ label. 3076 Diag(New->getLocation(), diag::err_different_asm_label); 3077 Diag(OldA->getLocation(), diag::note_previous_declaration); 3078 } 3079 } else if (Old->isUsed()) { 3080 // This redeclaration adds an __asm__ label to a declaration that has 3081 // already been ODR-used. 3082 Diag(New->getLocation(), diag::err_late_asm_label_name) 3083 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 3084 } 3085 } 3086 3087 // Re-declaration cannot add abi_tag's. 3088 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 3089 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 3090 for (const auto &NewTag : NewAbiTagAttr->tags()) { 3091 if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) { 3092 Diag(NewAbiTagAttr->getLocation(), 3093 diag::err_new_abi_tag_on_redeclaration) 3094 << NewTag; 3095 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 3096 } 3097 } 3098 } else { 3099 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 3100 Diag(Old->getLocation(), diag::note_previous_declaration); 3101 } 3102 } 3103 3104 // This redeclaration adds a section attribute. 3105 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { 3106 if (auto *VD = dyn_cast<VarDecl>(New)) { 3107 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) { 3108 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration); 3109 Diag(Old->getLocation(), diag::note_previous_declaration); 3110 } 3111 } 3112 } 3113 3114 // Redeclaration adds code-seg attribute. 3115 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 3116 if (NewCSA && !Old->hasAttr<CodeSegAttr>() && 3117 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) { 3118 Diag(New->getLocation(), diag::warn_mismatched_section) 3119 << 0 /*codeseg*/; 3120 Diag(Old->getLocation(), diag::note_previous_declaration); 3121 } 3122 3123 if (!Old->hasAttrs()) 3124 return; 3125 3126 bool foundAny = New->hasAttrs(); 3127 3128 // Ensure that any moving of objects within the allocated map is done before 3129 // we process them. 3130 if (!foundAny) New->setAttrs(AttrVec()); 3131 3132 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 3133 // Ignore deprecated/unavailable/availability attributes if requested. 3134 AvailabilityMergeKind LocalAMK = AMK_None; 3135 if (isa<DeprecatedAttr>(I) || 3136 isa<UnavailableAttr>(I) || 3137 isa<AvailabilityAttr>(I)) { 3138 switch (AMK) { 3139 case AMK_None: 3140 continue; 3141 3142 case AMK_Redeclaration: 3143 case AMK_Override: 3144 case AMK_ProtocolImplementation: 3145 case AMK_OptionalProtocolImplementation: 3146 LocalAMK = AMK; 3147 break; 3148 } 3149 } 3150 3151 // Already handled. 3152 if (isa<UsedAttr>(I) || isa<RetainAttr>(I)) 3153 continue; 3154 3155 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 3156 foundAny = true; 3157 } 3158 3159 if (mergeAlignedAttrs(*this, New, Old)) 3160 foundAny = true; 3161 3162 if (!foundAny) New->dropAttrs(); 3163 } 3164 3165 /// mergeParamDeclAttributes - Copy attributes from the old parameter 3166 /// to the new one. 3167 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 3168 const ParmVarDecl *oldDecl, 3169 Sema &S) { 3170 // C++11 [dcl.attr.depend]p2: 3171 // The first declaration of a function shall specify the 3172 // carries_dependency attribute for its declarator-id if any declaration 3173 // of the function specifies the carries_dependency attribute. 3174 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 3175 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 3176 S.Diag(CDA->getLocation(), 3177 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 3178 // Find the first declaration of the parameter. 3179 // FIXME: Should we build redeclaration chains for function parameters? 3180 const FunctionDecl *FirstFD = 3181 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 3182 const ParmVarDecl *FirstVD = 3183 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 3184 S.Diag(FirstVD->getLocation(), 3185 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 3186 } 3187 3188 if (!oldDecl->hasAttrs()) 3189 return; 3190 3191 bool foundAny = newDecl->hasAttrs(); 3192 3193 // Ensure that any moving of objects within the allocated map is 3194 // done before we process them. 3195 if (!foundAny) newDecl->setAttrs(AttrVec()); 3196 3197 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 3198 if (!DeclHasAttr(newDecl, I)) { 3199 InheritableAttr *newAttr = 3200 cast<InheritableParamAttr>(I->clone(S.Context)); 3201 newAttr->setInherited(true); 3202 newDecl->addAttr(newAttr); 3203 foundAny = true; 3204 } 3205 } 3206 3207 if (!foundAny) newDecl->dropAttrs(); 3208 } 3209 3210 static bool EquivalentArrayTypes(QualType Old, QualType New, 3211 const ASTContext &Ctx) { 3212 3213 auto NoSizeInfo = [&Ctx](QualType Ty) { 3214 if (Ty->isIncompleteArrayType() || Ty->isPointerType()) 3215 return true; 3216 if (const auto *VAT = Ctx.getAsVariableArrayType(Ty)) 3217 return VAT->getSizeModifier() == ArrayType::ArraySizeModifier::Star; 3218 return false; 3219 }; 3220 3221 // `type[]` is equivalent to `type *` and `type[*]`. 3222 if (NoSizeInfo(Old) && NoSizeInfo(New)) 3223 return true; 3224 3225 // Don't try to compare VLA sizes, unless one of them has the star modifier. 3226 if (Old->isVariableArrayType() && New->isVariableArrayType()) { 3227 const auto *OldVAT = Ctx.getAsVariableArrayType(Old); 3228 const auto *NewVAT = Ctx.getAsVariableArrayType(New); 3229 if ((OldVAT->getSizeModifier() == ArrayType::ArraySizeModifier::Star) ^ 3230 (NewVAT->getSizeModifier() == ArrayType::ArraySizeModifier::Star)) 3231 return false; 3232 return true; 3233 } 3234 3235 // Only compare size, ignore Size modifiers and CVR. 3236 if (Old->isConstantArrayType() && New->isConstantArrayType()) 3237 return Ctx.getAsConstantArrayType(Old)->getSize() == 3238 Ctx.getAsConstantArrayType(New)->getSize(); 3239 3240 return Old == New; 3241 } 3242 3243 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 3244 const ParmVarDecl *OldParam, 3245 Sema &S) { 3246 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 3247 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 3248 if (*Oldnullability != *Newnullability) { 3249 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 3250 << DiagNullabilityKind( 3251 *Newnullability, 3252 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3253 != 0)) 3254 << DiagNullabilityKind( 3255 *Oldnullability, 3256 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3257 != 0)); 3258 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 3259 } 3260 } else { 3261 QualType NewT = NewParam->getType(); 3262 NewT = S.Context.getAttributedType( 3263 AttributedType::getNullabilityAttrKind(*Oldnullability), 3264 NewT, NewT); 3265 NewParam->setType(NewT); 3266 } 3267 } 3268 const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType()); 3269 const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType()); 3270 if (OldParamDT && NewParamDT && 3271 OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) { 3272 QualType OldParamOT = OldParamDT->getOriginalType(); 3273 QualType NewParamOT = NewParamDT->getOriginalType(); 3274 if (!EquivalentArrayTypes(OldParamOT, NewParamOT, S.getASTContext())) { 3275 S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form) 3276 << NewParam << NewParamOT; 3277 S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as) 3278 << OldParamOT; 3279 } 3280 } 3281 } 3282 3283 namespace { 3284 3285 /// Used in MergeFunctionDecl to keep track of function parameters in 3286 /// C. 3287 struct GNUCompatibleParamWarning { 3288 ParmVarDecl *OldParm; 3289 ParmVarDecl *NewParm; 3290 QualType PromotedType; 3291 }; 3292 3293 } // end anonymous namespace 3294 3295 // Determine whether the previous declaration was a definition, implicit 3296 // declaration, or a declaration. 3297 template <typename T> 3298 static std::pair<diag::kind, SourceLocation> 3299 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 3300 diag::kind PrevDiag; 3301 SourceLocation OldLocation = Old->getLocation(); 3302 if (Old->isThisDeclarationADefinition()) 3303 PrevDiag = diag::note_previous_definition; 3304 else if (Old->isImplicit()) { 3305 PrevDiag = diag::note_previous_implicit_declaration; 3306 if (const auto *FD = dyn_cast<FunctionDecl>(Old)) { 3307 if (FD->getBuiltinID()) 3308 PrevDiag = diag::note_previous_builtin_declaration; 3309 } 3310 if (OldLocation.isInvalid()) 3311 OldLocation = New->getLocation(); 3312 } else 3313 PrevDiag = diag::note_previous_declaration; 3314 return std::make_pair(PrevDiag, OldLocation); 3315 } 3316 3317 /// canRedefineFunction - checks if a function can be redefined. Currently, 3318 /// only extern inline functions can be redefined, and even then only in 3319 /// GNU89 mode. 3320 static bool canRedefineFunction(const FunctionDecl *FD, 3321 const LangOptions& LangOpts) { 3322 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 3323 !LangOpts.CPlusPlus && 3324 FD->isInlineSpecified() && 3325 FD->getStorageClass() == SC_Extern); 3326 } 3327 3328 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 3329 const AttributedType *AT = T->getAs<AttributedType>(); 3330 while (AT && !AT->isCallingConv()) 3331 AT = AT->getModifiedType()->getAs<AttributedType>(); 3332 return AT; 3333 } 3334 3335 template <typename T> 3336 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 3337 const DeclContext *DC = Old->getDeclContext(); 3338 if (DC->isRecord()) 3339 return false; 3340 3341 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 3342 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 3343 return true; 3344 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 3345 return true; 3346 return false; 3347 } 3348 3349 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 3350 static bool isExternC(VarTemplateDecl *) { return false; } 3351 static bool isExternC(FunctionTemplateDecl *) { return false; } 3352 3353 /// Check whether a redeclaration of an entity introduced by a 3354 /// using-declaration is valid, given that we know it's not an overload 3355 /// (nor a hidden tag declaration). 3356 template<typename ExpectedDecl> 3357 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 3358 ExpectedDecl *New) { 3359 // C++11 [basic.scope.declarative]p4: 3360 // Given a set of declarations in a single declarative region, each of 3361 // which specifies the same unqualified name, 3362 // -- they shall all refer to the same entity, or all refer to functions 3363 // and function templates; or 3364 // -- exactly one declaration shall declare a class name or enumeration 3365 // name that is not a typedef name and the other declarations shall all 3366 // refer to the same variable or enumerator, or all refer to functions 3367 // and function templates; in this case the class name or enumeration 3368 // name is hidden (3.3.10). 3369 3370 // C++11 [namespace.udecl]p14: 3371 // If a function declaration in namespace scope or block scope has the 3372 // same name and the same parameter-type-list as a function introduced 3373 // by a using-declaration, and the declarations do not declare the same 3374 // function, the program is ill-formed. 3375 3376 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 3377 if (Old && 3378 !Old->getDeclContext()->getRedeclContext()->Equals( 3379 New->getDeclContext()->getRedeclContext()) && 3380 !(isExternC(Old) && isExternC(New))) 3381 Old = nullptr; 3382 3383 if (!Old) { 3384 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 3385 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 3386 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0; 3387 return true; 3388 } 3389 return false; 3390 } 3391 3392 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 3393 const FunctionDecl *B) { 3394 assert(A->getNumParams() == B->getNumParams()); 3395 3396 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 3397 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 3398 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 3399 if (AttrA == AttrB) 3400 return true; 3401 return AttrA && AttrB && AttrA->getType() == AttrB->getType() && 3402 AttrA->isDynamic() == AttrB->isDynamic(); 3403 }; 3404 3405 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 3406 } 3407 3408 /// If necessary, adjust the semantic declaration context for a qualified 3409 /// declaration to name the correct inline namespace within the qualifier. 3410 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, 3411 DeclaratorDecl *OldD) { 3412 // The only case where we need to update the DeclContext is when 3413 // redeclaration lookup for a qualified name finds a declaration 3414 // in an inline namespace within the context named by the qualifier: 3415 // 3416 // inline namespace N { int f(); } 3417 // int ::f(); // Sema DC needs adjusting from :: to N::. 3418 // 3419 // For unqualified declarations, the semantic context *can* change 3420 // along the redeclaration chain (for local extern declarations, 3421 // extern "C" declarations, and friend declarations in particular). 3422 if (!NewD->getQualifier()) 3423 return; 3424 3425 // NewD is probably already in the right context. 3426 auto *NamedDC = NewD->getDeclContext()->getRedeclContext(); 3427 auto *SemaDC = OldD->getDeclContext()->getRedeclContext(); 3428 if (NamedDC->Equals(SemaDC)) 3429 return; 3430 3431 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || 3432 NewD->isInvalidDecl() || OldD->isInvalidDecl()) && 3433 "unexpected context for redeclaration"); 3434 3435 auto *LexDC = NewD->getLexicalDeclContext(); 3436 auto FixSemaDC = [=](NamedDecl *D) { 3437 if (!D) 3438 return; 3439 D->setDeclContext(SemaDC); 3440 D->setLexicalDeclContext(LexDC); 3441 }; 3442 3443 FixSemaDC(NewD); 3444 if (auto *FD = dyn_cast<FunctionDecl>(NewD)) 3445 FixSemaDC(FD->getDescribedFunctionTemplate()); 3446 else if (auto *VD = dyn_cast<VarDecl>(NewD)) 3447 FixSemaDC(VD->getDescribedVarTemplate()); 3448 } 3449 3450 /// MergeFunctionDecl - We just parsed a function 'New' from 3451 /// declarator D which has the same name and scope as a previous 3452 /// declaration 'Old'. Figure out how to resolve this situation, 3453 /// merging decls or emitting diagnostics as appropriate. 3454 /// 3455 /// In C++, New and Old must be declarations that are not 3456 /// overloaded. Use IsOverload to determine whether New and Old are 3457 /// overloaded, and to select the Old declaration that New should be 3458 /// merged with. 3459 /// 3460 /// Returns true if there was an error, false otherwise. 3461 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, Scope *S, 3462 bool MergeTypeWithOld, bool NewDeclIsDefn) { 3463 // Verify the old decl was also a function. 3464 FunctionDecl *Old = OldD->getAsFunction(); 3465 if (!Old) { 3466 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 3467 if (New->getFriendObjectKind()) { 3468 Diag(New->getLocation(), diag::err_using_decl_friend); 3469 Diag(Shadow->getTargetDecl()->getLocation(), 3470 diag::note_using_decl_target); 3471 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) 3472 << 0; 3473 return true; 3474 } 3475 3476 // Check whether the two declarations might declare the same function or 3477 // function template. 3478 if (FunctionTemplateDecl *NewTemplate = 3479 New->getDescribedFunctionTemplate()) { 3480 if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow, 3481 NewTemplate)) 3482 return true; 3483 OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl()) 3484 ->getAsFunction(); 3485 } else { 3486 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 3487 return true; 3488 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 3489 } 3490 } else { 3491 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3492 << New->getDeclName(); 3493 notePreviousDefinition(OldD, New->getLocation()); 3494 return true; 3495 } 3496 } 3497 3498 // If the old declaration was found in an inline namespace and the new 3499 // declaration was qualified, update the DeclContext to match. 3500 adjustDeclContextForDeclaratorDecl(New, Old); 3501 3502 // If the old declaration is invalid, just give up here. 3503 if (Old->isInvalidDecl()) 3504 return true; 3505 3506 // Disallow redeclaration of some builtins. 3507 if (!getASTContext().canBuiltinBeRedeclared(Old)) { 3508 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName(); 3509 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 3510 << Old << Old->getType(); 3511 return true; 3512 } 3513 3514 diag::kind PrevDiag; 3515 SourceLocation OldLocation; 3516 std::tie(PrevDiag, OldLocation) = 3517 getNoteDiagForInvalidRedeclaration(Old, New); 3518 3519 // Don't complain about this if we're in GNU89 mode and the old function 3520 // is an extern inline function. 3521 // Don't complain about specializations. They are not supposed to have 3522 // storage classes. 3523 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 3524 New->getStorageClass() == SC_Static && 3525 Old->hasExternalFormalLinkage() && 3526 !New->getTemplateSpecializationInfo() && 3527 !canRedefineFunction(Old, getLangOpts())) { 3528 if (getLangOpts().MicrosoftExt) { 3529 Diag(New->getLocation(), diag::ext_static_non_static) << New; 3530 Diag(OldLocation, PrevDiag); 3531 } else { 3532 Diag(New->getLocation(), diag::err_static_non_static) << New; 3533 Diag(OldLocation, PrevDiag); 3534 return true; 3535 } 3536 } 3537 3538 if (const auto *ILA = New->getAttr<InternalLinkageAttr>()) 3539 if (!Old->hasAttr<InternalLinkageAttr>()) { 3540 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl) 3541 << ILA; 3542 Diag(Old->getLocation(), diag::note_previous_declaration); 3543 New->dropAttr<InternalLinkageAttr>(); 3544 } 3545 3546 if (auto *EA = New->getAttr<ErrorAttr>()) { 3547 if (!Old->hasAttr<ErrorAttr>()) { 3548 Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA; 3549 Diag(Old->getLocation(), diag::note_previous_declaration); 3550 New->dropAttr<ErrorAttr>(); 3551 } 3552 } 3553 3554 if (CheckRedeclarationInModule(New, Old)) 3555 return true; 3556 3557 if (!getLangOpts().CPlusPlus) { 3558 bool OldOvl = Old->hasAttr<OverloadableAttr>(); 3559 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { 3560 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) 3561 << New << OldOvl; 3562 3563 // Try our best to find a decl that actually has the overloadable 3564 // attribute for the note. In most cases (e.g. programs with only one 3565 // broken declaration/definition), this won't matter. 3566 // 3567 // FIXME: We could do this if we juggled some extra state in 3568 // OverloadableAttr, rather than just removing it. 3569 const Decl *DiagOld = Old; 3570 if (OldOvl) { 3571 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { 3572 const auto *A = D->getAttr<OverloadableAttr>(); 3573 return A && !A->isImplicit(); 3574 }); 3575 // If we've implicitly added *all* of the overloadable attrs to this 3576 // chain, emitting a "previous redecl" note is pointless. 3577 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; 3578 } 3579 3580 if (DiagOld) 3581 Diag(DiagOld->getLocation(), 3582 diag::note_attribute_overloadable_prev_overload) 3583 << OldOvl; 3584 3585 if (OldOvl) 3586 New->addAttr(OverloadableAttr::CreateImplicit(Context)); 3587 else 3588 New->dropAttr<OverloadableAttr>(); 3589 } 3590 } 3591 3592 // If a function is first declared with a calling convention, but is later 3593 // declared or defined without one, all following decls assume the calling 3594 // convention of the first. 3595 // 3596 // It's OK if a function is first declared without a calling convention, 3597 // but is later declared or defined with the default calling convention. 3598 // 3599 // To test if either decl has an explicit calling convention, we look for 3600 // AttributedType sugar nodes on the type as written. If they are missing or 3601 // were canonicalized away, we assume the calling convention was implicit. 3602 // 3603 // Note also that we DO NOT return at this point, because we still have 3604 // other tests to run. 3605 QualType OldQType = Context.getCanonicalType(Old->getType()); 3606 QualType NewQType = Context.getCanonicalType(New->getType()); 3607 const FunctionType *OldType = cast<FunctionType>(OldQType); 3608 const FunctionType *NewType = cast<FunctionType>(NewQType); 3609 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 3610 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 3611 bool RequiresAdjustment = false; 3612 3613 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 3614 FunctionDecl *First = Old->getFirstDecl(); 3615 const FunctionType *FT = 3616 First->getType().getCanonicalType()->castAs<FunctionType>(); 3617 FunctionType::ExtInfo FI = FT->getExtInfo(); 3618 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 3619 if (!NewCCExplicit) { 3620 // Inherit the CC from the previous declaration if it was specified 3621 // there but not here. 3622 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3623 RequiresAdjustment = true; 3624 } else if (Old->getBuiltinID()) { 3625 // Builtin attribute isn't propagated to the new one yet at this point, 3626 // so we check if the old one is a builtin. 3627 3628 // Calling Conventions on a Builtin aren't really useful and setting a 3629 // default calling convention and cdecl'ing some builtin redeclarations is 3630 // common, so warn and ignore the calling convention on the redeclaration. 3631 Diag(New->getLocation(), diag::warn_cconv_unsupported) 3632 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3633 << (int)CallingConventionIgnoredReason::BuiltinFunction; 3634 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3635 RequiresAdjustment = true; 3636 } else { 3637 // Calling conventions aren't compatible, so complain. 3638 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 3639 Diag(New->getLocation(), diag::err_cconv_change) 3640 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3641 << !FirstCCExplicit 3642 << (!FirstCCExplicit ? "" : 3643 FunctionType::getNameForCallConv(FI.getCC())); 3644 3645 // Put the note on the first decl, since it is the one that matters. 3646 Diag(First->getLocation(), diag::note_previous_declaration); 3647 return true; 3648 } 3649 } 3650 3651 // FIXME: diagnose the other way around? 3652 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 3653 NewTypeInfo = NewTypeInfo.withNoReturn(true); 3654 RequiresAdjustment = true; 3655 } 3656 3657 // Merge regparm attribute. 3658 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 3659 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 3660 if (NewTypeInfo.getHasRegParm()) { 3661 Diag(New->getLocation(), diag::err_regparm_mismatch) 3662 << NewType->getRegParmType() 3663 << OldType->getRegParmType(); 3664 Diag(OldLocation, diag::note_previous_declaration); 3665 return true; 3666 } 3667 3668 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 3669 RequiresAdjustment = true; 3670 } 3671 3672 // Merge ns_returns_retained attribute. 3673 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 3674 if (NewTypeInfo.getProducesResult()) { 3675 Diag(New->getLocation(), diag::err_function_attribute_mismatch) 3676 << "'ns_returns_retained'"; 3677 Diag(OldLocation, diag::note_previous_declaration); 3678 return true; 3679 } 3680 3681 NewTypeInfo = NewTypeInfo.withProducesResult(true); 3682 RequiresAdjustment = true; 3683 } 3684 3685 if (OldTypeInfo.getNoCallerSavedRegs() != 3686 NewTypeInfo.getNoCallerSavedRegs()) { 3687 if (NewTypeInfo.getNoCallerSavedRegs()) { 3688 AnyX86NoCallerSavedRegistersAttr *Attr = 3689 New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); 3690 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; 3691 Diag(OldLocation, diag::note_previous_declaration); 3692 return true; 3693 } 3694 3695 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); 3696 RequiresAdjustment = true; 3697 } 3698 3699 if (RequiresAdjustment) { 3700 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 3701 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 3702 New->setType(QualType(AdjustedType, 0)); 3703 NewQType = Context.getCanonicalType(New->getType()); 3704 } 3705 3706 // If this redeclaration makes the function inline, we may need to add it to 3707 // UndefinedButUsed. 3708 if (!Old->isInlined() && New->isInlined() && 3709 !New->hasAttr<GNUInlineAttr>() && 3710 !getLangOpts().GNUInline && 3711 Old->isUsed(false) && 3712 !Old->isDefined() && !New->isThisDeclarationADefinition()) 3713 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3714 SourceLocation())); 3715 3716 // If this redeclaration makes it newly gnu_inline, we don't want to warn 3717 // about it. 3718 if (New->hasAttr<GNUInlineAttr>() && 3719 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 3720 UndefinedButUsed.erase(Old->getCanonicalDecl()); 3721 } 3722 3723 // If pass_object_size params don't match up perfectly, this isn't a valid 3724 // redeclaration. 3725 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 3726 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 3727 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 3728 << New->getDeclName(); 3729 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3730 return true; 3731 } 3732 3733 if (getLangOpts().CPlusPlus) { 3734 // C++1z [over.load]p2 3735 // Certain function declarations cannot be overloaded: 3736 // -- Function declarations that differ only in the return type, 3737 // the exception specification, or both cannot be overloaded. 3738 3739 // Check the exception specifications match. This may recompute the type of 3740 // both Old and New if it resolved exception specifications, so grab the 3741 // types again after this. Because this updates the type, we do this before 3742 // any of the other checks below, which may update the "de facto" NewQType 3743 // but do not necessarily update the type of New. 3744 if (CheckEquivalentExceptionSpec(Old, New)) 3745 return true; 3746 OldQType = Context.getCanonicalType(Old->getType()); 3747 NewQType = Context.getCanonicalType(New->getType()); 3748 3749 // Go back to the type source info to compare the declared return types, 3750 // per C++1y [dcl.type.auto]p13: 3751 // Redeclarations or specializations of a function or function template 3752 // with a declared return type that uses a placeholder type shall also 3753 // use that placeholder, not a deduced type. 3754 QualType OldDeclaredReturnType = Old->getDeclaredReturnType(); 3755 QualType NewDeclaredReturnType = New->getDeclaredReturnType(); 3756 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 3757 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType, 3758 OldDeclaredReturnType)) { 3759 QualType ResQT; 3760 if (NewDeclaredReturnType->isObjCObjectPointerType() && 3761 OldDeclaredReturnType->isObjCObjectPointerType()) 3762 // FIXME: This does the wrong thing for a deduced return type. 3763 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 3764 if (ResQT.isNull()) { 3765 if (New->isCXXClassMember() && New->isOutOfLine()) 3766 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 3767 << New << New->getReturnTypeSourceRange(); 3768 else 3769 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 3770 << New->getReturnTypeSourceRange(); 3771 Diag(OldLocation, PrevDiag) << Old << Old->getType() 3772 << Old->getReturnTypeSourceRange(); 3773 return true; 3774 } 3775 else 3776 NewQType = ResQT; 3777 } 3778 3779 QualType OldReturnType = OldType->getReturnType(); 3780 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 3781 if (OldReturnType != NewReturnType) { 3782 // If this function has a deduced return type and has already been 3783 // defined, copy the deduced value from the old declaration. 3784 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 3785 if (OldAT && OldAT->isDeduced()) { 3786 QualType DT = OldAT->getDeducedType(); 3787 if (DT.isNull()) { 3788 New->setType(SubstAutoTypeDependent(New->getType())); 3789 NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType)); 3790 } else { 3791 New->setType(SubstAutoType(New->getType(), DT)); 3792 NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT)); 3793 } 3794 } 3795 } 3796 3797 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 3798 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 3799 if (OldMethod && NewMethod) { 3800 // Preserve triviality. 3801 NewMethod->setTrivial(OldMethod->isTrivial()); 3802 3803 // MSVC allows explicit template specialization at class scope: 3804 // 2 CXXMethodDecls referring to the same function will be injected. 3805 // We don't want a redeclaration error. 3806 bool IsClassScopeExplicitSpecialization = 3807 OldMethod->isFunctionTemplateSpecialization() && 3808 NewMethod->isFunctionTemplateSpecialization(); 3809 bool isFriend = NewMethod->getFriendObjectKind(); 3810 3811 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 3812 !IsClassScopeExplicitSpecialization) { 3813 // -- Member function declarations with the same name and the 3814 // same parameter types cannot be overloaded if any of them 3815 // is a static member function declaration. 3816 if (OldMethod->isStatic() != NewMethod->isStatic()) { 3817 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 3818 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3819 return true; 3820 } 3821 3822 // C++ [class.mem]p1: 3823 // [...] A member shall not be declared twice in the 3824 // member-specification, except that a nested class or member 3825 // class template can be declared and then later defined. 3826 if (!inTemplateInstantiation()) { 3827 unsigned NewDiag; 3828 if (isa<CXXConstructorDecl>(OldMethod)) 3829 NewDiag = diag::err_constructor_redeclared; 3830 else if (isa<CXXDestructorDecl>(NewMethod)) 3831 NewDiag = diag::err_destructor_redeclared; 3832 else if (isa<CXXConversionDecl>(NewMethod)) 3833 NewDiag = diag::err_conv_function_redeclared; 3834 else 3835 NewDiag = diag::err_member_redeclared; 3836 3837 Diag(New->getLocation(), NewDiag); 3838 } else { 3839 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 3840 << New << New->getType(); 3841 } 3842 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3843 return true; 3844 3845 // Complain if this is an explicit declaration of a special 3846 // member that was initially declared implicitly. 3847 // 3848 // As an exception, it's okay to befriend such methods in order 3849 // to permit the implicit constructor/destructor/operator calls. 3850 } else if (OldMethod->isImplicit()) { 3851 if (isFriend) { 3852 NewMethod->setImplicit(); 3853 } else { 3854 Diag(NewMethod->getLocation(), 3855 diag::err_definition_of_implicitly_declared_member) 3856 << New << getSpecialMember(OldMethod); 3857 return true; 3858 } 3859 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 3860 Diag(NewMethod->getLocation(), 3861 diag::err_definition_of_explicitly_defaulted_member) 3862 << getSpecialMember(OldMethod); 3863 return true; 3864 } 3865 } 3866 3867 // C++11 [dcl.attr.noreturn]p1: 3868 // The first declaration of a function shall specify the noreturn 3869 // attribute if any declaration of that function specifies the noreturn 3870 // attribute. 3871 if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>()) 3872 if (!Old->hasAttr<CXX11NoReturnAttr>()) { 3873 Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl) 3874 << NRA; 3875 Diag(Old->getLocation(), diag::note_previous_declaration); 3876 } 3877 3878 // C++11 [dcl.attr.depend]p2: 3879 // The first declaration of a function shall specify the 3880 // carries_dependency attribute for its declarator-id if any declaration 3881 // of the function specifies the carries_dependency attribute. 3882 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 3883 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 3884 Diag(CDA->getLocation(), 3885 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 3886 Diag(Old->getFirstDecl()->getLocation(), 3887 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 3888 } 3889 3890 // (C++98 8.3.5p3): 3891 // All declarations for a function shall agree exactly in both the 3892 // return type and the parameter-type-list. 3893 // We also want to respect all the extended bits except noreturn. 3894 3895 // noreturn should now match unless the old type info didn't have it. 3896 QualType OldQTypeForComparison = OldQType; 3897 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3898 auto *OldType = OldQType->castAs<FunctionProtoType>(); 3899 const FunctionType *OldTypeForComparison 3900 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3901 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3902 assert(OldQTypeForComparison.isCanonical()); 3903 } 3904 3905 if (haveIncompatibleLanguageLinkages(Old, New)) { 3906 // As a special case, retain the language linkage from previous 3907 // declarations of a friend function as an extension. 3908 // 3909 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3910 // and is useful because there's otherwise no way to specify language 3911 // linkage within class scope. 3912 // 3913 // Check cautiously as the friend object kind isn't yet complete. 3914 if (New->getFriendObjectKind() != Decl::FOK_None) { 3915 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3916 Diag(OldLocation, PrevDiag); 3917 } else { 3918 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3919 Diag(OldLocation, PrevDiag); 3920 return true; 3921 } 3922 } 3923 3924 // If the function types are compatible, merge the declarations. Ignore the 3925 // exception specifier because it was already checked above in 3926 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics 3927 // about incompatible types under -fms-compatibility. 3928 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison, 3929 NewQType)) 3930 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3931 3932 // If the types are imprecise (due to dependent constructs in friends or 3933 // local extern declarations), it's OK if they differ. We'll check again 3934 // during instantiation. 3935 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType)) 3936 return false; 3937 3938 // Fall through for conflicting redeclarations and redefinitions. 3939 } 3940 3941 // C: Function types need to be compatible, not identical. This handles 3942 // duplicate function decls like "void f(int); void f(enum X);" properly. 3943 if (!getLangOpts().CPlusPlus) { 3944 // C99 6.7.5.3p15: ...If one type has a parameter type list and the other 3945 // type is specified by a function definition that contains a (possibly 3946 // empty) identifier list, both shall agree in the number of parameters 3947 // and the type of each parameter shall be compatible with the type that 3948 // results from the application of default argument promotions to the 3949 // type of the corresponding identifier. ... 3950 // This cannot be handled by ASTContext::typesAreCompatible() because that 3951 // doesn't know whether the function type is for a definition or not when 3952 // eventually calling ASTContext::mergeFunctionTypes(). The only situation 3953 // we need to cover here is that the number of arguments agree as the 3954 // default argument promotion rules were already checked by 3955 // ASTContext::typesAreCompatible(). 3956 if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn && 3957 Old->getNumParams() != New->getNumParams()) { 3958 if (Old->hasInheritedPrototype()) 3959 Old = Old->getCanonicalDecl(); 3960 Diag(New->getLocation(), diag::err_conflicting_types) << New; 3961 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 3962 return true; 3963 } 3964 3965 // If we are merging two functions where only one of them has a prototype, 3966 // we may have enough information to decide to issue a diagnostic that the 3967 // function without a protoype will change behavior in C2x. This handles 3968 // cases like: 3969 // void i(); void i(int j); 3970 // void i(int j); void i(); 3971 // void i(); void i(int j) {} 3972 // See ActOnFinishFunctionBody() for other cases of the behavior change 3973 // diagnostic. See GetFullTypeForDeclarator() for handling of a function 3974 // type without a prototype. 3975 if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() && 3976 !New->isImplicit() && !Old->isImplicit()) { 3977 const FunctionDecl *WithProto, *WithoutProto; 3978 if (New->hasWrittenPrototype()) { 3979 WithProto = New; 3980 WithoutProto = Old; 3981 } else { 3982 WithProto = Old; 3983 WithoutProto = New; 3984 } 3985 3986 if (WithProto->getNumParams() != 0) { 3987 if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) { 3988 // The one without the prototype will be changing behavior in C2x, so 3989 // warn about that one so long as it's a user-visible declaration. 3990 bool IsWithoutProtoADef = false, IsWithProtoADef = false; 3991 if (WithoutProto == New) 3992 IsWithoutProtoADef = NewDeclIsDefn; 3993 else 3994 IsWithProtoADef = NewDeclIsDefn; 3995 Diag(WithoutProto->getLocation(), 3996 diag::warn_non_prototype_changes_behavior) 3997 << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1) 3998 << (WithoutProto == Old) << IsWithProtoADef; 3999 4000 // The reason the one without the prototype will be changing behavior 4001 // is because of the one with the prototype, so note that so long as 4002 // it's a user-visible declaration. There is one exception to this: 4003 // when the new declaration is a definition without a prototype, the 4004 // old declaration with a prototype is not the cause of the issue, 4005 // and that does not need to be noted because the one with a 4006 // prototype will not change behavior in C2x. 4007 if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() && 4008 !IsWithoutProtoADef) 4009 Diag(WithProto->getLocation(), diag::note_conflicting_prototype); 4010 } 4011 } 4012 } 4013 4014 if (Context.typesAreCompatible(OldQType, NewQType)) { 4015 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 4016 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 4017 const FunctionProtoType *OldProto = nullptr; 4018 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 4019 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 4020 // The old declaration provided a function prototype, but the 4021 // new declaration does not. Merge in the prototype. 4022 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 4023 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 4024 NewQType = 4025 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 4026 OldProto->getExtProtoInfo()); 4027 New->setType(NewQType); 4028 New->setHasInheritedPrototype(); 4029 4030 // Synthesize parameters with the same types. 4031 SmallVector<ParmVarDecl *, 16> Params; 4032 for (const auto &ParamType : OldProto->param_types()) { 4033 ParmVarDecl *Param = ParmVarDecl::Create( 4034 Context, New, SourceLocation(), SourceLocation(), nullptr, 4035 ParamType, /*TInfo=*/nullptr, SC_None, nullptr); 4036 Param->setScopeInfo(0, Params.size()); 4037 Param->setImplicit(); 4038 Params.push_back(Param); 4039 } 4040 4041 New->setParams(Params); 4042 } 4043 4044 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 4045 } 4046 } 4047 4048 // Check if the function types are compatible when pointer size address 4049 // spaces are ignored. 4050 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType)) 4051 return false; 4052 4053 // GNU C permits a K&R definition to follow a prototype declaration 4054 // if the declared types of the parameters in the K&R definition 4055 // match the types in the prototype declaration, even when the 4056 // promoted types of the parameters from the K&R definition differ 4057 // from the types in the prototype. GCC then keeps the types from 4058 // the prototype. 4059 // 4060 // If a variadic prototype is followed by a non-variadic K&R definition, 4061 // the K&R definition becomes variadic. This is sort of an edge case, but 4062 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 4063 // C99 6.9.1p8. 4064 if (!getLangOpts().CPlusPlus && 4065 Old->hasPrototype() && !New->hasPrototype() && 4066 New->getType()->getAs<FunctionProtoType>() && 4067 Old->getNumParams() == New->getNumParams()) { 4068 SmallVector<QualType, 16> ArgTypes; 4069 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 4070 const FunctionProtoType *OldProto 4071 = Old->getType()->getAs<FunctionProtoType>(); 4072 const FunctionProtoType *NewProto 4073 = New->getType()->getAs<FunctionProtoType>(); 4074 4075 // Determine whether this is the GNU C extension. 4076 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 4077 NewProto->getReturnType()); 4078 bool LooseCompatible = !MergedReturn.isNull(); 4079 for (unsigned Idx = 0, End = Old->getNumParams(); 4080 LooseCompatible && Idx != End; ++Idx) { 4081 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 4082 ParmVarDecl *NewParm = New->getParamDecl(Idx); 4083 if (Context.typesAreCompatible(OldParm->getType(), 4084 NewProto->getParamType(Idx))) { 4085 ArgTypes.push_back(NewParm->getType()); 4086 } else if (Context.typesAreCompatible(OldParm->getType(), 4087 NewParm->getType(), 4088 /*CompareUnqualified=*/true)) { 4089 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 4090 NewProto->getParamType(Idx) }; 4091 Warnings.push_back(Warn); 4092 ArgTypes.push_back(NewParm->getType()); 4093 } else 4094 LooseCompatible = false; 4095 } 4096 4097 if (LooseCompatible) { 4098 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 4099 Diag(Warnings[Warn].NewParm->getLocation(), 4100 diag::ext_param_promoted_not_compatible_with_prototype) 4101 << Warnings[Warn].PromotedType 4102 << Warnings[Warn].OldParm->getType(); 4103 if (Warnings[Warn].OldParm->getLocation().isValid()) 4104 Diag(Warnings[Warn].OldParm->getLocation(), 4105 diag::note_previous_declaration); 4106 } 4107 4108 if (MergeTypeWithOld) 4109 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 4110 OldProto->getExtProtoInfo())); 4111 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 4112 } 4113 4114 // Fall through to diagnose conflicting types. 4115 } 4116 4117 // A function that has already been declared has been redeclared or 4118 // defined with a different type; show an appropriate diagnostic. 4119 4120 // If the previous declaration was an implicitly-generated builtin 4121 // declaration, then at the very least we should use a specialized note. 4122 unsigned BuiltinID; 4123 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 4124 // If it's actually a library-defined builtin function like 'malloc' 4125 // or 'printf', just warn about the incompatible redeclaration. 4126 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 4127 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 4128 Diag(OldLocation, diag::note_previous_builtin_declaration) 4129 << Old << Old->getType(); 4130 return false; 4131 } 4132 4133 PrevDiag = diag::note_previous_builtin_declaration; 4134 } 4135 4136 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 4137 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 4138 return true; 4139 } 4140 4141 /// Completes the merge of two function declarations that are 4142 /// known to be compatible. 4143 /// 4144 /// This routine handles the merging of attributes and other 4145 /// properties of function declarations from the old declaration to 4146 /// the new declaration, once we know that New is in fact a 4147 /// redeclaration of Old. 4148 /// 4149 /// \returns false 4150 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 4151 Scope *S, bool MergeTypeWithOld) { 4152 // Merge the attributes 4153 mergeDeclAttributes(New, Old); 4154 4155 // Merge "pure" flag. 4156 if (Old->isPure()) 4157 New->setPure(); 4158 4159 // Merge "used" flag. 4160 if (Old->getMostRecentDecl()->isUsed(false)) 4161 New->setIsUsed(); 4162 4163 // Merge attributes from the parameters. These can mismatch with K&R 4164 // declarations. 4165 if (New->getNumParams() == Old->getNumParams()) 4166 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 4167 ParmVarDecl *NewParam = New->getParamDecl(i); 4168 ParmVarDecl *OldParam = Old->getParamDecl(i); 4169 mergeParamDeclAttributes(NewParam, OldParam, *this); 4170 mergeParamDeclTypes(NewParam, OldParam, *this); 4171 } 4172 4173 if (getLangOpts().CPlusPlus) 4174 return MergeCXXFunctionDecl(New, Old, S); 4175 4176 // Merge the function types so the we get the composite types for the return 4177 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 4178 // was visible. 4179 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 4180 if (!Merged.isNull() && MergeTypeWithOld) 4181 New->setType(Merged); 4182 4183 return false; 4184 } 4185 4186 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 4187 ObjCMethodDecl *oldMethod) { 4188 // Merge the attributes, including deprecated/unavailable 4189 AvailabilityMergeKind MergeKind = 4190 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 4191 ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation 4192 : AMK_ProtocolImplementation) 4193 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 4194 : AMK_Override; 4195 4196 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 4197 4198 // Merge attributes from the parameters. 4199 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 4200 oe = oldMethod->param_end(); 4201 for (ObjCMethodDecl::param_iterator 4202 ni = newMethod->param_begin(), ne = newMethod->param_end(); 4203 ni != ne && oi != oe; ++ni, ++oi) 4204 mergeParamDeclAttributes(*ni, *oi, *this); 4205 4206 CheckObjCMethodOverride(newMethod, oldMethod); 4207 } 4208 4209 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 4210 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 4211 4212 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 4213 ? diag::err_redefinition_different_type 4214 : diag::err_redeclaration_different_type) 4215 << New->getDeclName() << New->getType() << Old->getType(); 4216 4217 diag::kind PrevDiag; 4218 SourceLocation OldLocation; 4219 std::tie(PrevDiag, OldLocation) 4220 = getNoteDiagForInvalidRedeclaration(Old, New); 4221 S.Diag(OldLocation, PrevDiag); 4222 New->setInvalidDecl(); 4223 } 4224 4225 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 4226 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 4227 /// emitting diagnostics as appropriate. 4228 /// 4229 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 4230 /// to here in AddInitializerToDecl. We can't check them before the initializer 4231 /// is attached. 4232 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 4233 bool MergeTypeWithOld) { 4234 if (New->isInvalidDecl() || Old->isInvalidDecl()) 4235 return; 4236 4237 QualType MergedT; 4238 if (getLangOpts().CPlusPlus) { 4239 if (New->getType()->isUndeducedType()) { 4240 // We don't know what the new type is until the initializer is attached. 4241 return; 4242 } else if (Context.hasSameType(New->getType(), Old->getType())) { 4243 // These could still be something that needs exception specs checked. 4244 return MergeVarDeclExceptionSpecs(New, Old); 4245 } 4246 // C++ [basic.link]p10: 4247 // [...] the types specified by all declarations referring to a given 4248 // object or function shall be identical, except that declarations for an 4249 // array object can specify array types that differ by the presence or 4250 // absence of a major array bound (8.3.4). 4251 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 4252 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 4253 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 4254 4255 // We are merging a variable declaration New into Old. If it has an array 4256 // bound, and that bound differs from Old's bound, we should diagnose the 4257 // mismatch. 4258 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 4259 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 4260 PrevVD = PrevVD->getPreviousDecl()) { 4261 QualType PrevVDTy = PrevVD->getType(); 4262 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 4263 continue; 4264 4265 if (!Context.hasSameType(New->getType(), PrevVDTy)) 4266 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 4267 } 4268 } 4269 4270 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 4271 if (Context.hasSameType(OldArray->getElementType(), 4272 NewArray->getElementType())) 4273 MergedT = New->getType(); 4274 } 4275 // FIXME: Check visibility. New is hidden but has a complete type. If New 4276 // has no array bound, it should not inherit one from Old, if Old is not 4277 // visible. 4278 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 4279 if (Context.hasSameType(OldArray->getElementType(), 4280 NewArray->getElementType())) 4281 MergedT = Old->getType(); 4282 } 4283 } 4284 else if (New->getType()->isObjCObjectPointerType() && 4285 Old->getType()->isObjCObjectPointerType()) { 4286 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 4287 Old->getType()); 4288 } 4289 } else { 4290 // C 6.2.7p2: 4291 // All declarations that refer to the same object or function shall have 4292 // compatible type. 4293 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 4294 } 4295 if (MergedT.isNull()) { 4296 // It's OK if we couldn't merge types if either type is dependent, for a 4297 // block-scope variable. In other cases (static data members of class 4298 // templates, variable templates, ...), we require the types to be 4299 // equivalent. 4300 // FIXME: The C++ standard doesn't say anything about this. 4301 if ((New->getType()->isDependentType() || 4302 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 4303 // If the old type was dependent, we can't merge with it, so the new type 4304 // becomes dependent for now. We'll reproduce the original type when we 4305 // instantiate the TypeSourceInfo for the variable. 4306 if (!New->getType()->isDependentType() && MergeTypeWithOld) 4307 New->setType(Context.DependentTy); 4308 return; 4309 } 4310 return diagnoseVarDeclTypeMismatch(*this, New, Old); 4311 } 4312 4313 // Don't actually update the type on the new declaration if the old 4314 // declaration was an extern declaration in a different scope. 4315 if (MergeTypeWithOld) 4316 New->setType(MergedT); 4317 } 4318 4319 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 4320 LookupResult &Previous) { 4321 // C11 6.2.7p4: 4322 // For an identifier with internal or external linkage declared 4323 // in a scope in which a prior declaration of that identifier is 4324 // visible, if the prior declaration specifies internal or 4325 // external linkage, the type of the identifier at the later 4326 // declaration becomes the composite type. 4327 // 4328 // If the variable isn't visible, we do not merge with its type. 4329 if (Previous.isShadowed()) 4330 return false; 4331 4332 if (S.getLangOpts().CPlusPlus) { 4333 // C++11 [dcl.array]p3: 4334 // If there is a preceding declaration of the entity in the same 4335 // scope in which the bound was specified, an omitted array bound 4336 // is taken to be the same as in that earlier declaration. 4337 return NewVD->isPreviousDeclInSameBlockScope() || 4338 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 4339 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 4340 } else { 4341 // If the old declaration was function-local, don't merge with its 4342 // type unless we're in the same function. 4343 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 4344 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 4345 } 4346 } 4347 4348 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 4349 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 4350 /// situation, merging decls or emitting diagnostics as appropriate. 4351 /// 4352 /// Tentative definition rules (C99 6.9.2p2) are checked by 4353 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 4354 /// definitions here, since the initializer hasn't been attached. 4355 /// 4356 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 4357 // If the new decl is already invalid, don't do any other checking. 4358 if (New->isInvalidDecl()) 4359 return; 4360 4361 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 4362 return; 4363 4364 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 4365 4366 // Verify the old decl was also a variable or variable template. 4367 VarDecl *Old = nullptr; 4368 VarTemplateDecl *OldTemplate = nullptr; 4369 if (Previous.isSingleResult()) { 4370 if (NewTemplate) { 4371 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 4372 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 4373 4374 if (auto *Shadow = 4375 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4376 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 4377 return New->setInvalidDecl(); 4378 } else { 4379 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 4380 4381 if (auto *Shadow = 4382 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4383 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 4384 return New->setInvalidDecl(); 4385 } 4386 } 4387 if (!Old) { 4388 Diag(New->getLocation(), diag::err_redefinition_different_kind) 4389 << New->getDeclName(); 4390 notePreviousDefinition(Previous.getRepresentativeDecl(), 4391 New->getLocation()); 4392 return New->setInvalidDecl(); 4393 } 4394 4395 // If the old declaration was found in an inline namespace and the new 4396 // declaration was qualified, update the DeclContext to match. 4397 adjustDeclContextForDeclaratorDecl(New, Old); 4398 4399 // Ensure the template parameters are compatible. 4400 if (NewTemplate && 4401 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 4402 OldTemplate->getTemplateParameters(), 4403 /*Complain=*/true, TPL_TemplateMatch)) 4404 return New->setInvalidDecl(); 4405 4406 // C++ [class.mem]p1: 4407 // A member shall not be declared twice in the member-specification [...] 4408 // 4409 // Here, we need only consider static data members. 4410 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 4411 Diag(New->getLocation(), diag::err_duplicate_member) 4412 << New->getIdentifier(); 4413 Diag(Old->getLocation(), diag::note_previous_declaration); 4414 New->setInvalidDecl(); 4415 } 4416 4417 mergeDeclAttributes(New, Old); 4418 // Warn if an already-declared variable is made a weak_import in a subsequent 4419 // declaration 4420 if (New->hasAttr<WeakImportAttr>() && 4421 Old->getStorageClass() == SC_None && 4422 !Old->hasAttr<WeakImportAttr>()) { 4423 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 4424 Diag(Old->getLocation(), diag::note_previous_declaration); 4425 // Remove weak_import attribute on new declaration. 4426 New->dropAttr<WeakImportAttr>(); 4427 } 4428 4429 if (const auto *ILA = New->getAttr<InternalLinkageAttr>()) 4430 if (!Old->hasAttr<InternalLinkageAttr>()) { 4431 Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl) 4432 << ILA; 4433 Diag(Old->getLocation(), diag::note_previous_declaration); 4434 New->dropAttr<InternalLinkageAttr>(); 4435 } 4436 4437 // Merge the types. 4438 VarDecl *MostRecent = Old->getMostRecentDecl(); 4439 if (MostRecent != Old) { 4440 MergeVarDeclTypes(New, MostRecent, 4441 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 4442 if (New->isInvalidDecl()) 4443 return; 4444 } 4445 4446 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 4447 if (New->isInvalidDecl()) 4448 return; 4449 4450 diag::kind PrevDiag; 4451 SourceLocation OldLocation; 4452 std::tie(PrevDiag, OldLocation) = 4453 getNoteDiagForInvalidRedeclaration(Old, New); 4454 4455 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 4456 if (New->getStorageClass() == SC_Static && 4457 !New->isStaticDataMember() && 4458 Old->hasExternalFormalLinkage()) { 4459 if (getLangOpts().MicrosoftExt) { 4460 Diag(New->getLocation(), diag::ext_static_non_static) 4461 << New->getDeclName(); 4462 Diag(OldLocation, PrevDiag); 4463 } else { 4464 Diag(New->getLocation(), diag::err_static_non_static) 4465 << New->getDeclName(); 4466 Diag(OldLocation, PrevDiag); 4467 return New->setInvalidDecl(); 4468 } 4469 } 4470 // C99 6.2.2p4: 4471 // For an identifier declared with the storage-class specifier 4472 // extern in a scope in which a prior declaration of that 4473 // identifier is visible,23) if the prior declaration specifies 4474 // internal or external linkage, the linkage of the identifier at 4475 // the later declaration is the same as the linkage specified at 4476 // the prior declaration. If no prior declaration is visible, or 4477 // if the prior declaration specifies no linkage, then the 4478 // identifier has external linkage. 4479 if (New->hasExternalStorage() && Old->hasLinkage()) 4480 /* Okay */; 4481 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 4482 !New->isStaticDataMember() && 4483 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 4484 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 4485 Diag(OldLocation, PrevDiag); 4486 return New->setInvalidDecl(); 4487 } 4488 4489 // Check if extern is followed by non-extern and vice-versa. 4490 if (New->hasExternalStorage() && 4491 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 4492 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 4493 Diag(OldLocation, PrevDiag); 4494 return New->setInvalidDecl(); 4495 } 4496 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 4497 !New->hasExternalStorage()) { 4498 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 4499 Diag(OldLocation, PrevDiag); 4500 return New->setInvalidDecl(); 4501 } 4502 4503 if (CheckRedeclarationInModule(New, Old)) 4504 return; 4505 4506 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 4507 4508 // FIXME: The test for external storage here seems wrong? We still 4509 // need to check for mismatches. 4510 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 4511 // Don't complain about out-of-line definitions of static members. 4512 !(Old->getLexicalDeclContext()->isRecord() && 4513 !New->getLexicalDeclContext()->isRecord())) { 4514 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 4515 Diag(OldLocation, PrevDiag); 4516 return New->setInvalidDecl(); 4517 } 4518 4519 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 4520 if (VarDecl *Def = Old->getDefinition()) { 4521 // C++1z [dcl.fcn.spec]p4: 4522 // If the definition of a variable appears in a translation unit before 4523 // its first declaration as inline, the program is ill-formed. 4524 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 4525 Diag(Def->getLocation(), diag::note_previous_definition); 4526 } 4527 } 4528 4529 // If this redeclaration makes the variable inline, we may need to add it to 4530 // UndefinedButUsed. 4531 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 4532 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 4533 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 4534 SourceLocation())); 4535 4536 if (New->getTLSKind() != Old->getTLSKind()) { 4537 if (!Old->getTLSKind()) { 4538 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 4539 Diag(OldLocation, PrevDiag); 4540 } else if (!New->getTLSKind()) { 4541 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 4542 Diag(OldLocation, PrevDiag); 4543 } else { 4544 // Do not allow redeclaration to change the variable between requiring 4545 // static and dynamic initialization. 4546 // FIXME: GCC allows this, but uses the TLS keyword on the first 4547 // declaration to determine the kind. Do we need to be compatible here? 4548 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 4549 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 4550 Diag(OldLocation, PrevDiag); 4551 } 4552 } 4553 4554 // C++ doesn't have tentative definitions, so go right ahead and check here. 4555 if (getLangOpts().CPlusPlus) { 4556 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 4557 Old->getCanonicalDecl()->isConstexpr()) { 4558 // This definition won't be a definition any more once it's been merged. 4559 Diag(New->getLocation(), 4560 diag::warn_deprecated_redundant_constexpr_static_def); 4561 } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) { 4562 VarDecl *Def = Old->getDefinition(); 4563 if (Def && checkVarDeclRedefinition(Def, New)) 4564 return; 4565 } 4566 } 4567 4568 if (haveIncompatibleLanguageLinkages(Old, New)) { 4569 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 4570 Diag(OldLocation, PrevDiag); 4571 New->setInvalidDecl(); 4572 return; 4573 } 4574 4575 // Merge "used" flag. 4576 if (Old->getMostRecentDecl()->isUsed(false)) 4577 New->setIsUsed(); 4578 4579 // Keep a chain of previous declarations. 4580 New->setPreviousDecl(Old); 4581 if (NewTemplate) 4582 NewTemplate->setPreviousDecl(OldTemplate); 4583 4584 // Inherit access appropriately. 4585 New->setAccess(Old->getAccess()); 4586 if (NewTemplate) 4587 NewTemplate->setAccess(New->getAccess()); 4588 4589 if (Old->isInline()) 4590 New->setImplicitlyInline(); 4591 } 4592 4593 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { 4594 SourceManager &SrcMgr = getSourceManager(); 4595 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); 4596 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); 4597 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); 4598 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); 4599 auto &HSI = PP.getHeaderSearchInfo(); 4600 StringRef HdrFilename = 4601 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); 4602 4603 auto noteFromModuleOrInclude = [&](Module *Mod, 4604 SourceLocation IncLoc) -> bool { 4605 // Redefinition errors with modules are common with non modular mapped 4606 // headers, example: a non-modular header H in module A that also gets 4607 // included directly in a TU. Pointing twice to the same header/definition 4608 // is confusing, try to get better diagnostics when modules is on. 4609 if (IncLoc.isValid()) { 4610 if (Mod) { 4611 Diag(IncLoc, diag::note_redefinition_modules_same_file) 4612 << HdrFilename.str() << Mod->getFullModuleName(); 4613 if (!Mod->DefinitionLoc.isInvalid()) 4614 Diag(Mod->DefinitionLoc, diag::note_defined_here) 4615 << Mod->getFullModuleName(); 4616 } else { 4617 Diag(IncLoc, diag::note_redefinition_include_same_file) 4618 << HdrFilename.str(); 4619 } 4620 return true; 4621 } 4622 4623 return false; 4624 }; 4625 4626 // Is it the same file and same offset? Provide more information on why 4627 // this leads to a redefinition error. 4628 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { 4629 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); 4630 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); 4631 bool EmittedDiag = 4632 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); 4633 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); 4634 4635 // If the header has no guards, emit a note suggesting one. 4636 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) 4637 Diag(Old->getLocation(), diag::note_use_ifdef_guards); 4638 4639 if (EmittedDiag) 4640 return; 4641 } 4642 4643 // Redefinition coming from different files or couldn't do better above. 4644 if (Old->getLocation().isValid()) 4645 Diag(Old->getLocation(), diag::note_previous_definition); 4646 } 4647 4648 /// We've just determined that \p Old and \p New both appear to be definitions 4649 /// of the same variable. Either diagnose or fix the problem. 4650 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 4651 if (!hasVisibleDefinition(Old) && 4652 (New->getFormalLinkage() == InternalLinkage || 4653 New->isInline() || 4654 New->getDescribedVarTemplate() || 4655 New->getNumTemplateParameterLists() || 4656 New->getDeclContext()->isDependentContext())) { 4657 // The previous definition is hidden, and multiple definitions are 4658 // permitted (in separate TUs). Demote this to a declaration. 4659 New->demoteThisDefinitionToDeclaration(); 4660 4661 // Make the canonical definition visible. 4662 if (auto *OldTD = Old->getDescribedVarTemplate()) 4663 makeMergedDefinitionVisible(OldTD); 4664 makeMergedDefinitionVisible(Old); 4665 return false; 4666 } else { 4667 Diag(New->getLocation(), diag::err_redefinition) << New; 4668 notePreviousDefinition(Old, New->getLocation()); 4669 New->setInvalidDecl(); 4670 return true; 4671 } 4672 } 4673 4674 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4675 /// no declarator (e.g. "struct foo;") is parsed. 4676 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 4677 DeclSpec &DS, 4678 const ParsedAttributesView &DeclAttrs, 4679 RecordDecl *&AnonRecord) { 4680 return ParsedFreeStandingDeclSpec( 4681 S, AS, DS, DeclAttrs, MultiTemplateParamsArg(), false, AnonRecord); 4682 } 4683 4684 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 4685 // disambiguate entities defined in different scopes. 4686 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 4687 // compatibility. 4688 // We will pick our mangling number depending on which version of MSVC is being 4689 // targeted. 4690 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 4691 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 4692 ? S->getMSCurManglingNumber() 4693 : S->getMSLastManglingNumber(); 4694 } 4695 4696 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 4697 if (!Context.getLangOpts().CPlusPlus) 4698 return; 4699 4700 if (isa<CXXRecordDecl>(Tag->getParent())) { 4701 // If this tag is the direct child of a class, number it if 4702 // it is anonymous. 4703 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 4704 return; 4705 MangleNumberingContext &MCtx = 4706 Context.getManglingNumberContext(Tag->getParent()); 4707 Context.setManglingNumber( 4708 Tag, MCtx.getManglingNumber( 4709 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4710 return; 4711 } 4712 4713 // If this tag isn't a direct child of a class, number it if it is local. 4714 MangleNumberingContext *MCtx; 4715 Decl *ManglingContextDecl; 4716 std::tie(MCtx, ManglingContextDecl) = 4717 getCurrentMangleNumberContext(Tag->getDeclContext()); 4718 if (MCtx) { 4719 Context.setManglingNumber( 4720 Tag, MCtx->getManglingNumber( 4721 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4722 } 4723 } 4724 4725 namespace { 4726 struct NonCLikeKind { 4727 enum { 4728 None, 4729 BaseClass, 4730 DefaultMemberInit, 4731 Lambda, 4732 Friend, 4733 OtherMember, 4734 Invalid, 4735 } Kind = None; 4736 SourceRange Range; 4737 4738 explicit operator bool() { return Kind != None; } 4739 }; 4740 } 4741 4742 /// Determine whether a class is C-like, according to the rules of C++ 4743 /// [dcl.typedef] for anonymous classes with typedef names for linkage. 4744 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) { 4745 if (RD->isInvalidDecl()) 4746 return {NonCLikeKind::Invalid, {}}; 4747 4748 // C++ [dcl.typedef]p9: [P1766R1] 4749 // An unnamed class with a typedef name for linkage purposes shall not 4750 // 4751 // -- have any base classes 4752 if (RD->getNumBases()) 4753 return {NonCLikeKind::BaseClass, 4754 SourceRange(RD->bases_begin()->getBeginLoc(), 4755 RD->bases_end()[-1].getEndLoc())}; 4756 bool Invalid = false; 4757 for (Decl *D : RD->decls()) { 4758 // Don't complain about things we already diagnosed. 4759 if (D->isInvalidDecl()) { 4760 Invalid = true; 4761 continue; 4762 } 4763 4764 // -- have any [...] default member initializers 4765 if (auto *FD = dyn_cast<FieldDecl>(D)) { 4766 if (FD->hasInClassInitializer()) { 4767 auto *Init = FD->getInClassInitializer(); 4768 return {NonCLikeKind::DefaultMemberInit, 4769 Init ? Init->getSourceRange() : D->getSourceRange()}; 4770 } 4771 continue; 4772 } 4773 4774 // FIXME: We don't allow friend declarations. This violates the wording of 4775 // P1766, but not the intent. 4776 if (isa<FriendDecl>(D)) 4777 return {NonCLikeKind::Friend, D->getSourceRange()}; 4778 4779 // -- declare any members other than non-static data members, member 4780 // enumerations, or member classes, 4781 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) || 4782 isa<EnumDecl>(D)) 4783 continue; 4784 auto *MemberRD = dyn_cast<CXXRecordDecl>(D); 4785 if (!MemberRD) { 4786 if (D->isImplicit()) 4787 continue; 4788 return {NonCLikeKind::OtherMember, D->getSourceRange()}; 4789 } 4790 4791 // -- contain a lambda-expression, 4792 if (MemberRD->isLambda()) 4793 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()}; 4794 4795 // and all member classes shall also satisfy these requirements 4796 // (recursively). 4797 if (MemberRD->isThisDeclarationADefinition()) { 4798 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD)) 4799 return Kind; 4800 } 4801 } 4802 4803 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}}; 4804 } 4805 4806 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 4807 TypedefNameDecl *NewTD) { 4808 if (TagFromDeclSpec->isInvalidDecl()) 4809 return; 4810 4811 // Do nothing if the tag already has a name for linkage purposes. 4812 if (TagFromDeclSpec->hasNameForLinkage()) 4813 return; 4814 4815 // A well-formed anonymous tag must always be a TUK_Definition. 4816 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 4817 4818 // The type must match the tag exactly; no qualifiers allowed. 4819 if (!Context.hasSameType(NewTD->getUnderlyingType(), 4820 Context.getTagDeclType(TagFromDeclSpec))) { 4821 if (getLangOpts().CPlusPlus) 4822 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 4823 return; 4824 } 4825 4826 // C++ [dcl.typedef]p9: [P1766R1, applied as DR] 4827 // An unnamed class with a typedef name for linkage purposes shall [be 4828 // C-like]. 4829 // 4830 // FIXME: Also diagnose if we've already computed the linkage. That ideally 4831 // shouldn't happen, but there are constructs that the language rule doesn't 4832 // disallow for which we can't reasonably avoid computing linkage early. 4833 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec); 4834 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD) 4835 : NonCLikeKind(); 4836 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed(); 4837 if (NonCLike || ChangesLinkage) { 4838 if (NonCLike.Kind == NonCLikeKind::Invalid) 4839 return; 4840 4841 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef; 4842 if (ChangesLinkage) { 4843 // If the linkage changes, we can't accept this as an extension. 4844 if (NonCLike.Kind == NonCLikeKind::None) 4845 DiagID = diag::err_typedef_changes_linkage; 4846 else 4847 DiagID = diag::err_non_c_like_anon_struct_in_typedef; 4848 } 4849 4850 SourceLocation FixitLoc = 4851 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart()); 4852 llvm::SmallString<40> TextToInsert; 4853 TextToInsert += ' '; 4854 TextToInsert += NewTD->getIdentifier()->getName(); 4855 4856 Diag(FixitLoc, DiagID) 4857 << isa<TypeAliasDecl>(NewTD) 4858 << FixItHint::CreateInsertion(FixitLoc, TextToInsert); 4859 if (NonCLike.Kind != NonCLikeKind::None) { 4860 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct) 4861 << NonCLike.Kind - 1 << NonCLike.Range; 4862 } 4863 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here) 4864 << NewTD << isa<TypeAliasDecl>(NewTD); 4865 4866 if (ChangesLinkage) 4867 return; 4868 } 4869 4870 // Otherwise, set this as the anon-decl typedef for the tag. 4871 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 4872 } 4873 4874 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 4875 switch (T) { 4876 case DeclSpec::TST_class: 4877 return 0; 4878 case DeclSpec::TST_struct: 4879 return 1; 4880 case DeclSpec::TST_interface: 4881 return 2; 4882 case DeclSpec::TST_union: 4883 return 3; 4884 case DeclSpec::TST_enum: 4885 return 4; 4886 default: 4887 llvm_unreachable("unexpected type specifier"); 4888 } 4889 } 4890 4891 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4892 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 4893 /// parameters to cope with template friend declarations. 4894 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 4895 DeclSpec &DS, 4896 const ParsedAttributesView &DeclAttrs, 4897 MultiTemplateParamsArg TemplateParams, 4898 bool IsExplicitInstantiation, 4899 RecordDecl *&AnonRecord) { 4900 Decl *TagD = nullptr; 4901 TagDecl *Tag = nullptr; 4902 if (DS.getTypeSpecType() == DeclSpec::TST_class || 4903 DS.getTypeSpecType() == DeclSpec::TST_struct || 4904 DS.getTypeSpecType() == DeclSpec::TST_interface || 4905 DS.getTypeSpecType() == DeclSpec::TST_union || 4906 DS.getTypeSpecType() == DeclSpec::TST_enum) { 4907 TagD = DS.getRepAsDecl(); 4908 4909 if (!TagD) // We probably had an error 4910 return nullptr; 4911 4912 // Note that the above type specs guarantee that the 4913 // type rep is a Decl, whereas in many of the others 4914 // it's a Type. 4915 if (isa<TagDecl>(TagD)) 4916 Tag = cast<TagDecl>(TagD); 4917 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 4918 Tag = CTD->getTemplatedDecl(); 4919 } 4920 4921 if (Tag) { 4922 handleTagNumbering(Tag, S); 4923 Tag->setFreeStanding(); 4924 if (Tag->isInvalidDecl()) 4925 return Tag; 4926 } 4927 4928 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 4929 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 4930 // or incomplete types shall not be restrict-qualified." 4931 if (TypeQuals & DeclSpec::TQ_restrict) 4932 Diag(DS.getRestrictSpecLoc(), 4933 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 4934 << DS.getSourceRange(); 4935 } 4936 4937 if (DS.isInlineSpecified()) 4938 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 4939 << getLangOpts().CPlusPlus17; 4940 4941 if (DS.hasConstexprSpecifier()) { 4942 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 4943 // and definitions of functions and variables. 4944 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to 4945 // the declaration of a function or function template 4946 if (Tag) 4947 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 4948 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) 4949 << static_cast<int>(DS.getConstexprSpecifier()); 4950 else 4951 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind) 4952 << static_cast<int>(DS.getConstexprSpecifier()); 4953 // Don't emit warnings after this error. 4954 return TagD; 4955 } 4956 4957 DiagnoseFunctionSpecifiers(DS); 4958 4959 if (DS.isFriendSpecified()) { 4960 // If we're dealing with a decl but not a TagDecl, assume that 4961 // whatever routines created it handled the friendship aspect. 4962 if (TagD && !Tag) 4963 return nullptr; 4964 return ActOnFriendTypeDecl(S, DS, TemplateParams); 4965 } 4966 4967 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 4968 bool IsExplicitSpecialization = 4969 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 4970 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 4971 !IsExplicitInstantiation && !IsExplicitSpecialization && 4972 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 4973 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 4974 // nested-name-specifier unless it is an explicit instantiation 4975 // or an explicit specialization. 4976 // 4977 // FIXME: We allow class template partial specializations here too, per the 4978 // obvious intent of DR1819. 4979 // 4980 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 4981 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 4982 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 4983 return nullptr; 4984 } 4985 4986 // Track whether this decl-specifier declares anything. 4987 bool DeclaresAnything = true; 4988 4989 // Handle anonymous struct definitions. 4990 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 4991 if (!Record->getDeclName() && Record->isCompleteDefinition() && 4992 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 4993 if (getLangOpts().CPlusPlus || 4994 Record->getDeclContext()->isRecord()) { 4995 // If CurContext is a DeclContext that can contain statements, 4996 // RecursiveASTVisitor won't visit the decls that 4997 // BuildAnonymousStructOrUnion() will put into CurContext. 4998 // Also store them here so that they can be part of the 4999 // DeclStmt that gets created in this case. 5000 // FIXME: Also return the IndirectFieldDecls created by 5001 // BuildAnonymousStructOr union, for the same reason? 5002 if (CurContext->isFunctionOrMethod()) 5003 AnonRecord = Record; 5004 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 5005 Context.getPrintingPolicy()); 5006 } 5007 5008 DeclaresAnything = false; 5009 } 5010 } 5011 5012 // C11 6.7.2.1p2: 5013 // A struct-declaration that does not declare an anonymous structure or 5014 // anonymous union shall contain a struct-declarator-list. 5015 // 5016 // This rule also existed in C89 and C99; the grammar for struct-declaration 5017 // did not permit a struct-declaration without a struct-declarator-list. 5018 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 5019 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 5020 // Check for Microsoft C extension: anonymous struct/union member. 5021 // Handle 2 kinds of anonymous struct/union: 5022 // struct STRUCT; 5023 // union UNION; 5024 // and 5025 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 5026 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 5027 if ((Tag && Tag->getDeclName()) || 5028 DS.getTypeSpecType() == DeclSpec::TST_typename) { 5029 RecordDecl *Record = nullptr; 5030 if (Tag) 5031 Record = dyn_cast<RecordDecl>(Tag); 5032 else if (const RecordType *RT = 5033 DS.getRepAsType().get()->getAsStructureType()) 5034 Record = RT->getDecl(); 5035 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 5036 Record = UT->getDecl(); 5037 5038 if (Record && getLangOpts().MicrosoftExt) { 5039 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record) 5040 << Record->isUnion() << DS.getSourceRange(); 5041 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 5042 } 5043 5044 DeclaresAnything = false; 5045 } 5046 } 5047 5048 // Skip all the checks below if we have a type error. 5049 if (DS.getTypeSpecType() == DeclSpec::TST_error || 5050 (TagD && TagD->isInvalidDecl())) 5051 return TagD; 5052 5053 if (getLangOpts().CPlusPlus && 5054 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 5055 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 5056 if (Enum->enumerator_begin() == Enum->enumerator_end() && 5057 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 5058 DeclaresAnything = false; 5059 5060 if (!DS.isMissingDeclaratorOk()) { 5061 // Customize diagnostic for a typedef missing a name. 5062 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 5063 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name) 5064 << DS.getSourceRange(); 5065 else 5066 DeclaresAnything = false; 5067 } 5068 5069 if (DS.isModulePrivateSpecified() && 5070 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 5071 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 5072 << Tag->getTagKind() 5073 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 5074 5075 ActOnDocumentableDecl(TagD); 5076 5077 // C 6.7/2: 5078 // A declaration [...] shall declare at least a declarator [...], a tag, 5079 // or the members of an enumeration. 5080 // C++ [dcl.dcl]p3: 5081 // [If there are no declarators], and except for the declaration of an 5082 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 5083 // names into the program, or shall redeclare a name introduced by a 5084 // previous declaration. 5085 if (!DeclaresAnything) { 5086 // In C, we allow this as a (popular) extension / bug. Don't bother 5087 // producing further diagnostics for redundant qualifiers after this. 5088 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty()) 5089 ? diag::err_no_declarators 5090 : diag::ext_no_declarators) 5091 << DS.getSourceRange(); 5092 return TagD; 5093 } 5094 5095 // C++ [dcl.stc]p1: 5096 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 5097 // init-declarator-list of the declaration shall not be empty. 5098 // C++ [dcl.fct.spec]p1: 5099 // If a cv-qualifier appears in a decl-specifier-seq, the 5100 // init-declarator-list of the declaration shall not be empty. 5101 // 5102 // Spurious qualifiers here appear to be valid in C. 5103 unsigned DiagID = diag::warn_standalone_specifier; 5104 if (getLangOpts().CPlusPlus) 5105 DiagID = diag::ext_standalone_specifier; 5106 5107 // Note that a linkage-specification sets a storage class, but 5108 // 'extern "C" struct foo;' is actually valid and not theoretically 5109 // useless. 5110 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 5111 if (SCS == DeclSpec::SCS_mutable) 5112 // Since mutable is not a viable storage class specifier in C, there is 5113 // no reason to treat it as an extension. Instead, diagnose as an error. 5114 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 5115 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 5116 Diag(DS.getStorageClassSpecLoc(), DiagID) 5117 << DeclSpec::getSpecifierName(SCS); 5118 } 5119 5120 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 5121 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 5122 << DeclSpec::getSpecifierName(TSCS); 5123 if (DS.getTypeQualifiers()) { 5124 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 5125 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 5126 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 5127 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 5128 // Restrict is covered above. 5129 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 5130 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 5131 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 5132 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 5133 } 5134 5135 // Warn about ignored type attributes, for example: 5136 // __attribute__((aligned)) struct A; 5137 // Attributes should be placed after tag to apply to type declaration. 5138 if (!DS.getAttributes().empty() || !DeclAttrs.empty()) { 5139 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 5140 if (TypeSpecType == DeclSpec::TST_class || 5141 TypeSpecType == DeclSpec::TST_struct || 5142 TypeSpecType == DeclSpec::TST_interface || 5143 TypeSpecType == DeclSpec::TST_union || 5144 TypeSpecType == DeclSpec::TST_enum) { 5145 for (const ParsedAttr &AL : DS.getAttributes()) 5146 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored) 5147 << AL << GetDiagnosticTypeSpecifierID(TypeSpecType); 5148 for (const ParsedAttr &AL : DeclAttrs) 5149 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored) 5150 << AL << GetDiagnosticTypeSpecifierID(TypeSpecType); 5151 } 5152 } 5153 5154 return TagD; 5155 } 5156 5157 /// We are trying to inject an anonymous member into the given scope; 5158 /// check if there's an existing declaration that can't be overloaded. 5159 /// 5160 /// \return true if this is a forbidden redeclaration 5161 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 5162 Scope *S, 5163 DeclContext *Owner, 5164 DeclarationName Name, 5165 SourceLocation NameLoc, 5166 bool IsUnion) { 5167 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 5168 Sema::ForVisibleRedeclaration); 5169 if (!SemaRef.LookupName(R, S)) return false; 5170 5171 // Pick a representative declaration. 5172 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 5173 assert(PrevDecl && "Expected a non-null Decl"); 5174 5175 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 5176 return false; 5177 5178 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 5179 << IsUnion << Name; 5180 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 5181 5182 return true; 5183 } 5184 5185 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 5186 /// anonymous struct or union AnonRecord into the owning context Owner 5187 /// and scope S. This routine will be invoked just after we realize 5188 /// that an unnamed union or struct is actually an anonymous union or 5189 /// struct, e.g., 5190 /// 5191 /// @code 5192 /// union { 5193 /// int i; 5194 /// float f; 5195 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 5196 /// // f into the surrounding scope.x 5197 /// @endcode 5198 /// 5199 /// This routine is recursive, injecting the names of nested anonymous 5200 /// structs/unions into the owning context and scope as well. 5201 static bool 5202 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 5203 RecordDecl *AnonRecord, AccessSpecifier AS, 5204 SmallVectorImpl<NamedDecl *> &Chaining) { 5205 bool Invalid = false; 5206 5207 // Look every FieldDecl and IndirectFieldDecl with a name. 5208 for (auto *D : AnonRecord->decls()) { 5209 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 5210 cast<NamedDecl>(D)->getDeclName()) { 5211 ValueDecl *VD = cast<ValueDecl>(D); 5212 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 5213 VD->getLocation(), 5214 AnonRecord->isUnion())) { 5215 // C++ [class.union]p2: 5216 // The names of the members of an anonymous union shall be 5217 // distinct from the names of any other entity in the 5218 // scope in which the anonymous union is declared. 5219 Invalid = true; 5220 } else { 5221 // C++ [class.union]p2: 5222 // For the purpose of name lookup, after the anonymous union 5223 // definition, the members of the anonymous union are 5224 // considered to have been defined in the scope in which the 5225 // anonymous union is declared. 5226 unsigned OldChainingSize = Chaining.size(); 5227 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 5228 Chaining.append(IF->chain_begin(), IF->chain_end()); 5229 else 5230 Chaining.push_back(VD); 5231 5232 assert(Chaining.size() >= 2); 5233 NamedDecl **NamedChain = 5234 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 5235 for (unsigned i = 0; i < Chaining.size(); i++) 5236 NamedChain[i] = Chaining[i]; 5237 5238 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 5239 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 5240 VD->getType(), {NamedChain, Chaining.size()}); 5241 5242 for (const auto *Attr : VD->attrs()) 5243 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 5244 5245 IndirectField->setAccess(AS); 5246 IndirectField->setImplicit(); 5247 SemaRef.PushOnScopeChains(IndirectField, S); 5248 5249 // That includes picking up the appropriate access specifier. 5250 if (AS != AS_none) IndirectField->setAccess(AS); 5251 5252 Chaining.resize(OldChainingSize); 5253 } 5254 } 5255 } 5256 5257 return Invalid; 5258 } 5259 5260 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 5261 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 5262 /// illegal input values are mapped to SC_None. 5263 static StorageClass 5264 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 5265 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 5266 assert(StorageClassSpec != DeclSpec::SCS_typedef && 5267 "Parser allowed 'typedef' as storage class VarDecl."); 5268 switch (StorageClassSpec) { 5269 case DeclSpec::SCS_unspecified: return SC_None; 5270 case DeclSpec::SCS_extern: 5271 if (DS.isExternInLinkageSpec()) 5272 return SC_None; 5273 return SC_Extern; 5274 case DeclSpec::SCS_static: return SC_Static; 5275 case DeclSpec::SCS_auto: return SC_Auto; 5276 case DeclSpec::SCS_register: return SC_Register; 5277 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 5278 // Illegal SCSs map to None: error reporting is up to the caller. 5279 case DeclSpec::SCS_mutable: // Fall through. 5280 case DeclSpec::SCS_typedef: return SC_None; 5281 } 5282 llvm_unreachable("unknown storage class specifier"); 5283 } 5284 5285 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 5286 assert(Record->hasInClassInitializer()); 5287 5288 for (const auto *I : Record->decls()) { 5289 const auto *FD = dyn_cast<FieldDecl>(I); 5290 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 5291 FD = IFD->getAnonField(); 5292 if (FD && FD->hasInClassInitializer()) 5293 return FD->getLocation(); 5294 } 5295 5296 llvm_unreachable("couldn't find in-class initializer"); 5297 } 5298 5299 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 5300 SourceLocation DefaultInitLoc) { 5301 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 5302 return; 5303 5304 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 5305 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 5306 } 5307 5308 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 5309 CXXRecordDecl *AnonUnion) { 5310 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 5311 return; 5312 5313 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 5314 } 5315 5316 /// BuildAnonymousStructOrUnion - Handle the declaration of an 5317 /// anonymous structure or union. Anonymous unions are a C++ feature 5318 /// (C++ [class.union]) and a C11 feature; anonymous structures 5319 /// are a C11 feature and GNU C++ extension. 5320 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 5321 AccessSpecifier AS, 5322 RecordDecl *Record, 5323 const PrintingPolicy &Policy) { 5324 DeclContext *Owner = Record->getDeclContext(); 5325 5326 // Diagnose whether this anonymous struct/union is an extension. 5327 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 5328 Diag(Record->getLocation(), diag::ext_anonymous_union); 5329 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 5330 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 5331 else if (!Record->isUnion() && !getLangOpts().C11) 5332 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 5333 5334 // C and C++ require different kinds of checks for anonymous 5335 // structs/unions. 5336 bool Invalid = false; 5337 if (getLangOpts().CPlusPlus) { 5338 const char *PrevSpec = nullptr; 5339 if (Record->isUnion()) { 5340 // C++ [class.union]p6: 5341 // C++17 [class.union.anon]p2: 5342 // Anonymous unions declared in a named namespace or in the 5343 // global namespace shall be declared static. 5344 unsigned DiagID; 5345 DeclContext *OwnerScope = Owner->getRedeclContext(); 5346 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 5347 (OwnerScope->isTranslationUnit() || 5348 (OwnerScope->isNamespace() && 5349 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) { 5350 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 5351 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 5352 5353 // Recover by adding 'static'. 5354 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 5355 PrevSpec, DiagID, Policy); 5356 } 5357 // C++ [class.union]p6: 5358 // A storage class is not allowed in a declaration of an 5359 // anonymous union in a class scope. 5360 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 5361 isa<RecordDecl>(Owner)) { 5362 Diag(DS.getStorageClassSpecLoc(), 5363 diag::err_anonymous_union_with_storage_spec) 5364 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 5365 5366 // Recover by removing the storage specifier. 5367 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 5368 SourceLocation(), 5369 PrevSpec, DiagID, Context.getPrintingPolicy()); 5370 } 5371 } 5372 5373 // Ignore const/volatile/restrict qualifiers. 5374 if (DS.getTypeQualifiers()) { 5375 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 5376 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 5377 << Record->isUnion() << "const" 5378 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 5379 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 5380 Diag(DS.getVolatileSpecLoc(), 5381 diag::ext_anonymous_struct_union_qualified) 5382 << Record->isUnion() << "volatile" 5383 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 5384 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 5385 Diag(DS.getRestrictSpecLoc(), 5386 diag::ext_anonymous_struct_union_qualified) 5387 << Record->isUnion() << "restrict" 5388 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 5389 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 5390 Diag(DS.getAtomicSpecLoc(), 5391 diag::ext_anonymous_struct_union_qualified) 5392 << Record->isUnion() << "_Atomic" 5393 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 5394 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 5395 Diag(DS.getUnalignedSpecLoc(), 5396 diag::ext_anonymous_struct_union_qualified) 5397 << Record->isUnion() << "__unaligned" 5398 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 5399 5400 DS.ClearTypeQualifiers(); 5401 } 5402 5403 // C++ [class.union]p2: 5404 // The member-specification of an anonymous union shall only 5405 // define non-static data members. [Note: nested types and 5406 // functions cannot be declared within an anonymous union. ] 5407 for (auto *Mem : Record->decls()) { 5408 // Ignore invalid declarations; we already diagnosed them. 5409 if (Mem->isInvalidDecl()) 5410 continue; 5411 5412 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 5413 // C++ [class.union]p3: 5414 // An anonymous union shall not have private or protected 5415 // members (clause 11). 5416 assert(FD->getAccess() != AS_none); 5417 if (FD->getAccess() != AS_public) { 5418 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 5419 << Record->isUnion() << (FD->getAccess() == AS_protected); 5420 Invalid = true; 5421 } 5422 5423 // C++ [class.union]p1 5424 // An object of a class with a non-trivial constructor, a non-trivial 5425 // copy constructor, a non-trivial destructor, or a non-trivial copy 5426 // assignment operator cannot be a member of a union, nor can an 5427 // array of such objects. 5428 if (CheckNontrivialField(FD)) 5429 Invalid = true; 5430 } else if (Mem->isImplicit()) { 5431 // Any implicit members are fine. 5432 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 5433 // This is a type that showed up in an 5434 // elaborated-type-specifier inside the anonymous struct or 5435 // union, but which actually declares a type outside of the 5436 // anonymous struct or union. It's okay. 5437 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 5438 if (!MemRecord->isAnonymousStructOrUnion() && 5439 MemRecord->getDeclName()) { 5440 // Visual C++ allows type definition in anonymous struct or union. 5441 if (getLangOpts().MicrosoftExt) 5442 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 5443 << Record->isUnion(); 5444 else { 5445 // This is a nested type declaration. 5446 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 5447 << Record->isUnion(); 5448 Invalid = true; 5449 } 5450 } else { 5451 // This is an anonymous type definition within another anonymous type. 5452 // This is a popular extension, provided by Plan9, MSVC and GCC, but 5453 // not part of standard C++. 5454 Diag(MemRecord->getLocation(), 5455 diag::ext_anonymous_record_with_anonymous_type) 5456 << Record->isUnion(); 5457 } 5458 } else if (isa<AccessSpecDecl>(Mem)) { 5459 // Any access specifier is fine. 5460 } else if (isa<StaticAssertDecl>(Mem)) { 5461 // In C++1z, static_assert declarations are also fine. 5462 } else { 5463 // We have something that isn't a non-static data 5464 // member. Complain about it. 5465 unsigned DK = diag::err_anonymous_record_bad_member; 5466 if (isa<TypeDecl>(Mem)) 5467 DK = diag::err_anonymous_record_with_type; 5468 else if (isa<FunctionDecl>(Mem)) 5469 DK = diag::err_anonymous_record_with_function; 5470 else if (isa<VarDecl>(Mem)) 5471 DK = diag::err_anonymous_record_with_static; 5472 5473 // Visual C++ allows type definition in anonymous struct or union. 5474 if (getLangOpts().MicrosoftExt && 5475 DK == diag::err_anonymous_record_with_type) 5476 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 5477 << Record->isUnion(); 5478 else { 5479 Diag(Mem->getLocation(), DK) << Record->isUnion(); 5480 Invalid = true; 5481 } 5482 } 5483 } 5484 5485 // C++11 [class.union]p8 (DR1460): 5486 // At most one variant member of a union may have a 5487 // brace-or-equal-initializer. 5488 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 5489 Owner->isRecord()) 5490 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 5491 cast<CXXRecordDecl>(Record)); 5492 } 5493 5494 if (!Record->isUnion() && !Owner->isRecord()) { 5495 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 5496 << getLangOpts().CPlusPlus; 5497 Invalid = true; 5498 } 5499 5500 // C++ [dcl.dcl]p3: 5501 // [If there are no declarators], and except for the declaration of an 5502 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 5503 // names into the program 5504 // C++ [class.mem]p2: 5505 // each such member-declaration shall either declare at least one member 5506 // name of the class or declare at least one unnamed bit-field 5507 // 5508 // For C this is an error even for a named struct, and is diagnosed elsewhere. 5509 if (getLangOpts().CPlusPlus && Record->field_empty()) 5510 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); 5511 5512 // Mock up a declarator. 5513 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::Member); 5514 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5515 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 5516 5517 // Create a declaration for this anonymous struct/union. 5518 NamedDecl *Anon = nullptr; 5519 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 5520 Anon = FieldDecl::Create( 5521 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(), 5522 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo, 5523 /*BitWidth=*/nullptr, /*Mutable=*/false, 5524 /*InitStyle=*/ICIS_NoInit); 5525 Anon->setAccess(AS); 5526 ProcessDeclAttributes(S, Anon, Dc); 5527 5528 if (getLangOpts().CPlusPlus) 5529 FieldCollector->Add(cast<FieldDecl>(Anon)); 5530 } else { 5531 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 5532 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 5533 if (SCSpec == DeclSpec::SCS_mutable) { 5534 // mutable can only appear on non-static class members, so it's always 5535 // an error here 5536 Diag(Record->getLocation(), diag::err_mutable_nonmember); 5537 Invalid = true; 5538 SC = SC_None; 5539 } 5540 5541 assert(DS.getAttributes().empty() && "No attribute expected"); 5542 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(), 5543 Record->getLocation(), /*IdentifierInfo=*/nullptr, 5544 Context.getTypeDeclType(Record), TInfo, SC); 5545 5546 // Default-initialize the implicit variable. This initialization will be 5547 // trivial in almost all cases, except if a union member has an in-class 5548 // initializer: 5549 // union { int n = 0; }; 5550 ActOnUninitializedDecl(Anon); 5551 } 5552 Anon->setImplicit(); 5553 5554 // Mark this as an anonymous struct/union type. 5555 Record->setAnonymousStructOrUnion(true); 5556 5557 // Add the anonymous struct/union object to the current 5558 // context. We'll be referencing this object when we refer to one of 5559 // its members. 5560 Owner->addDecl(Anon); 5561 5562 // Inject the members of the anonymous struct/union into the owning 5563 // context and into the identifier resolver chain for name lookup 5564 // purposes. 5565 SmallVector<NamedDecl*, 2> Chain; 5566 Chain.push_back(Anon); 5567 5568 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 5569 Invalid = true; 5570 5571 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 5572 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 5573 MangleNumberingContext *MCtx; 5574 Decl *ManglingContextDecl; 5575 std::tie(MCtx, ManglingContextDecl) = 5576 getCurrentMangleNumberContext(NewVD->getDeclContext()); 5577 if (MCtx) { 5578 Context.setManglingNumber( 5579 NewVD, MCtx->getManglingNumber( 5580 NewVD, getMSManglingNumber(getLangOpts(), S))); 5581 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 5582 } 5583 } 5584 } 5585 5586 if (Invalid) 5587 Anon->setInvalidDecl(); 5588 5589 return Anon; 5590 } 5591 5592 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 5593 /// Microsoft C anonymous structure. 5594 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 5595 /// Example: 5596 /// 5597 /// struct A { int a; }; 5598 /// struct B { struct A; int b; }; 5599 /// 5600 /// void foo() { 5601 /// B var; 5602 /// var.a = 3; 5603 /// } 5604 /// 5605 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 5606 RecordDecl *Record) { 5607 assert(Record && "expected a record!"); 5608 5609 // Mock up a declarator. 5610 Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::TypeName); 5611 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5612 assert(TInfo && "couldn't build declarator info for anonymous struct"); 5613 5614 auto *ParentDecl = cast<RecordDecl>(CurContext); 5615 QualType RecTy = Context.getTypeDeclType(Record); 5616 5617 // Create a declaration for this anonymous struct. 5618 NamedDecl *Anon = 5619 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(), 5620 /*IdentifierInfo=*/nullptr, RecTy, TInfo, 5621 /*BitWidth=*/nullptr, /*Mutable=*/false, 5622 /*InitStyle=*/ICIS_NoInit); 5623 Anon->setImplicit(); 5624 5625 // Add the anonymous struct object to the current context. 5626 CurContext->addDecl(Anon); 5627 5628 // Inject the members of the anonymous struct into the current 5629 // context and into the identifier resolver chain for name lookup 5630 // purposes. 5631 SmallVector<NamedDecl*, 2> Chain; 5632 Chain.push_back(Anon); 5633 5634 RecordDecl *RecordDef = Record->getDefinition(); 5635 if (RequireCompleteSizedType(Anon->getLocation(), RecTy, 5636 diag::err_field_incomplete_or_sizeless) || 5637 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 5638 AS_none, Chain)) { 5639 Anon->setInvalidDecl(); 5640 ParentDecl->setInvalidDecl(); 5641 } 5642 5643 return Anon; 5644 } 5645 5646 /// GetNameForDeclarator - Determine the full declaration name for the 5647 /// given Declarator. 5648 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 5649 return GetNameFromUnqualifiedId(D.getName()); 5650 } 5651 5652 /// Retrieves the declaration name from a parsed unqualified-id. 5653 DeclarationNameInfo 5654 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 5655 DeclarationNameInfo NameInfo; 5656 NameInfo.setLoc(Name.StartLocation); 5657 5658 switch (Name.getKind()) { 5659 5660 case UnqualifiedIdKind::IK_ImplicitSelfParam: 5661 case UnqualifiedIdKind::IK_Identifier: 5662 NameInfo.setName(Name.Identifier); 5663 return NameInfo; 5664 5665 case UnqualifiedIdKind::IK_DeductionGuideName: { 5666 // C++ [temp.deduct.guide]p3: 5667 // The simple-template-id shall name a class template specialization. 5668 // The template-name shall be the same identifier as the template-name 5669 // of the simple-template-id. 5670 // These together intend to imply that the template-name shall name a 5671 // class template. 5672 // FIXME: template<typename T> struct X {}; 5673 // template<typename T> using Y = X<T>; 5674 // Y(int) -> Y<int>; 5675 // satisfies these rules but does not name a class template. 5676 TemplateName TN = Name.TemplateName.get().get(); 5677 auto *Template = TN.getAsTemplateDecl(); 5678 if (!Template || !isa<ClassTemplateDecl>(Template)) { 5679 Diag(Name.StartLocation, 5680 diag::err_deduction_guide_name_not_class_template) 5681 << (int)getTemplateNameKindForDiagnostics(TN) << TN; 5682 if (Template) 5683 Diag(Template->getLocation(), diag::note_template_decl_here); 5684 return DeclarationNameInfo(); 5685 } 5686 5687 NameInfo.setName( 5688 Context.DeclarationNames.getCXXDeductionGuideName(Template)); 5689 return NameInfo; 5690 } 5691 5692 case UnqualifiedIdKind::IK_OperatorFunctionId: 5693 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 5694 Name.OperatorFunctionId.Operator)); 5695 NameInfo.setCXXOperatorNameRange(SourceRange( 5696 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation)); 5697 return NameInfo; 5698 5699 case UnqualifiedIdKind::IK_LiteralOperatorId: 5700 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 5701 Name.Identifier)); 5702 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 5703 return NameInfo; 5704 5705 case UnqualifiedIdKind::IK_ConversionFunctionId: { 5706 TypeSourceInfo *TInfo; 5707 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 5708 if (Ty.isNull()) 5709 return DeclarationNameInfo(); 5710 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 5711 Context.getCanonicalType(Ty))); 5712 NameInfo.setNamedTypeInfo(TInfo); 5713 return NameInfo; 5714 } 5715 5716 case UnqualifiedIdKind::IK_ConstructorName: { 5717 TypeSourceInfo *TInfo; 5718 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 5719 if (Ty.isNull()) 5720 return DeclarationNameInfo(); 5721 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5722 Context.getCanonicalType(Ty))); 5723 NameInfo.setNamedTypeInfo(TInfo); 5724 return NameInfo; 5725 } 5726 5727 case UnqualifiedIdKind::IK_ConstructorTemplateId: { 5728 // In well-formed code, we can only have a constructor 5729 // template-id that refers to the current context, so go there 5730 // to find the actual type being constructed. 5731 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 5732 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 5733 return DeclarationNameInfo(); 5734 5735 // Determine the type of the class being constructed. 5736 QualType CurClassType = Context.getTypeDeclType(CurClass); 5737 5738 // FIXME: Check two things: that the template-id names the same type as 5739 // CurClassType, and that the template-id does not occur when the name 5740 // was qualified. 5741 5742 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5743 Context.getCanonicalType(CurClassType))); 5744 // FIXME: should we retrieve TypeSourceInfo? 5745 NameInfo.setNamedTypeInfo(nullptr); 5746 return NameInfo; 5747 } 5748 5749 case UnqualifiedIdKind::IK_DestructorName: { 5750 TypeSourceInfo *TInfo; 5751 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 5752 if (Ty.isNull()) 5753 return DeclarationNameInfo(); 5754 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 5755 Context.getCanonicalType(Ty))); 5756 NameInfo.setNamedTypeInfo(TInfo); 5757 return NameInfo; 5758 } 5759 5760 case UnqualifiedIdKind::IK_TemplateId: { 5761 TemplateName TName = Name.TemplateId->Template.get(); 5762 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 5763 return Context.getNameForTemplate(TName, TNameLoc); 5764 } 5765 5766 } // switch (Name.getKind()) 5767 5768 llvm_unreachable("Unknown name kind"); 5769 } 5770 5771 static QualType getCoreType(QualType Ty) { 5772 do { 5773 if (Ty->isPointerType() || Ty->isReferenceType()) 5774 Ty = Ty->getPointeeType(); 5775 else if (Ty->isArrayType()) 5776 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 5777 else 5778 return Ty.withoutLocalFastQualifiers(); 5779 } while (true); 5780 } 5781 5782 /// hasSimilarParameters - Determine whether the C++ functions Declaration 5783 /// and Definition have "nearly" matching parameters. This heuristic is 5784 /// used to improve diagnostics in the case where an out-of-line function 5785 /// definition doesn't match any declaration within the class or namespace. 5786 /// Also sets Params to the list of indices to the parameters that differ 5787 /// between the declaration and the definition. If hasSimilarParameters 5788 /// returns true and Params is empty, then all of the parameters match. 5789 static bool hasSimilarParameters(ASTContext &Context, 5790 FunctionDecl *Declaration, 5791 FunctionDecl *Definition, 5792 SmallVectorImpl<unsigned> &Params) { 5793 Params.clear(); 5794 if (Declaration->param_size() != Definition->param_size()) 5795 return false; 5796 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 5797 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 5798 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 5799 5800 // The parameter types are identical 5801 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy)) 5802 continue; 5803 5804 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 5805 QualType DefParamBaseTy = getCoreType(DefParamTy); 5806 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 5807 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 5808 5809 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 5810 (DeclTyName && DeclTyName == DefTyName)) 5811 Params.push_back(Idx); 5812 else // The two parameters aren't even close 5813 return false; 5814 } 5815 5816 return true; 5817 } 5818 5819 /// RebuildDeclaratorInCurrentInstantiation - Checks whether the given 5820 /// declarator needs to be rebuilt in the current instantiation. 5821 /// Any bits of declarator which appear before the name are valid for 5822 /// consideration here. That's specifically the type in the decl spec 5823 /// and the base type in any member-pointer chunks. 5824 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 5825 DeclarationName Name) { 5826 // The types we specifically need to rebuild are: 5827 // - typenames, typeofs, and decltypes 5828 // - types which will become injected class names 5829 // Of course, we also need to rebuild any type referencing such a 5830 // type. It's safest to just say "dependent", but we call out a 5831 // few cases here. 5832 5833 DeclSpec &DS = D.getMutableDeclSpec(); 5834 switch (DS.getTypeSpecType()) { 5835 case DeclSpec::TST_typename: 5836 case DeclSpec::TST_typeofType: 5837 case DeclSpec::TST_underlyingType: 5838 case DeclSpec::TST_atomic: { 5839 // Grab the type from the parser. 5840 TypeSourceInfo *TSI = nullptr; 5841 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 5842 if (T.isNull() || !T->isInstantiationDependentType()) break; 5843 5844 // Make sure there's a type source info. This isn't really much 5845 // of a waste; most dependent types should have type source info 5846 // attached already. 5847 if (!TSI) 5848 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 5849 5850 // Rebuild the type in the current instantiation. 5851 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 5852 if (!TSI) return true; 5853 5854 // Store the new type back in the decl spec. 5855 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 5856 DS.UpdateTypeRep(LocType); 5857 break; 5858 } 5859 5860 case DeclSpec::TST_decltype: 5861 case DeclSpec::TST_typeofExpr: { 5862 Expr *E = DS.getRepAsExpr(); 5863 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 5864 if (Result.isInvalid()) return true; 5865 DS.UpdateExprRep(Result.get()); 5866 break; 5867 } 5868 5869 default: 5870 // Nothing to do for these decl specs. 5871 break; 5872 } 5873 5874 // It doesn't matter what order we do this in. 5875 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 5876 DeclaratorChunk &Chunk = D.getTypeObject(I); 5877 5878 // The only type information in the declarator which can come 5879 // before the declaration name is the base type of a member 5880 // pointer. 5881 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 5882 continue; 5883 5884 // Rebuild the scope specifier in-place. 5885 CXXScopeSpec &SS = Chunk.Mem.Scope(); 5886 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 5887 return true; 5888 } 5889 5890 return false; 5891 } 5892 5893 /// Returns true if the declaration is declared in a system header or from a 5894 /// system macro. 5895 static bool isFromSystemHeader(SourceManager &SM, const Decl *D) { 5896 return SM.isInSystemHeader(D->getLocation()) || 5897 SM.isInSystemMacro(D->getLocation()); 5898 } 5899 5900 void Sema::warnOnReservedIdentifier(const NamedDecl *D) { 5901 // Avoid warning twice on the same identifier, and don't warn on redeclaration 5902 // of system decl. 5903 if (D->getPreviousDecl() || D->isImplicit()) 5904 return; 5905 ReservedIdentifierStatus Status = D->isReserved(getLangOpts()); 5906 if (Status != ReservedIdentifierStatus::NotReserved && 5907 !isFromSystemHeader(Context.getSourceManager(), D)) { 5908 Diag(D->getLocation(), diag::warn_reserved_extern_symbol) 5909 << D << static_cast<int>(Status); 5910 } 5911 } 5912 5913 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 5914 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration); 5915 5916 // Check if we are in an `omp begin/end declare variant` scope. Handle this 5917 // declaration only if the `bind_to_declaration` extension is set. 5918 SmallVector<FunctionDecl *, 4> Bases; 5919 if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope()) 5920 if (getOMPTraitInfoForSurroundingScope()->isExtensionActive(llvm::omp::TraitProperty:: 5921 implementation_extension_bind_to_declaration)) 5922 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( 5923 S, D, MultiTemplateParamsArg(), Bases); 5924 5925 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 5926 5927 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 5928 Dcl && Dcl->getDeclContext()->isFileContext()) 5929 Dcl->setTopLevelDeclInObjCContainer(); 5930 5931 if (!Bases.empty()) 5932 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases); 5933 5934 return Dcl; 5935 } 5936 5937 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 5938 /// If T is the name of a class, then each of the following shall have a 5939 /// name different from T: 5940 /// - every static data member of class T; 5941 /// - every member function of class T 5942 /// - every member of class T that is itself a type; 5943 /// \returns true if the declaration name violates these rules. 5944 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 5945 DeclarationNameInfo NameInfo) { 5946 DeclarationName Name = NameInfo.getName(); 5947 5948 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 5949 while (Record && Record->isAnonymousStructOrUnion()) 5950 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 5951 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 5952 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 5953 return true; 5954 } 5955 5956 return false; 5957 } 5958 5959 /// Diagnose a declaration whose declarator-id has the given 5960 /// nested-name-specifier. 5961 /// 5962 /// \param SS The nested-name-specifier of the declarator-id. 5963 /// 5964 /// \param DC The declaration context to which the nested-name-specifier 5965 /// resolves. 5966 /// 5967 /// \param Name The name of the entity being declared. 5968 /// 5969 /// \param Loc The location of the name of the entity being declared. 5970 /// 5971 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus 5972 /// we're declaring an explicit / partial specialization / instantiation. 5973 /// 5974 /// \returns true if we cannot safely recover from this error, false otherwise. 5975 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 5976 DeclarationName Name, 5977 SourceLocation Loc, bool IsTemplateId) { 5978 DeclContext *Cur = CurContext; 5979 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 5980 Cur = Cur->getParent(); 5981 5982 // If the user provided a superfluous scope specifier that refers back to the 5983 // class in which the entity is already declared, diagnose and ignore it. 5984 // 5985 // class X { 5986 // void X::f(); 5987 // }; 5988 // 5989 // Note, it was once ill-formed to give redundant qualification in all 5990 // contexts, but that rule was removed by DR482. 5991 if (Cur->Equals(DC)) { 5992 if (Cur->isRecord()) { 5993 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 5994 : diag::err_member_extra_qualification) 5995 << Name << FixItHint::CreateRemoval(SS.getRange()); 5996 SS.clear(); 5997 } else { 5998 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 5999 } 6000 return false; 6001 } 6002 6003 // Check whether the qualifying scope encloses the scope of the original 6004 // declaration. For a template-id, we perform the checks in 6005 // CheckTemplateSpecializationScope. 6006 if (!Cur->Encloses(DC) && !IsTemplateId) { 6007 if (Cur->isRecord()) 6008 Diag(Loc, diag::err_member_qualification) 6009 << Name << SS.getRange(); 6010 else if (isa<TranslationUnitDecl>(DC)) 6011 Diag(Loc, diag::err_invalid_declarator_global_scope) 6012 << Name << SS.getRange(); 6013 else if (isa<FunctionDecl>(Cur)) 6014 Diag(Loc, diag::err_invalid_declarator_in_function) 6015 << Name << SS.getRange(); 6016 else if (isa<BlockDecl>(Cur)) 6017 Diag(Loc, diag::err_invalid_declarator_in_block) 6018 << Name << SS.getRange(); 6019 else if (isa<ExportDecl>(Cur)) { 6020 if (!isa<NamespaceDecl>(DC)) 6021 Diag(Loc, diag::err_export_non_namespace_scope_name) 6022 << Name << SS.getRange(); 6023 else 6024 // The cases that DC is not NamespaceDecl should be handled in 6025 // CheckRedeclarationExported. 6026 return false; 6027 } else 6028 Diag(Loc, diag::err_invalid_declarator_scope) 6029 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 6030 6031 return true; 6032 } 6033 6034 if (Cur->isRecord()) { 6035 // Cannot qualify members within a class. 6036 Diag(Loc, diag::err_member_qualification) 6037 << Name << SS.getRange(); 6038 SS.clear(); 6039 6040 // C++ constructors and destructors with incorrect scopes can break 6041 // our AST invariants by having the wrong underlying types. If 6042 // that's the case, then drop this declaration entirely. 6043 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 6044 Name.getNameKind() == DeclarationName::CXXDestructorName) && 6045 !Context.hasSameType(Name.getCXXNameType(), 6046 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 6047 return true; 6048 6049 return false; 6050 } 6051 6052 // C++11 [dcl.meaning]p1: 6053 // [...] "The nested-name-specifier of the qualified declarator-id shall 6054 // not begin with a decltype-specifer" 6055 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 6056 while (SpecLoc.getPrefix()) 6057 SpecLoc = SpecLoc.getPrefix(); 6058 if (isa_and_nonnull<DecltypeType>( 6059 SpecLoc.getNestedNameSpecifier()->getAsType())) 6060 Diag(Loc, diag::err_decltype_in_declarator) 6061 << SpecLoc.getTypeLoc().getSourceRange(); 6062 6063 return false; 6064 } 6065 6066 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 6067 MultiTemplateParamsArg TemplateParamLists) { 6068 // TODO: consider using NameInfo for diagnostic. 6069 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 6070 DeclarationName Name = NameInfo.getName(); 6071 6072 // All of these full declarators require an identifier. If it doesn't have 6073 // one, the ParsedFreeStandingDeclSpec action should be used. 6074 if (D.isDecompositionDeclarator()) { 6075 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 6076 } else if (!Name) { 6077 if (!D.isInvalidType()) // Reject this if we think it is valid. 6078 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident) 6079 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 6080 return nullptr; 6081 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 6082 return nullptr; 6083 6084 // The scope passed in may not be a decl scope. Zip up the scope tree until 6085 // we find one that is. 6086 while ((S->getFlags() & Scope::DeclScope) == 0 || 6087 (S->getFlags() & Scope::TemplateParamScope) != 0) 6088 S = S->getParent(); 6089 6090 DeclContext *DC = CurContext; 6091 if (D.getCXXScopeSpec().isInvalid()) 6092 D.setInvalidType(); 6093 else if (D.getCXXScopeSpec().isSet()) { 6094 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 6095 UPPC_DeclarationQualifier)) 6096 return nullptr; 6097 6098 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 6099 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 6100 if (!DC || isa<EnumDecl>(DC)) { 6101 // If we could not compute the declaration context, it's because the 6102 // declaration context is dependent but does not refer to a class, 6103 // class template, or class template partial specialization. Complain 6104 // and return early, to avoid the coming semantic disaster. 6105 Diag(D.getIdentifierLoc(), 6106 diag::err_template_qualified_declarator_no_match) 6107 << D.getCXXScopeSpec().getScopeRep() 6108 << D.getCXXScopeSpec().getRange(); 6109 return nullptr; 6110 } 6111 bool IsDependentContext = DC->isDependentContext(); 6112 6113 if (!IsDependentContext && 6114 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 6115 return nullptr; 6116 6117 // If a class is incomplete, do not parse entities inside it. 6118 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 6119 Diag(D.getIdentifierLoc(), 6120 diag::err_member_def_undefined_record) 6121 << Name << DC << D.getCXXScopeSpec().getRange(); 6122 return nullptr; 6123 } 6124 if (!D.getDeclSpec().isFriendSpecified()) { 6125 if (diagnoseQualifiedDeclaration( 6126 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(), 6127 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) { 6128 if (DC->isRecord()) 6129 return nullptr; 6130 6131 D.setInvalidType(); 6132 } 6133 } 6134 6135 // Check whether we need to rebuild the type of the given 6136 // declaration in the current instantiation. 6137 if (EnteringContext && IsDependentContext && 6138 TemplateParamLists.size() != 0) { 6139 ContextRAII SavedContext(*this, DC); 6140 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 6141 D.setInvalidType(); 6142 } 6143 } 6144 6145 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 6146 QualType R = TInfo->getType(); 6147 6148 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 6149 UPPC_DeclarationType)) 6150 D.setInvalidType(); 6151 6152 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 6153 forRedeclarationInCurContext()); 6154 6155 // See if this is a redefinition of a variable in the same scope. 6156 if (!D.getCXXScopeSpec().isSet()) { 6157 bool IsLinkageLookup = false; 6158 bool CreateBuiltins = false; 6159 6160 // If the declaration we're planning to build will be a function 6161 // or object with linkage, then look for another declaration with 6162 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 6163 // 6164 // If the declaration we're planning to build will be declared with 6165 // external linkage in the translation unit, create any builtin with 6166 // the same name. 6167 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 6168 /* Do nothing*/; 6169 else if (CurContext->isFunctionOrMethod() && 6170 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 6171 R->isFunctionType())) { 6172 IsLinkageLookup = true; 6173 CreateBuiltins = 6174 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 6175 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 6176 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 6177 CreateBuiltins = true; 6178 6179 if (IsLinkageLookup) { 6180 Previous.clear(LookupRedeclarationWithLinkage); 6181 Previous.setRedeclarationKind(ForExternalRedeclaration); 6182 } 6183 6184 LookupName(Previous, S, CreateBuiltins); 6185 } else { // Something like "int foo::x;" 6186 LookupQualifiedName(Previous, DC); 6187 6188 // C++ [dcl.meaning]p1: 6189 // When the declarator-id is qualified, the declaration shall refer to a 6190 // previously declared member of the class or namespace to which the 6191 // qualifier refers (or, in the case of a namespace, of an element of the 6192 // inline namespace set of that namespace (7.3.1)) or to a specialization 6193 // thereof; [...] 6194 // 6195 // Note that we already checked the context above, and that we do not have 6196 // enough information to make sure that Previous contains the declaration 6197 // we want to match. For example, given: 6198 // 6199 // class X { 6200 // void f(); 6201 // void f(float); 6202 // }; 6203 // 6204 // void X::f(int) { } // ill-formed 6205 // 6206 // In this case, Previous will point to the overload set 6207 // containing the two f's declared in X, but neither of them 6208 // matches. 6209 6210 // C++ [dcl.meaning]p1: 6211 // [...] the member shall not merely have been introduced by a 6212 // using-declaration in the scope of the class or namespace nominated by 6213 // the nested-name-specifier of the declarator-id. 6214 RemoveUsingDecls(Previous); 6215 } 6216 6217 if (Previous.isSingleResult() && 6218 Previous.getFoundDecl()->isTemplateParameter()) { 6219 // Maybe we will complain about the shadowed template parameter. 6220 if (!D.isInvalidType()) 6221 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 6222 Previous.getFoundDecl()); 6223 6224 // Just pretend that we didn't see the previous declaration. 6225 Previous.clear(); 6226 } 6227 6228 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 6229 // Forget that the previous declaration is the injected-class-name. 6230 Previous.clear(); 6231 6232 // In C++, the previous declaration we find might be a tag type 6233 // (class or enum). In this case, the new declaration will hide the 6234 // tag type. Note that this applies to functions, function templates, and 6235 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. 6236 if (Previous.isSingleTagDecl() && 6237 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 6238 (TemplateParamLists.size() == 0 || R->isFunctionType())) 6239 Previous.clear(); 6240 6241 // Check that there are no default arguments other than in the parameters 6242 // of a function declaration (C++ only). 6243 if (getLangOpts().CPlusPlus) 6244 CheckExtraCXXDefaultArguments(D); 6245 6246 NamedDecl *New; 6247 6248 bool AddToScope = true; 6249 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 6250 if (TemplateParamLists.size()) { 6251 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 6252 return nullptr; 6253 } 6254 6255 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 6256 } else if (R->isFunctionType()) { 6257 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 6258 TemplateParamLists, 6259 AddToScope); 6260 } else { 6261 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 6262 AddToScope); 6263 } 6264 6265 if (!New) 6266 return nullptr; 6267 6268 // If this has an identifier and is not a function template specialization, 6269 // add it to the scope stack. 6270 if (New->getDeclName() && AddToScope) 6271 PushOnScopeChains(New, S); 6272 6273 if (isInOpenMPDeclareTargetContext()) 6274 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 6275 6276 return New; 6277 } 6278 6279 /// Helper method to turn variable array types into constant array 6280 /// types in certain situations which would otherwise be errors (for 6281 /// GCC compatibility). 6282 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 6283 ASTContext &Context, 6284 bool &SizeIsNegative, 6285 llvm::APSInt &Oversized) { 6286 // This method tries to turn a variable array into a constant 6287 // array even when the size isn't an ICE. This is necessary 6288 // for compatibility with code that depends on gcc's buggy 6289 // constant expression folding, like struct {char x[(int)(char*)2];} 6290 SizeIsNegative = false; 6291 Oversized = 0; 6292 6293 if (T->isDependentType()) 6294 return QualType(); 6295 6296 QualifierCollector Qs; 6297 const Type *Ty = Qs.strip(T); 6298 6299 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 6300 QualType Pointee = PTy->getPointeeType(); 6301 QualType FixedType = 6302 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 6303 Oversized); 6304 if (FixedType.isNull()) return FixedType; 6305 FixedType = Context.getPointerType(FixedType); 6306 return Qs.apply(Context, FixedType); 6307 } 6308 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 6309 QualType Inner = PTy->getInnerType(); 6310 QualType FixedType = 6311 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 6312 Oversized); 6313 if (FixedType.isNull()) return FixedType; 6314 FixedType = Context.getParenType(FixedType); 6315 return Qs.apply(Context, FixedType); 6316 } 6317 6318 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 6319 if (!VLATy) 6320 return QualType(); 6321 6322 QualType ElemTy = VLATy->getElementType(); 6323 if (ElemTy->isVariablyModifiedType()) { 6324 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context, 6325 SizeIsNegative, Oversized); 6326 if (ElemTy.isNull()) 6327 return QualType(); 6328 } 6329 6330 Expr::EvalResult Result; 6331 if (!VLATy->getSizeExpr() || 6332 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context)) 6333 return QualType(); 6334 6335 llvm::APSInt Res = Result.Val.getInt(); 6336 6337 // Check whether the array size is negative. 6338 if (Res.isSigned() && Res.isNegative()) { 6339 SizeIsNegative = true; 6340 return QualType(); 6341 } 6342 6343 // Check whether the array is too large to be addressed. 6344 unsigned ActiveSizeBits = 6345 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() && 6346 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType()) 6347 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res) 6348 : Res.getActiveBits(); 6349 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 6350 Oversized = Res; 6351 return QualType(); 6352 } 6353 6354 QualType FoldedArrayType = Context.getConstantArrayType( 6355 ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0); 6356 return Qs.apply(Context, FoldedArrayType); 6357 } 6358 6359 static void 6360 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 6361 SrcTL = SrcTL.getUnqualifiedLoc(); 6362 DstTL = DstTL.getUnqualifiedLoc(); 6363 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 6364 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 6365 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 6366 DstPTL.getPointeeLoc()); 6367 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 6368 return; 6369 } 6370 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 6371 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 6372 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 6373 DstPTL.getInnerLoc()); 6374 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 6375 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 6376 return; 6377 } 6378 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 6379 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 6380 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 6381 TypeLoc DstElemTL = DstATL.getElementLoc(); 6382 if (VariableArrayTypeLoc SrcElemATL = 6383 SrcElemTL.getAs<VariableArrayTypeLoc>()) { 6384 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>(); 6385 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL); 6386 } else { 6387 DstElemTL.initializeFullCopy(SrcElemTL); 6388 } 6389 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 6390 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 6391 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 6392 } 6393 6394 /// Helper method to turn variable array types into constant array 6395 /// types in certain situations which would otherwise be errors (for 6396 /// GCC compatibility). 6397 static TypeSourceInfo* 6398 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 6399 ASTContext &Context, 6400 bool &SizeIsNegative, 6401 llvm::APSInt &Oversized) { 6402 QualType FixedTy 6403 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 6404 SizeIsNegative, Oversized); 6405 if (FixedTy.isNull()) 6406 return nullptr; 6407 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 6408 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 6409 FixedTInfo->getTypeLoc()); 6410 return FixedTInfo; 6411 } 6412 6413 /// Attempt to fold a variable-sized type to a constant-sized type, returning 6414 /// true if we were successful. 6415 bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, 6416 QualType &T, SourceLocation Loc, 6417 unsigned FailedFoldDiagID) { 6418 bool SizeIsNegative; 6419 llvm::APSInt Oversized; 6420 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 6421 TInfo, Context, SizeIsNegative, Oversized); 6422 if (FixedTInfo) { 6423 Diag(Loc, diag::ext_vla_folded_to_constant); 6424 TInfo = FixedTInfo; 6425 T = FixedTInfo->getType(); 6426 return true; 6427 } 6428 6429 if (SizeIsNegative) 6430 Diag(Loc, diag::err_typecheck_negative_array_size); 6431 else if (Oversized.getBoolValue()) 6432 Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10); 6433 else if (FailedFoldDiagID) 6434 Diag(Loc, FailedFoldDiagID); 6435 return false; 6436 } 6437 6438 /// Register the given locally-scoped extern "C" declaration so 6439 /// that it can be found later for redeclarations. We include any extern "C" 6440 /// declaration that is not visible in the translation unit here, not just 6441 /// function-scope declarations. 6442 void 6443 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 6444 if (!getLangOpts().CPlusPlus && 6445 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 6446 // Don't need to track declarations in the TU in C. 6447 return; 6448 6449 // Note that we have a locally-scoped external with this name. 6450 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 6451 } 6452 6453 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 6454 // FIXME: We can have multiple results via __attribute__((overloadable)). 6455 auto Result = Context.getExternCContextDecl()->lookup(Name); 6456 return Result.empty() ? nullptr : *Result.begin(); 6457 } 6458 6459 /// Diagnose function specifiers on a declaration of an identifier that 6460 /// does not identify a function. 6461 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 6462 // FIXME: We should probably indicate the identifier in question to avoid 6463 // confusion for constructs like "virtual int a(), b;" 6464 if (DS.isVirtualSpecified()) 6465 Diag(DS.getVirtualSpecLoc(), 6466 diag::err_virtual_non_function); 6467 6468 if (DS.hasExplicitSpecifier()) 6469 Diag(DS.getExplicitSpecLoc(), 6470 diag::err_explicit_non_function); 6471 6472 if (DS.isNoreturnSpecified()) 6473 Diag(DS.getNoreturnSpecLoc(), 6474 diag::err_noreturn_non_function); 6475 } 6476 6477 NamedDecl* 6478 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 6479 TypeSourceInfo *TInfo, LookupResult &Previous) { 6480 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 6481 if (D.getCXXScopeSpec().isSet()) { 6482 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 6483 << D.getCXXScopeSpec().getRange(); 6484 D.setInvalidType(); 6485 // Pretend we didn't see the scope specifier. 6486 DC = CurContext; 6487 Previous.clear(); 6488 } 6489 6490 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6491 6492 if (D.getDeclSpec().isInlineSpecified()) 6493 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6494 << getLangOpts().CPlusPlus17; 6495 if (D.getDeclSpec().hasConstexprSpecifier()) 6496 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 6497 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 6498 6499 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) { 6500 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName) 6501 Diag(D.getName().StartLocation, 6502 diag::err_deduction_guide_invalid_specifier) 6503 << "typedef"; 6504 else 6505 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 6506 << D.getName().getSourceRange(); 6507 return nullptr; 6508 } 6509 6510 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 6511 if (!NewTD) return nullptr; 6512 6513 // Handle attributes prior to checking for duplicates in MergeVarDecl 6514 ProcessDeclAttributes(S, NewTD, D); 6515 6516 CheckTypedefForVariablyModifiedType(S, NewTD); 6517 6518 bool Redeclaration = D.isRedeclaration(); 6519 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 6520 D.setRedeclaration(Redeclaration); 6521 return ND; 6522 } 6523 6524 void 6525 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 6526 // C99 6.7.7p2: If a typedef name specifies a variably modified type 6527 // then it shall have block scope. 6528 // Note that variably modified types must be fixed before merging the decl so 6529 // that redeclarations will match. 6530 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 6531 QualType T = TInfo->getType(); 6532 if (T->isVariablyModifiedType()) { 6533 setFunctionHasBranchProtectedScope(); 6534 6535 if (S->getFnParent() == nullptr) { 6536 bool SizeIsNegative; 6537 llvm::APSInt Oversized; 6538 TypeSourceInfo *FixedTInfo = 6539 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 6540 SizeIsNegative, 6541 Oversized); 6542 if (FixedTInfo) { 6543 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant); 6544 NewTD->setTypeSourceInfo(FixedTInfo); 6545 } else { 6546 if (SizeIsNegative) 6547 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 6548 else if (T->isVariableArrayType()) 6549 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 6550 else if (Oversized.getBoolValue()) 6551 Diag(NewTD->getLocation(), diag::err_array_too_large) 6552 << toString(Oversized, 10); 6553 else 6554 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 6555 NewTD->setInvalidDecl(); 6556 } 6557 } 6558 } 6559 } 6560 6561 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 6562 /// declares a typedef-name, either using the 'typedef' type specifier or via 6563 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 6564 NamedDecl* 6565 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 6566 LookupResult &Previous, bool &Redeclaration) { 6567 6568 // Find the shadowed declaration before filtering for scope. 6569 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); 6570 6571 // Merge the decl with the existing one if appropriate. If the decl is 6572 // in an outer scope, it isn't the same thing. 6573 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 6574 /*AllowInlineNamespace*/false); 6575 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 6576 if (!Previous.empty()) { 6577 Redeclaration = true; 6578 MergeTypedefNameDecl(S, NewTD, Previous); 6579 } else { 6580 inferGslPointerAttribute(NewTD); 6581 } 6582 6583 if (ShadowedDecl && !Redeclaration) 6584 CheckShadow(NewTD, ShadowedDecl, Previous); 6585 6586 // If this is the C FILE type, notify the AST context. 6587 if (IdentifierInfo *II = NewTD->getIdentifier()) 6588 if (!NewTD->isInvalidDecl() && 6589 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 6590 if (II->isStr("FILE")) 6591 Context.setFILEDecl(NewTD); 6592 else if (II->isStr("jmp_buf")) 6593 Context.setjmp_bufDecl(NewTD); 6594 else if (II->isStr("sigjmp_buf")) 6595 Context.setsigjmp_bufDecl(NewTD); 6596 else if (II->isStr("ucontext_t")) 6597 Context.setucontext_tDecl(NewTD); 6598 } 6599 6600 return NewTD; 6601 } 6602 6603 /// Determines whether the given declaration is an out-of-scope 6604 /// previous declaration. 6605 /// 6606 /// This routine should be invoked when name lookup has found a 6607 /// previous declaration (PrevDecl) that is not in the scope where a 6608 /// new declaration by the same name is being introduced. If the new 6609 /// declaration occurs in a local scope, previous declarations with 6610 /// linkage may still be considered previous declarations (C99 6611 /// 6.2.2p4-5, C++ [basic.link]p6). 6612 /// 6613 /// \param PrevDecl the previous declaration found by name 6614 /// lookup 6615 /// 6616 /// \param DC the context in which the new declaration is being 6617 /// declared. 6618 /// 6619 /// \returns true if PrevDecl is an out-of-scope previous declaration 6620 /// for a new delcaration with the same name. 6621 static bool 6622 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 6623 ASTContext &Context) { 6624 if (!PrevDecl) 6625 return false; 6626 6627 if (!PrevDecl->hasLinkage()) 6628 return false; 6629 6630 if (Context.getLangOpts().CPlusPlus) { 6631 // C++ [basic.link]p6: 6632 // If there is a visible declaration of an entity with linkage 6633 // having the same name and type, ignoring entities declared 6634 // outside the innermost enclosing namespace scope, the block 6635 // scope declaration declares that same entity and receives the 6636 // linkage of the previous declaration. 6637 DeclContext *OuterContext = DC->getRedeclContext(); 6638 if (!OuterContext->isFunctionOrMethod()) 6639 // This rule only applies to block-scope declarations. 6640 return false; 6641 6642 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 6643 if (PrevOuterContext->isRecord()) 6644 // We found a member function: ignore it. 6645 return false; 6646 6647 // Find the innermost enclosing namespace for the new and 6648 // previous declarations. 6649 OuterContext = OuterContext->getEnclosingNamespaceContext(); 6650 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 6651 6652 // The previous declaration is in a different namespace, so it 6653 // isn't the same function. 6654 if (!OuterContext->Equals(PrevOuterContext)) 6655 return false; 6656 } 6657 6658 return true; 6659 } 6660 6661 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) { 6662 CXXScopeSpec &SS = D.getCXXScopeSpec(); 6663 if (!SS.isSet()) return; 6664 DD->setQualifierInfo(SS.getWithLocInContext(S.Context)); 6665 } 6666 6667 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 6668 QualType type = decl->getType(); 6669 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 6670 if (lifetime == Qualifiers::OCL_Autoreleasing) { 6671 // Various kinds of declaration aren't allowed to be __autoreleasing. 6672 unsigned kind = -1U; 6673 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6674 if (var->hasAttr<BlocksAttr>()) 6675 kind = 0; // __block 6676 else if (!var->hasLocalStorage()) 6677 kind = 1; // global 6678 } else if (isa<ObjCIvarDecl>(decl)) { 6679 kind = 3; // ivar 6680 } else if (isa<FieldDecl>(decl)) { 6681 kind = 2; // field 6682 } 6683 6684 if (kind != -1U) { 6685 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 6686 << kind; 6687 } 6688 } else if (lifetime == Qualifiers::OCL_None) { 6689 // Try to infer lifetime. 6690 if (!type->isObjCLifetimeType()) 6691 return false; 6692 6693 lifetime = type->getObjCARCImplicitLifetime(); 6694 type = Context.getLifetimeQualifiedType(type, lifetime); 6695 decl->setType(type); 6696 } 6697 6698 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6699 // Thread-local variables cannot have lifetime. 6700 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 6701 var->getTLSKind()) { 6702 Diag(var->getLocation(), diag::err_arc_thread_ownership) 6703 << var->getType(); 6704 return true; 6705 } 6706 } 6707 6708 return false; 6709 } 6710 6711 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) { 6712 if (Decl->getType().hasAddressSpace()) 6713 return; 6714 if (Decl->getType()->isDependentType()) 6715 return; 6716 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) { 6717 QualType Type = Var->getType(); 6718 if (Type->isSamplerT() || Type->isVoidType()) 6719 return; 6720 LangAS ImplAS = LangAS::opencl_private; 6721 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the 6722 // __opencl_c_program_scope_global_variables feature, the address space 6723 // for a variable at program scope or a static or extern variable inside 6724 // a function are inferred to be __global. 6725 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) && 6726 Var->hasGlobalStorage()) 6727 ImplAS = LangAS::opencl_global; 6728 // If the original type from a decayed type is an array type and that array 6729 // type has no address space yet, deduce it now. 6730 if (auto DT = dyn_cast<DecayedType>(Type)) { 6731 auto OrigTy = DT->getOriginalType(); 6732 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) { 6733 // Add the address space to the original array type and then propagate 6734 // that to the element type through `getAsArrayType`. 6735 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS); 6736 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0); 6737 // Re-generate the decayed type. 6738 Type = Context.getDecayedType(OrigTy); 6739 } 6740 } 6741 Type = Context.getAddrSpaceQualType(Type, ImplAS); 6742 // Apply any qualifiers (including address space) from the array type to 6743 // the element type. This implements C99 6.7.3p8: "If the specification of 6744 // an array type includes any type qualifiers, the element type is so 6745 // qualified, not the array type." 6746 if (Type->isArrayType()) 6747 Type = QualType(Context.getAsArrayType(Type), 0); 6748 Decl->setType(Type); 6749 } 6750 } 6751 6752 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 6753 // Ensure that an auto decl is deduced otherwise the checks below might cache 6754 // the wrong linkage. 6755 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 6756 6757 // 'weak' only applies to declarations with external linkage. 6758 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 6759 if (!ND.isExternallyVisible()) { 6760 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 6761 ND.dropAttr<WeakAttr>(); 6762 } 6763 } 6764 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 6765 if (ND.isExternallyVisible()) { 6766 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 6767 ND.dropAttr<WeakRefAttr>(); 6768 ND.dropAttr<AliasAttr>(); 6769 } 6770 } 6771 6772 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 6773 if (VD->hasInit()) { 6774 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 6775 assert(VD->isThisDeclarationADefinition() && 6776 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 6777 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 6778 VD->dropAttr<AliasAttr>(); 6779 } 6780 } 6781 } 6782 6783 // 'selectany' only applies to externally visible variable declarations. 6784 // It does not apply to functions. 6785 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 6786 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 6787 S.Diag(Attr->getLocation(), 6788 diag::err_attribute_selectany_non_extern_data); 6789 ND.dropAttr<SelectAnyAttr>(); 6790 } 6791 } 6792 6793 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 6794 auto *VD = dyn_cast<VarDecl>(&ND); 6795 bool IsAnonymousNS = false; 6796 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6797 if (VD) { 6798 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext()); 6799 while (NS && !IsAnonymousNS) { 6800 IsAnonymousNS = NS->isAnonymousNamespace(); 6801 NS = dyn_cast<NamespaceDecl>(NS->getParent()); 6802 } 6803 } 6804 // dll attributes require external linkage. Static locals may have external 6805 // linkage but still cannot be explicitly imported or exported. 6806 // In Microsoft mode, a variable defined in anonymous namespace must have 6807 // external linkage in order to be exported. 6808 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft; 6809 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) || 6810 (!AnonNSInMicrosoftMode && 6811 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) { 6812 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 6813 << &ND << Attr; 6814 ND.setInvalidDecl(); 6815 } 6816 } 6817 6818 // Check the attributes on the function type, if any. 6819 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) { 6820 // Don't declare this variable in the second operand of the for-statement; 6821 // GCC miscompiles that by ending its lifetime before evaluating the 6822 // third operand. See gcc.gnu.org/PR86769. 6823 AttributedTypeLoc ATL; 6824 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc(); 6825 (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); 6826 TL = ATL.getModifiedLoc()) { 6827 // The [[lifetimebound]] attribute can be applied to the implicit object 6828 // parameter of a non-static member function (other than a ctor or dtor) 6829 // by applying it to the function type. 6830 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) { 6831 const auto *MD = dyn_cast<CXXMethodDecl>(FD); 6832 if (!MD || MD->isStatic()) { 6833 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param) 6834 << !MD << A->getRange(); 6835 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) { 6836 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor) 6837 << isa<CXXDestructorDecl>(MD) << A->getRange(); 6838 } 6839 } 6840 } 6841 } 6842 } 6843 6844 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 6845 NamedDecl *NewDecl, 6846 bool IsSpecialization, 6847 bool IsDefinition) { 6848 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl()) 6849 return; 6850 6851 bool IsTemplate = false; 6852 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 6853 OldDecl = OldTD->getTemplatedDecl(); 6854 IsTemplate = true; 6855 if (!IsSpecialization) 6856 IsDefinition = false; 6857 } 6858 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { 6859 NewDecl = NewTD->getTemplatedDecl(); 6860 IsTemplate = true; 6861 } 6862 6863 if (!OldDecl || !NewDecl) 6864 return; 6865 6866 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 6867 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 6868 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 6869 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 6870 6871 // dllimport and dllexport are inheritable attributes so we have to exclude 6872 // inherited attribute instances. 6873 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 6874 (NewExportAttr && !NewExportAttr->isInherited()); 6875 6876 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 6877 // the only exception being explicit specializations. 6878 // Implicitly generated declarations are also excluded for now because there 6879 // is no other way to switch these to use dllimport or dllexport. 6880 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 6881 6882 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 6883 // Allow with a warning for free functions and global variables. 6884 bool JustWarn = false; 6885 if (!OldDecl->isCXXClassMember()) { 6886 auto *VD = dyn_cast<VarDecl>(OldDecl); 6887 if (VD && !VD->getDescribedVarTemplate()) 6888 JustWarn = true; 6889 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 6890 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 6891 JustWarn = true; 6892 } 6893 6894 // We cannot change a declaration that's been used because IR has already 6895 // been emitted. Dllimported functions will still work though (modulo 6896 // address equality) as they can use the thunk. 6897 if (OldDecl->isUsed()) 6898 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 6899 JustWarn = false; 6900 6901 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 6902 : diag::err_attribute_dll_redeclaration; 6903 S.Diag(NewDecl->getLocation(), DiagID) 6904 << NewDecl 6905 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 6906 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6907 if (!JustWarn) { 6908 NewDecl->setInvalidDecl(); 6909 return; 6910 } 6911 } 6912 6913 // A redeclaration is not allowed to drop a dllimport attribute, the only 6914 // exceptions being inline function definitions (except for function 6915 // templates), local extern declarations, qualified friend declarations or 6916 // special MSVC extension: in the last case, the declaration is treated as if 6917 // it were marked dllexport. 6918 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 6919 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols(); 6920 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 6921 // Ignore static data because out-of-line definitions are diagnosed 6922 // separately. 6923 IsStaticDataMember = VD->isStaticDataMember(); 6924 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 6925 VarDecl::DeclarationOnly; 6926 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 6927 IsInline = FD->isInlined(); 6928 IsQualifiedFriend = FD->getQualifier() && 6929 FD->getFriendObjectKind() == Decl::FOK_Declared; 6930 } 6931 6932 if (OldImportAttr && !HasNewAttr && 6933 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember && 6934 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 6935 if (IsMicrosoftABI && IsDefinition) { 6936 S.Diag(NewDecl->getLocation(), 6937 diag::warn_redeclaration_without_import_attribute) 6938 << NewDecl; 6939 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6940 NewDecl->dropAttr<DLLImportAttr>(); 6941 NewDecl->addAttr( 6942 DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange())); 6943 } else { 6944 S.Diag(NewDecl->getLocation(), 6945 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 6946 << NewDecl << OldImportAttr; 6947 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6948 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 6949 OldDecl->dropAttr<DLLImportAttr>(); 6950 NewDecl->dropAttr<DLLImportAttr>(); 6951 } 6952 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) { 6953 // In MinGW, seeing a function declared inline drops the dllimport 6954 // attribute. 6955 OldDecl->dropAttr<DLLImportAttr>(); 6956 NewDecl->dropAttr<DLLImportAttr>(); 6957 S.Diag(NewDecl->getLocation(), 6958 diag::warn_dllimport_dropped_from_inline_function) 6959 << NewDecl << OldImportAttr; 6960 } 6961 6962 // A specialization of a class template member function is processed here 6963 // since it's a redeclaration. If the parent class is dllexport, the 6964 // specialization inherits that attribute. This doesn't happen automatically 6965 // since the parent class isn't instantiated until later. 6966 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) { 6967 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && 6968 !NewImportAttr && !NewExportAttr) { 6969 if (const DLLExportAttr *ParentExportAttr = 6970 MD->getParent()->getAttr<DLLExportAttr>()) { 6971 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context); 6972 NewAttr->setInherited(true); 6973 NewDecl->addAttr(NewAttr); 6974 } 6975 } 6976 } 6977 } 6978 6979 /// Given that we are within the definition of the given function, 6980 /// will that definition behave like C99's 'inline', where the 6981 /// definition is discarded except for optimization purposes? 6982 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 6983 // Try to avoid calling GetGVALinkageForFunction. 6984 6985 // All cases of this require the 'inline' keyword. 6986 if (!FD->isInlined()) return false; 6987 6988 // This is only possible in C++ with the gnu_inline attribute. 6989 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 6990 return false; 6991 6992 // Okay, go ahead and call the relatively-more-expensive function. 6993 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 6994 } 6995 6996 /// Determine whether a variable is extern "C" prior to attaching 6997 /// an initializer. We can't just call isExternC() here, because that 6998 /// will also compute and cache whether the declaration is externally 6999 /// visible, which might change when we attach the initializer. 7000 /// 7001 /// This can only be used if the declaration is known to not be a 7002 /// redeclaration of an internal linkage declaration. 7003 /// 7004 /// For instance: 7005 /// 7006 /// auto x = []{}; 7007 /// 7008 /// Attaching the initializer here makes this declaration not externally 7009 /// visible, because its type has internal linkage. 7010 /// 7011 /// FIXME: This is a hack. 7012 template<typename T> 7013 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 7014 if (S.getLangOpts().CPlusPlus) { 7015 // In C++, the overloadable attribute negates the effects of extern "C". 7016 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 7017 return false; 7018 7019 // So do CUDA's host/device attributes. 7020 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 7021 D->template hasAttr<CUDAHostAttr>())) 7022 return false; 7023 } 7024 return D->isExternC(); 7025 } 7026 7027 static bool shouldConsiderLinkage(const VarDecl *VD) { 7028 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 7029 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) || 7030 isa<OMPDeclareMapperDecl>(DC)) 7031 return VD->hasExternalStorage(); 7032 if (DC->isFileContext()) 7033 return true; 7034 if (DC->isRecord()) 7035 return false; 7036 if (isa<RequiresExprBodyDecl>(DC)) 7037 return false; 7038 llvm_unreachable("Unexpected context"); 7039 } 7040 7041 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 7042 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 7043 if (DC->isFileContext() || DC->isFunctionOrMethod() || 7044 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC)) 7045 return true; 7046 if (DC->isRecord()) 7047 return false; 7048 llvm_unreachable("Unexpected context"); 7049 } 7050 7051 static bool hasParsedAttr(Scope *S, const Declarator &PD, 7052 ParsedAttr::Kind Kind) { 7053 // Check decl attributes on the DeclSpec. 7054 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind)) 7055 return true; 7056 7057 // Walk the declarator structure, checking decl attributes that were in a type 7058 // position to the decl itself. 7059 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 7060 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind)) 7061 return true; 7062 } 7063 7064 // Finally, check attributes on the decl itself. 7065 return PD.getAttributes().hasAttribute(Kind) || 7066 PD.getDeclarationAttributes().hasAttribute(Kind); 7067 } 7068 7069 /// Adjust the \c DeclContext for a function or variable that might be a 7070 /// function-local external declaration. 7071 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 7072 if (!DC->isFunctionOrMethod()) 7073 return false; 7074 7075 // If this is a local extern function or variable declared within a function 7076 // template, don't add it into the enclosing namespace scope until it is 7077 // instantiated; it might have a dependent type right now. 7078 if (DC->isDependentContext()) 7079 return true; 7080 7081 // C++11 [basic.link]p7: 7082 // When a block scope declaration of an entity with linkage is not found to 7083 // refer to some other declaration, then that entity is a member of the 7084 // innermost enclosing namespace. 7085 // 7086 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 7087 // semantically-enclosing namespace, not a lexically-enclosing one. 7088 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 7089 DC = DC->getParent(); 7090 return true; 7091 } 7092 7093 /// Returns true if given declaration has external C language linkage. 7094 static bool isDeclExternC(const Decl *D) { 7095 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 7096 return FD->isExternC(); 7097 if (const auto *VD = dyn_cast<VarDecl>(D)) 7098 return VD->isExternC(); 7099 7100 llvm_unreachable("Unknown type of decl!"); 7101 } 7102 7103 /// Returns true if there hasn't been any invalid type diagnosed. 7104 static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) { 7105 DeclContext *DC = NewVD->getDeclContext(); 7106 QualType R = NewVD->getType(); 7107 7108 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 7109 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 7110 // argument. 7111 if (R->isImageType() || R->isPipeType()) { 7112 Se.Diag(NewVD->getLocation(), 7113 diag::err_opencl_type_can_only_be_used_as_function_parameter) 7114 << R; 7115 NewVD->setInvalidDecl(); 7116 return false; 7117 } 7118 7119 // OpenCL v1.2 s6.9.r: 7120 // The event type cannot be used to declare a program scope variable. 7121 // OpenCL v2.0 s6.9.q: 7122 // The clk_event_t and reserve_id_t types cannot be declared in program 7123 // scope. 7124 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) { 7125 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 7126 Se.Diag(NewVD->getLocation(), 7127 diag::err_invalid_type_for_program_scope_var) 7128 << R; 7129 NewVD->setInvalidDecl(); 7130 return false; 7131 } 7132 } 7133 7134 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 7135 if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers", 7136 Se.getLangOpts())) { 7137 QualType NR = R.getCanonicalType(); 7138 while (NR->isPointerType() || NR->isMemberFunctionPointerType() || 7139 NR->isReferenceType()) { 7140 if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() || 7141 NR->isFunctionReferenceType()) { 7142 Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer) 7143 << NR->isReferenceType(); 7144 NewVD->setInvalidDecl(); 7145 return false; 7146 } 7147 NR = NR->getPointeeType(); 7148 } 7149 } 7150 7151 if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16", 7152 Se.getLangOpts())) { 7153 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 7154 // half array type (unless the cl_khr_fp16 extension is enabled). 7155 if (Se.Context.getBaseElementType(R)->isHalfType()) { 7156 Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R; 7157 NewVD->setInvalidDecl(); 7158 return false; 7159 } 7160 } 7161 7162 // OpenCL v1.2 s6.9.r: 7163 // The event type cannot be used with the __local, __constant and __global 7164 // address space qualifiers. 7165 if (R->isEventT()) { 7166 if (R.getAddressSpace() != LangAS::opencl_private) { 7167 Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual); 7168 NewVD->setInvalidDecl(); 7169 return false; 7170 } 7171 } 7172 7173 if (R->isSamplerT()) { 7174 // OpenCL v1.2 s6.9.b p4: 7175 // The sampler type cannot be used with the __local and __global address 7176 // space qualifiers. 7177 if (R.getAddressSpace() == LangAS::opencl_local || 7178 R.getAddressSpace() == LangAS::opencl_global) { 7179 Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace); 7180 NewVD->setInvalidDecl(); 7181 } 7182 7183 // OpenCL v1.2 s6.12.14.1: 7184 // A global sampler must be declared with either the constant address 7185 // space qualifier or with the const qualifier. 7186 if (DC->isTranslationUnit() && 7187 !(R.getAddressSpace() == LangAS::opencl_constant || 7188 R.isConstQualified())) { 7189 Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler); 7190 NewVD->setInvalidDecl(); 7191 } 7192 if (NewVD->isInvalidDecl()) 7193 return false; 7194 } 7195 7196 return true; 7197 } 7198 7199 template <typename AttrTy> 7200 static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) { 7201 const TypedefNameDecl *TND = TT->getDecl(); 7202 if (const auto *Attribute = TND->getAttr<AttrTy>()) { 7203 AttrTy *Clone = Attribute->clone(S.Context); 7204 Clone->setInherited(true); 7205 D->addAttr(Clone); 7206 } 7207 } 7208 7209 NamedDecl *Sema::ActOnVariableDeclarator( 7210 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 7211 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 7212 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 7213 QualType R = TInfo->getType(); 7214 DeclarationName Name = GetNameForDeclarator(D).getName(); 7215 7216 IdentifierInfo *II = Name.getAsIdentifierInfo(); 7217 7218 if (D.isDecompositionDeclarator()) { 7219 // Take the name of the first declarator as our name for diagnostic 7220 // purposes. 7221 auto &Decomp = D.getDecompositionDeclarator(); 7222 if (!Decomp.bindings().empty()) { 7223 II = Decomp.bindings()[0].Name; 7224 Name = II; 7225 } 7226 } else if (!II) { 7227 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; 7228 return nullptr; 7229 } 7230 7231 7232 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 7233 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 7234 7235 // dllimport globals without explicit storage class are treated as extern. We 7236 // have to change the storage class this early to get the right DeclContext. 7237 if (SC == SC_None && !DC->isRecord() && 7238 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) && 7239 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport)) 7240 SC = SC_Extern; 7241 7242 DeclContext *OriginalDC = DC; 7243 bool IsLocalExternDecl = SC == SC_Extern && 7244 adjustContextForLocalExternDecl(DC); 7245 7246 if (SCSpec == DeclSpec::SCS_mutable) { 7247 // mutable can only appear on non-static class members, so it's always 7248 // an error here 7249 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 7250 D.setInvalidType(); 7251 SC = SC_None; 7252 } 7253 7254 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 7255 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 7256 D.getDeclSpec().getStorageClassSpecLoc())) { 7257 // In C++11, the 'register' storage class specifier is deprecated. 7258 // Suppress the warning in system macros, it's used in macros in some 7259 // popular C system headers, such as in glibc's htonl() macro. 7260 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7261 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 7262 : diag::warn_deprecated_register) 7263 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7264 } 7265 7266 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 7267 7268 if (!DC->isRecord() && S->getFnParent() == nullptr) { 7269 // C99 6.9p2: The storage-class specifiers auto and register shall not 7270 // appear in the declaration specifiers in an external declaration. 7271 // Global Register+Asm is a GNU extension we support. 7272 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 7273 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 7274 D.setInvalidType(); 7275 } 7276 } 7277 7278 // If this variable has a VLA type and an initializer, try to 7279 // fold to a constant-sized type. This is otherwise invalid. 7280 if (D.hasInitializer() && R->isVariableArrayType()) 7281 tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(), 7282 /*DiagID=*/0); 7283 7284 bool IsMemberSpecialization = false; 7285 bool IsVariableTemplateSpecialization = false; 7286 bool IsPartialSpecialization = false; 7287 bool IsVariableTemplate = false; 7288 VarDecl *NewVD = nullptr; 7289 VarTemplateDecl *NewTemplate = nullptr; 7290 TemplateParameterList *TemplateParams = nullptr; 7291 if (!getLangOpts().CPlusPlus) { 7292 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), 7293 II, R, TInfo, SC); 7294 7295 if (R->getContainedDeducedType()) 7296 ParsingInitForAutoVars.insert(NewVD); 7297 7298 if (D.isInvalidType()) 7299 NewVD->setInvalidDecl(); 7300 7301 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() && 7302 NewVD->hasLocalStorage()) 7303 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(), 7304 NTCUC_AutoVar, NTCUK_Destruct); 7305 } else { 7306 bool Invalid = false; 7307 7308 if (DC->isRecord() && !CurContext->isRecord()) { 7309 // This is an out-of-line definition of a static data member. 7310 switch (SC) { 7311 case SC_None: 7312 break; 7313 case SC_Static: 7314 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7315 diag::err_static_out_of_line) 7316 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7317 break; 7318 case SC_Auto: 7319 case SC_Register: 7320 case SC_Extern: 7321 // [dcl.stc] p2: The auto or register specifiers shall be applied only 7322 // to names of variables declared in a block or to function parameters. 7323 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 7324 // of class members 7325 7326 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7327 diag::err_storage_class_for_static_member) 7328 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7329 break; 7330 case SC_PrivateExtern: 7331 llvm_unreachable("C storage class in c++!"); 7332 } 7333 } 7334 7335 if (SC == SC_Static && CurContext->isRecord()) { 7336 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 7337 // Walk up the enclosing DeclContexts to check for any that are 7338 // incompatible with static data members. 7339 const DeclContext *FunctionOrMethod = nullptr; 7340 const CXXRecordDecl *AnonStruct = nullptr; 7341 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) { 7342 if (Ctxt->isFunctionOrMethod()) { 7343 FunctionOrMethod = Ctxt; 7344 break; 7345 } 7346 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt); 7347 if (ParentDecl && !ParentDecl->getDeclName()) { 7348 AnonStruct = ParentDecl; 7349 break; 7350 } 7351 } 7352 if (FunctionOrMethod) { 7353 // C++ [class.static.data]p5: A local class shall not have static data 7354 // members. 7355 Diag(D.getIdentifierLoc(), 7356 diag::err_static_data_member_not_allowed_in_local_class) 7357 << Name << RD->getDeclName() << RD->getTagKind(); 7358 } else if (AnonStruct) { 7359 // C++ [class.static.data]p4: Unnamed classes and classes contained 7360 // directly or indirectly within unnamed classes shall not contain 7361 // static data members. 7362 Diag(D.getIdentifierLoc(), 7363 diag::err_static_data_member_not_allowed_in_anon_struct) 7364 << Name << AnonStruct->getTagKind(); 7365 Invalid = true; 7366 } else if (RD->isUnion()) { 7367 // C++98 [class.union]p1: If a union contains a static data member, 7368 // the program is ill-formed. C++11 drops this restriction. 7369 Diag(D.getIdentifierLoc(), 7370 getLangOpts().CPlusPlus11 7371 ? diag::warn_cxx98_compat_static_data_member_in_union 7372 : diag::ext_static_data_member_in_union) << Name; 7373 } 7374 } 7375 } 7376 7377 // Match up the template parameter lists with the scope specifier, then 7378 // determine whether we have a template or a template specialization. 7379 bool InvalidScope = false; 7380 TemplateParams = MatchTemplateParametersToScopeSpecifier( 7381 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 7382 D.getCXXScopeSpec(), 7383 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 7384 ? D.getName().TemplateId 7385 : nullptr, 7386 TemplateParamLists, 7387 /*never a friend*/ false, IsMemberSpecialization, InvalidScope); 7388 Invalid |= InvalidScope; 7389 7390 if (TemplateParams) { 7391 if (!TemplateParams->size() && 7392 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 7393 // There is an extraneous 'template<>' for this variable. Complain 7394 // about it, but allow the declaration of the variable. 7395 Diag(TemplateParams->getTemplateLoc(), 7396 diag::err_template_variable_noparams) 7397 << II 7398 << SourceRange(TemplateParams->getTemplateLoc(), 7399 TemplateParams->getRAngleLoc()); 7400 TemplateParams = nullptr; 7401 } else { 7402 // Check that we can declare a template here. 7403 if (CheckTemplateDeclScope(S, TemplateParams)) 7404 return nullptr; 7405 7406 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 7407 // This is an explicit specialization or a partial specialization. 7408 IsVariableTemplateSpecialization = true; 7409 IsPartialSpecialization = TemplateParams->size() > 0; 7410 } else { // if (TemplateParams->size() > 0) 7411 // This is a template declaration. 7412 IsVariableTemplate = true; 7413 7414 // Only C++1y supports variable templates (N3651). 7415 Diag(D.getIdentifierLoc(), 7416 getLangOpts().CPlusPlus14 7417 ? diag::warn_cxx11_compat_variable_template 7418 : diag::ext_variable_template); 7419 } 7420 } 7421 } else { 7422 // Check that we can declare a member specialization here. 7423 if (!TemplateParamLists.empty() && IsMemberSpecialization && 7424 CheckTemplateDeclScope(S, TemplateParamLists.back())) 7425 return nullptr; 7426 assert((Invalid || 7427 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && 7428 "should have a 'template<>' for this decl"); 7429 } 7430 7431 if (IsVariableTemplateSpecialization) { 7432 SourceLocation TemplateKWLoc = 7433 TemplateParamLists.size() > 0 7434 ? TemplateParamLists[0]->getTemplateLoc() 7435 : SourceLocation(); 7436 DeclResult Res = ActOnVarTemplateSpecialization( 7437 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 7438 IsPartialSpecialization); 7439 if (Res.isInvalid()) 7440 return nullptr; 7441 NewVD = cast<VarDecl>(Res.get()); 7442 AddToScope = false; 7443 } else if (D.isDecompositionDeclarator()) { 7444 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(), 7445 D.getIdentifierLoc(), R, TInfo, SC, 7446 Bindings); 7447 } else 7448 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), 7449 D.getIdentifierLoc(), II, R, TInfo, SC); 7450 7451 // If this is supposed to be a variable template, create it as such. 7452 if (IsVariableTemplate) { 7453 NewTemplate = 7454 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 7455 TemplateParams, NewVD); 7456 NewVD->setDescribedVarTemplate(NewTemplate); 7457 } 7458 7459 // If this decl has an auto type in need of deduction, make a note of the 7460 // Decl so we can diagnose uses of it in its own initializer. 7461 if (R->getContainedDeducedType()) 7462 ParsingInitForAutoVars.insert(NewVD); 7463 7464 if (D.isInvalidType() || Invalid) { 7465 NewVD->setInvalidDecl(); 7466 if (NewTemplate) 7467 NewTemplate->setInvalidDecl(); 7468 } 7469 7470 SetNestedNameSpecifier(*this, NewVD, D); 7471 7472 // If we have any template parameter lists that don't directly belong to 7473 // the variable (matching the scope specifier), store them. 7474 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 7475 if (TemplateParamLists.size() > VDTemplateParamLists) 7476 NewVD->setTemplateParameterListsInfo( 7477 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 7478 } 7479 7480 if (D.getDeclSpec().isInlineSpecified()) { 7481 if (!getLangOpts().CPlusPlus) { 7482 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 7483 << 0; 7484 } else if (CurContext->isFunctionOrMethod()) { 7485 // 'inline' is not allowed on block scope variable declaration. 7486 Diag(D.getDeclSpec().getInlineSpecLoc(), 7487 diag::err_inline_declaration_block_scope) << Name 7488 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 7489 } else { 7490 Diag(D.getDeclSpec().getInlineSpecLoc(), 7491 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable 7492 : diag::ext_inline_variable); 7493 NewVD->setInlineSpecified(); 7494 } 7495 } 7496 7497 // Set the lexical context. If the declarator has a C++ scope specifier, the 7498 // lexical context will be different from the semantic context. 7499 NewVD->setLexicalDeclContext(CurContext); 7500 if (NewTemplate) 7501 NewTemplate->setLexicalDeclContext(CurContext); 7502 7503 if (IsLocalExternDecl) { 7504 if (D.isDecompositionDeclarator()) 7505 for (auto *B : Bindings) 7506 B->setLocalExternDecl(); 7507 else 7508 NewVD->setLocalExternDecl(); 7509 } 7510 7511 bool EmitTLSUnsupportedError = false; 7512 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 7513 // C++11 [dcl.stc]p4: 7514 // When thread_local is applied to a variable of block scope the 7515 // storage-class-specifier static is implied if it does not appear 7516 // explicitly. 7517 // Core issue: 'static' is not implied if the variable is declared 7518 // 'extern'. 7519 if (NewVD->hasLocalStorage() && 7520 (SCSpec != DeclSpec::SCS_unspecified || 7521 TSCS != DeclSpec::TSCS_thread_local || 7522 !DC->isFunctionOrMethod())) 7523 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7524 diag::err_thread_non_global) 7525 << DeclSpec::getSpecifierName(TSCS); 7526 else if (!Context.getTargetInfo().isTLSSupported()) { 7527 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || 7528 getLangOpts().SYCLIsDevice) { 7529 // Postpone error emission until we've collected attributes required to 7530 // figure out whether it's a host or device variable and whether the 7531 // error should be ignored. 7532 EmitTLSUnsupportedError = true; 7533 // We still need to mark the variable as TLS so it shows up in AST with 7534 // proper storage class for other tools to use even if we're not going 7535 // to emit any code for it. 7536 NewVD->setTSCSpec(TSCS); 7537 } else 7538 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7539 diag::err_thread_unsupported); 7540 } else 7541 NewVD->setTSCSpec(TSCS); 7542 } 7543 7544 switch (D.getDeclSpec().getConstexprSpecifier()) { 7545 case ConstexprSpecKind::Unspecified: 7546 break; 7547 7548 case ConstexprSpecKind::Consteval: 7549 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7550 diag::err_constexpr_wrong_decl_kind) 7551 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 7552 LLVM_FALLTHROUGH; 7553 7554 case ConstexprSpecKind::Constexpr: 7555 NewVD->setConstexpr(true); 7556 // C++1z [dcl.spec.constexpr]p1: 7557 // A static data member declared with the constexpr specifier is 7558 // implicitly an inline variable. 7559 if (NewVD->isStaticDataMember() && 7560 (getLangOpts().CPlusPlus17 || 7561 Context.getTargetInfo().getCXXABI().isMicrosoft())) 7562 NewVD->setImplicitlyInline(); 7563 break; 7564 7565 case ConstexprSpecKind::Constinit: 7566 if (!NewVD->hasGlobalStorage()) 7567 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7568 diag::err_constinit_local_variable); 7569 else 7570 NewVD->addAttr(ConstInitAttr::Create( 7571 Context, D.getDeclSpec().getConstexprSpecLoc(), 7572 AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit)); 7573 break; 7574 } 7575 7576 // C99 6.7.4p3 7577 // An inline definition of a function with external linkage shall 7578 // not contain a definition of a modifiable object with static or 7579 // thread storage duration... 7580 // We only apply this when the function is required to be defined 7581 // elsewhere, i.e. when the function is not 'extern inline'. Note 7582 // that a local variable with thread storage duration still has to 7583 // be marked 'static'. Also note that it's possible to get these 7584 // semantics in C++ using __attribute__((gnu_inline)). 7585 if (SC == SC_Static && S->getFnParent() != nullptr && 7586 !NewVD->getType().isConstQualified()) { 7587 FunctionDecl *CurFD = getCurFunctionDecl(); 7588 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 7589 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7590 diag::warn_static_local_in_extern_inline); 7591 MaybeSuggestAddingStaticToDecl(CurFD); 7592 } 7593 } 7594 7595 if (D.getDeclSpec().isModulePrivateSpecified()) { 7596 if (IsVariableTemplateSpecialization) 7597 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7598 << (IsPartialSpecialization ? 1 : 0) 7599 << FixItHint::CreateRemoval( 7600 D.getDeclSpec().getModulePrivateSpecLoc()); 7601 else if (IsMemberSpecialization) 7602 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7603 << 2 7604 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 7605 else if (NewVD->hasLocalStorage()) 7606 Diag(NewVD->getLocation(), diag::err_module_private_local) 7607 << 0 << NewVD 7608 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 7609 << FixItHint::CreateRemoval( 7610 D.getDeclSpec().getModulePrivateSpecLoc()); 7611 else { 7612 NewVD->setModulePrivate(); 7613 if (NewTemplate) 7614 NewTemplate->setModulePrivate(); 7615 for (auto *B : Bindings) 7616 B->setModulePrivate(); 7617 } 7618 } 7619 7620 if (getLangOpts().OpenCL) { 7621 deduceOpenCLAddressSpace(NewVD); 7622 7623 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec(); 7624 if (TSC != TSCS_unspecified) { 7625 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7626 diag::err_opencl_unknown_type_specifier) 7627 << getLangOpts().getOpenCLVersionString() 7628 << DeclSpec::getSpecifierName(TSC) << 1; 7629 NewVD->setInvalidDecl(); 7630 } 7631 } 7632 7633 // Handle attributes prior to checking for duplicates in MergeVarDecl 7634 ProcessDeclAttributes(S, NewVD, D); 7635 7636 // FIXME: This is probably the wrong location to be doing this and we should 7637 // probably be doing this for more attributes (especially for function 7638 // pointer attributes such as format, warn_unused_result, etc.). Ideally 7639 // the code to copy attributes would be generated by TableGen. 7640 if (R->isFunctionPointerType()) 7641 if (const auto *TT = R->getAs<TypedefType>()) 7642 copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT); 7643 7644 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || 7645 getLangOpts().SYCLIsDevice) { 7646 if (EmitTLSUnsupportedError && 7647 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || 7648 (getLangOpts().OpenMPIsDevice && 7649 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD)))) 7650 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7651 diag::err_thread_unsupported); 7652 7653 if (EmitTLSUnsupportedError && 7654 (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice))) 7655 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported); 7656 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 7657 // storage [duration]." 7658 if (SC == SC_None && S->getFnParent() != nullptr && 7659 (NewVD->hasAttr<CUDASharedAttr>() || 7660 NewVD->hasAttr<CUDAConstantAttr>())) { 7661 NewVD->setStorageClass(SC_Static); 7662 } 7663 } 7664 7665 // Ensure that dllimport globals without explicit storage class are treated as 7666 // extern. The storage class is set above using parsed attributes. Now we can 7667 // check the VarDecl itself. 7668 assert(!NewVD->hasAttr<DLLImportAttr>() || 7669 NewVD->getAttr<DLLImportAttr>()->isInherited() || 7670 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 7671 7672 // In auto-retain/release, infer strong retension for variables of 7673 // retainable type. 7674 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 7675 NewVD->setInvalidDecl(); 7676 7677 // Handle GNU asm-label extension (encoded as an attribute). 7678 if (Expr *E = (Expr*)D.getAsmLabel()) { 7679 // The parser guarantees this is a string. 7680 StringLiteral *SE = cast<StringLiteral>(E); 7681 StringRef Label = SE->getString(); 7682 if (S->getFnParent() != nullptr) { 7683 switch (SC) { 7684 case SC_None: 7685 case SC_Auto: 7686 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 7687 break; 7688 case SC_Register: 7689 // Local Named register 7690 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 7691 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 7692 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7693 break; 7694 case SC_Static: 7695 case SC_Extern: 7696 case SC_PrivateExtern: 7697 break; 7698 } 7699 } else if (SC == SC_Register) { 7700 // Global Named register 7701 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 7702 const auto &TI = Context.getTargetInfo(); 7703 bool HasSizeMismatch; 7704 7705 if (!TI.isValidGCCRegisterName(Label)) 7706 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7707 else if (!TI.validateGlobalRegisterVariable(Label, 7708 Context.getTypeSize(R), 7709 HasSizeMismatch)) 7710 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 7711 else if (HasSizeMismatch) 7712 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 7713 } 7714 7715 if (!R->isIntegralType(Context) && !R->isPointerType()) { 7716 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type); 7717 NewVD->setInvalidDecl(true); 7718 } 7719 } 7720 7721 NewVD->addAttr(AsmLabelAttr::Create(Context, Label, 7722 /*IsLiteralLabel=*/true, 7723 SE->getStrTokenLoc(0))); 7724 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 7725 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 7726 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 7727 if (I != ExtnameUndeclaredIdentifiers.end()) { 7728 if (isDeclExternC(NewVD)) { 7729 NewVD->addAttr(I->second); 7730 ExtnameUndeclaredIdentifiers.erase(I); 7731 } else 7732 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 7733 << /*Variable*/1 << NewVD; 7734 } 7735 } 7736 7737 // Find the shadowed declaration before filtering for scope. 7738 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 7739 ? getShadowedDeclaration(NewVD, Previous) 7740 : nullptr; 7741 7742 // Don't consider existing declarations that are in a different 7743 // scope and are out-of-semantic-context declarations (if the new 7744 // declaration has linkage). 7745 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 7746 D.getCXXScopeSpec().isNotEmpty() || 7747 IsMemberSpecialization || 7748 IsVariableTemplateSpecialization); 7749 7750 // Check whether the previous declaration is in the same block scope. This 7751 // affects whether we merge types with it, per C++11 [dcl.array]p3. 7752 if (getLangOpts().CPlusPlus && 7753 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 7754 NewVD->setPreviousDeclInSameBlockScope( 7755 Previous.isSingleResult() && !Previous.isShadowed() && 7756 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 7757 7758 if (!getLangOpts().CPlusPlus) { 7759 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7760 } else { 7761 // If this is an explicit specialization of a static data member, check it. 7762 if (IsMemberSpecialization && !NewVD->isInvalidDecl() && 7763 CheckMemberSpecialization(NewVD, Previous)) 7764 NewVD->setInvalidDecl(); 7765 7766 // Merge the decl with the existing one if appropriate. 7767 if (!Previous.empty()) { 7768 if (Previous.isSingleResult() && 7769 isa<FieldDecl>(Previous.getFoundDecl()) && 7770 D.getCXXScopeSpec().isSet()) { 7771 // The user tried to define a non-static data member 7772 // out-of-line (C++ [dcl.meaning]p1). 7773 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 7774 << D.getCXXScopeSpec().getRange(); 7775 Previous.clear(); 7776 NewVD->setInvalidDecl(); 7777 } 7778 } else if (D.getCXXScopeSpec().isSet()) { 7779 // No previous declaration in the qualifying scope. 7780 Diag(D.getIdentifierLoc(), diag::err_no_member) 7781 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 7782 << D.getCXXScopeSpec().getRange(); 7783 NewVD->setInvalidDecl(); 7784 } 7785 7786 if (!IsVariableTemplateSpecialization) 7787 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7788 7789 if (NewTemplate) { 7790 VarTemplateDecl *PrevVarTemplate = 7791 NewVD->getPreviousDecl() 7792 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 7793 : nullptr; 7794 7795 // Check the template parameter list of this declaration, possibly 7796 // merging in the template parameter list from the previous variable 7797 // template declaration. 7798 if (CheckTemplateParameterList( 7799 TemplateParams, 7800 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 7801 : nullptr, 7802 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 7803 DC->isDependentContext()) 7804 ? TPC_ClassTemplateMember 7805 : TPC_VarTemplate)) 7806 NewVD->setInvalidDecl(); 7807 7808 // If we are providing an explicit specialization of a static variable 7809 // template, make a note of that. 7810 if (PrevVarTemplate && 7811 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 7812 PrevVarTemplate->setMemberSpecialization(); 7813 } 7814 } 7815 7816 // Diagnose shadowed variables iff this isn't a redeclaration. 7817 if (ShadowedDecl && !D.isRedeclaration()) 7818 CheckShadow(NewVD, ShadowedDecl, Previous); 7819 7820 ProcessPragmaWeak(S, NewVD); 7821 7822 // If this is the first declaration of an extern C variable, update 7823 // the map of such variables. 7824 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 7825 isIncompleteDeclExternC(*this, NewVD)) 7826 RegisterLocallyScopedExternCDecl(NewVD, S); 7827 7828 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 7829 MangleNumberingContext *MCtx; 7830 Decl *ManglingContextDecl; 7831 std::tie(MCtx, ManglingContextDecl) = 7832 getCurrentMangleNumberContext(NewVD->getDeclContext()); 7833 if (MCtx) { 7834 Context.setManglingNumber( 7835 NewVD, MCtx->getManglingNumber( 7836 NewVD, getMSManglingNumber(getLangOpts(), S))); 7837 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 7838 } 7839 } 7840 7841 // Special handling of variable named 'main'. 7842 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 7843 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 7844 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 7845 7846 // C++ [basic.start.main]p3 7847 // A program that declares a variable main at global scope is ill-formed. 7848 if (getLangOpts().CPlusPlus) 7849 Diag(D.getBeginLoc(), diag::err_main_global_variable); 7850 7851 // In C, and external-linkage variable named main results in undefined 7852 // behavior. 7853 else if (NewVD->hasExternalFormalLinkage()) 7854 Diag(D.getBeginLoc(), diag::warn_main_redefined); 7855 } 7856 7857 if (D.isRedeclaration() && !Previous.empty()) { 7858 NamedDecl *Prev = Previous.getRepresentativeDecl(); 7859 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization, 7860 D.isFunctionDefinition()); 7861 } 7862 7863 if (NewTemplate) { 7864 if (NewVD->isInvalidDecl()) 7865 NewTemplate->setInvalidDecl(); 7866 ActOnDocumentableDecl(NewTemplate); 7867 return NewTemplate; 7868 } 7869 7870 if (IsMemberSpecialization && !NewVD->isInvalidDecl()) 7871 CompleteMemberSpecialization(NewVD, Previous); 7872 7873 return NewVD; 7874 } 7875 7876 /// Enum describing the %select options in diag::warn_decl_shadow. 7877 enum ShadowedDeclKind { 7878 SDK_Local, 7879 SDK_Global, 7880 SDK_StaticMember, 7881 SDK_Field, 7882 SDK_Typedef, 7883 SDK_Using, 7884 SDK_StructuredBinding 7885 }; 7886 7887 /// Determine what kind of declaration we're shadowing. 7888 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 7889 const DeclContext *OldDC) { 7890 if (isa<TypeAliasDecl>(ShadowedDecl)) 7891 return SDK_Using; 7892 else if (isa<TypedefDecl>(ShadowedDecl)) 7893 return SDK_Typedef; 7894 else if (isa<BindingDecl>(ShadowedDecl)) 7895 return SDK_StructuredBinding; 7896 else if (isa<RecordDecl>(OldDC)) 7897 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 7898 7899 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 7900 } 7901 7902 /// Return the location of the capture if the given lambda captures the given 7903 /// variable \p VD, or an invalid source location otherwise. 7904 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 7905 const VarDecl *VD) { 7906 for (const Capture &Capture : LSI->Captures) { 7907 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 7908 return Capture.getLocation(); 7909 } 7910 return SourceLocation(); 7911 } 7912 7913 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, 7914 const LookupResult &R) { 7915 // Only diagnose if we're shadowing an unambiguous field or variable. 7916 if (R.getResultKind() != LookupResult::Found) 7917 return false; 7918 7919 // Return false if warning is ignored. 7920 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); 7921 } 7922 7923 /// Return the declaration shadowed by the given variable \p D, or null 7924 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7925 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 7926 const LookupResult &R) { 7927 if (!shouldWarnIfShadowedDecl(Diags, R)) 7928 return nullptr; 7929 7930 // Don't diagnose declarations at file scope. 7931 if (D->hasGlobalStorage()) 7932 return nullptr; 7933 7934 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7935 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl 7936 : nullptr; 7937 } 7938 7939 /// Return the declaration shadowed by the given typedef \p D, or null 7940 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7941 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, 7942 const LookupResult &R) { 7943 // Don't warn if typedef declaration is part of a class 7944 if (D->getDeclContext()->isRecord()) 7945 return nullptr; 7946 7947 if (!shouldWarnIfShadowedDecl(Diags, R)) 7948 return nullptr; 7949 7950 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7951 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; 7952 } 7953 7954 /// Return the declaration shadowed by the given variable \p D, or null 7955 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7956 NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D, 7957 const LookupResult &R) { 7958 if (!shouldWarnIfShadowedDecl(Diags, R)) 7959 return nullptr; 7960 7961 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7962 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl 7963 : nullptr; 7964 } 7965 7966 /// Diagnose variable or built-in function shadowing. Implements 7967 /// -Wshadow. 7968 /// 7969 /// This method is called whenever a VarDecl is added to a "useful" 7970 /// scope. 7971 /// 7972 /// \param ShadowedDecl the declaration that is shadowed by the given variable 7973 /// \param R the lookup of the name 7974 /// 7975 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 7976 const LookupResult &R) { 7977 DeclContext *NewDC = D->getDeclContext(); 7978 7979 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 7980 // Fields are not shadowed by variables in C++ static methods. 7981 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 7982 if (MD->isStatic()) 7983 return; 7984 7985 // Fields shadowed by constructor parameters are a special case. Usually 7986 // the constructor initializes the field with the parameter. 7987 if (isa<CXXConstructorDecl>(NewDC)) 7988 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { 7989 // Remember that this was shadowed so we can either warn about its 7990 // modification or its existence depending on warning settings. 7991 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); 7992 return; 7993 } 7994 } 7995 7996 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 7997 if (shadowedVar->isExternC()) { 7998 // For shadowing external vars, make sure that we point to the global 7999 // declaration, not a locally scoped extern declaration. 8000 for (auto I : shadowedVar->redecls()) 8001 if (I->isFileVarDecl()) { 8002 ShadowedDecl = I; 8003 break; 8004 } 8005 } 8006 8007 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); 8008 8009 unsigned WarningDiag = diag::warn_decl_shadow; 8010 SourceLocation CaptureLoc; 8011 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && 8012 isa<CXXMethodDecl>(NewDC)) { 8013 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 8014 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 8015 if (RD->getLambdaCaptureDefault() == LCD_None) { 8016 // Try to avoid warnings for lambdas with an explicit capture list. 8017 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 8018 // Warn only when the lambda captures the shadowed decl explicitly. 8019 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 8020 if (CaptureLoc.isInvalid()) 8021 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 8022 } else { 8023 // Remember that this was shadowed so we can avoid the warning if the 8024 // shadowed decl isn't captured and the warning settings allow it. 8025 cast<LambdaScopeInfo>(getCurFunction()) 8026 ->ShadowingDecls.push_back( 8027 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); 8028 return; 8029 } 8030 } 8031 8032 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { 8033 // A variable can't shadow a local variable in an enclosing scope, if 8034 // they are separated by a non-capturing declaration context. 8035 for (DeclContext *ParentDC = NewDC; 8036 ParentDC && !ParentDC->Equals(OldDC); 8037 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { 8038 // Only block literals, captured statements, and lambda expressions 8039 // can capture; other scopes don't. 8040 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && 8041 !isLambdaCallOperator(ParentDC)) { 8042 return; 8043 } 8044 } 8045 } 8046 } 8047 } 8048 8049 // Only warn about certain kinds of shadowing for class members. 8050 if (NewDC && NewDC->isRecord()) { 8051 // In particular, don't warn about shadowing non-class members. 8052 if (!OldDC->isRecord()) 8053 return; 8054 8055 // TODO: should we warn about static data members shadowing 8056 // static data members from base classes? 8057 8058 // TODO: don't diagnose for inaccessible shadowed members. 8059 // This is hard to do perfectly because we might friend the 8060 // shadowing context, but that's just a false negative. 8061 } 8062 8063 8064 DeclarationName Name = R.getLookupName(); 8065 8066 // Emit warning and note. 8067 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 8068 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 8069 if (!CaptureLoc.isInvalid()) 8070 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 8071 << Name << /*explicitly*/ 1; 8072 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 8073 } 8074 8075 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 8076 /// when these variables are captured by the lambda. 8077 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 8078 for (const auto &Shadow : LSI->ShadowingDecls) { 8079 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 8080 // Try to avoid the warning when the shadowed decl isn't captured. 8081 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 8082 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 8083 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 8084 ? diag::warn_decl_shadow_uncaptured_local 8085 : diag::warn_decl_shadow) 8086 << Shadow.VD->getDeclName() 8087 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 8088 if (!CaptureLoc.isInvalid()) 8089 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 8090 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 8091 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 8092 } 8093 } 8094 8095 /// Check -Wshadow without the advantage of a previous lookup. 8096 void Sema::CheckShadow(Scope *S, VarDecl *D) { 8097 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 8098 return; 8099 8100 LookupResult R(*this, D->getDeclName(), D->getLocation(), 8101 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); 8102 LookupName(R, S); 8103 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 8104 CheckShadow(D, ShadowedDecl, R); 8105 } 8106 8107 /// Check if 'E', which is an expression that is about to be modified, refers 8108 /// to a constructor parameter that shadows a field. 8109 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 8110 // Quickly ignore expressions that can't be shadowing ctor parameters. 8111 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 8112 return; 8113 E = E->IgnoreParenImpCasts(); 8114 auto *DRE = dyn_cast<DeclRefExpr>(E); 8115 if (!DRE) 8116 return; 8117 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 8118 auto I = ShadowingDecls.find(D); 8119 if (I == ShadowingDecls.end()) 8120 return; 8121 const NamedDecl *ShadowedDecl = I->second; 8122 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 8123 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 8124 Diag(D->getLocation(), diag::note_var_declared_here) << D; 8125 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 8126 8127 // Avoid issuing multiple warnings about the same decl. 8128 ShadowingDecls.erase(I); 8129 } 8130 8131 /// Check for conflict between this global or extern "C" declaration and 8132 /// previous global or extern "C" declarations. This is only used in C++. 8133 template<typename T> 8134 static bool checkGlobalOrExternCConflict( 8135 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 8136 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 8137 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 8138 8139 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 8140 // The common case: this global doesn't conflict with any extern "C" 8141 // declaration. 8142 return false; 8143 } 8144 8145 if (Prev) { 8146 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 8147 // Both the old and new declarations have C language linkage. This is a 8148 // redeclaration. 8149 Previous.clear(); 8150 Previous.addDecl(Prev); 8151 return true; 8152 } 8153 8154 // This is a global, non-extern "C" declaration, and there is a previous 8155 // non-global extern "C" declaration. Diagnose if this is a variable 8156 // declaration. 8157 if (!isa<VarDecl>(ND)) 8158 return false; 8159 } else { 8160 // The declaration is extern "C". Check for any declaration in the 8161 // translation unit which might conflict. 8162 if (IsGlobal) { 8163 // We have already performed the lookup into the translation unit. 8164 IsGlobal = false; 8165 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 8166 I != E; ++I) { 8167 if (isa<VarDecl>(*I)) { 8168 Prev = *I; 8169 break; 8170 } 8171 } 8172 } else { 8173 DeclContext::lookup_result R = 8174 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 8175 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 8176 I != E; ++I) { 8177 if (isa<VarDecl>(*I)) { 8178 Prev = *I; 8179 break; 8180 } 8181 // FIXME: If we have any other entity with this name in global scope, 8182 // the declaration is ill-formed, but that is a defect: it breaks the 8183 // 'stat' hack, for instance. Only variables can have mangled name 8184 // clashes with extern "C" declarations, so only they deserve a 8185 // diagnostic. 8186 } 8187 } 8188 8189 if (!Prev) 8190 return false; 8191 } 8192 8193 // Use the first declaration's location to ensure we point at something which 8194 // is lexically inside an extern "C" linkage-spec. 8195 assert(Prev && "should have found a previous declaration to diagnose"); 8196 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 8197 Prev = FD->getFirstDecl(); 8198 else 8199 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 8200 8201 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 8202 << IsGlobal << ND; 8203 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 8204 << IsGlobal; 8205 return false; 8206 } 8207 8208 /// Apply special rules for handling extern "C" declarations. Returns \c true 8209 /// if we have found that this is a redeclaration of some prior entity. 8210 /// 8211 /// Per C++ [dcl.link]p6: 8212 /// Two declarations [for a function or variable] with C language linkage 8213 /// with the same name that appear in different scopes refer to the same 8214 /// [entity]. An entity with C language linkage shall not be declared with 8215 /// the same name as an entity in global scope. 8216 template<typename T> 8217 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 8218 LookupResult &Previous) { 8219 if (!S.getLangOpts().CPlusPlus) { 8220 // In C, when declaring a global variable, look for a corresponding 'extern' 8221 // variable declared in function scope. We don't need this in C++, because 8222 // we find local extern decls in the surrounding file-scope DeclContext. 8223 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 8224 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 8225 Previous.clear(); 8226 Previous.addDecl(Prev); 8227 return true; 8228 } 8229 } 8230 return false; 8231 } 8232 8233 // A declaration in the translation unit can conflict with an extern "C" 8234 // declaration. 8235 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 8236 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 8237 8238 // An extern "C" declaration can conflict with a declaration in the 8239 // translation unit or can be a redeclaration of an extern "C" declaration 8240 // in another scope. 8241 if (isIncompleteDeclExternC(S,ND)) 8242 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 8243 8244 // Neither global nor extern "C": nothing to do. 8245 return false; 8246 } 8247 8248 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 8249 // If the decl is already known invalid, don't check it. 8250 if (NewVD->isInvalidDecl()) 8251 return; 8252 8253 QualType T = NewVD->getType(); 8254 8255 // Defer checking an 'auto' type until its initializer is attached. 8256 if (T->isUndeducedType()) 8257 return; 8258 8259 if (NewVD->hasAttrs()) 8260 CheckAlignasUnderalignment(NewVD); 8261 8262 if (T->isObjCObjectType()) { 8263 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 8264 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 8265 T = Context.getObjCObjectPointerType(T); 8266 NewVD->setType(T); 8267 } 8268 8269 // Emit an error if an address space was applied to decl with local storage. 8270 // This includes arrays of objects with address space qualifiers, but not 8271 // automatic variables that point to other address spaces. 8272 // ISO/IEC TR 18037 S5.1.2 8273 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && 8274 T.getAddressSpace() != LangAS::Default) { 8275 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; 8276 NewVD->setInvalidDecl(); 8277 return; 8278 } 8279 8280 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 8281 // scope. 8282 if (getLangOpts().OpenCLVersion == 120 && 8283 !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers", 8284 getLangOpts()) && 8285 NewVD->isStaticLocal()) { 8286 Diag(NewVD->getLocation(), diag::err_static_function_scope); 8287 NewVD->setInvalidDecl(); 8288 return; 8289 } 8290 8291 if (getLangOpts().OpenCL) { 8292 if (!diagnoseOpenCLTypes(*this, NewVD)) 8293 return; 8294 8295 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 8296 if (NewVD->hasAttr<BlocksAttr>()) { 8297 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 8298 return; 8299 } 8300 8301 if (T->isBlockPointerType()) { 8302 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 8303 // can't use 'extern' storage class. 8304 if (!T.isConstQualified()) { 8305 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 8306 << 0 /*const*/; 8307 NewVD->setInvalidDecl(); 8308 return; 8309 } 8310 if (NewVD->hasExternalStorage()) { 8311 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 8312 NewVD->setInvalidDecl(); 8313 return; 8314 } 8315 } 8316 8317 // FIXME: Adding local AS in C++ for OpenCL might make sense. 8318 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 8319 NewVD->hasExternalStorage()) { 8320 if (!T->isSamplerT() && !T->isDependentType() && 8321 !(T.getAddressSpace() == LangAS::opencl_constant || 8322 (T.getAddressSpace() == LangAS::opencl_global && 8323 getOpenCLOptions().areProgramScopeVariablesSupported( 8324 getLangOpts())))) { 8325 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 8326 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts())) 8327 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 8328 << Scope << "global or constant"; 8329 else 8330 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 8331 << Scope << "constant"; 8332 NewVD->setInvalidDecl(); 8333 return; 8334 } 8335 } else { 8336 if (T.getAddressSpace() == LangAS::opencl_global) { 8337 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 8338 << 1 /*is any function*/ << "global"; 8339 NewVD->setInvalidDecl(); 8340 return; 8341 } 8342 if (T.getAddressSpace() == LangAS::opencl_constant || 8343 T.getAddressSpace() == LangAS::opencl_local) { 8344 FunctionDecl *FD = getCurFunctionDecl(); 8345 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables 8346 // in functions. 8347 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 8348 if (T.getAddressSpace() == LangAS::opencl_constant) 8349 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 8350 << 0 /*non-kernel only*/ << "constant"; 8351 else 8352 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 8353 << 0 /*non-kernel only*/ << "local"; 8354 NewVD->setInvalidDecl(); 8355 return; 8356 } 8357 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be 8358 // in the outermost scope of a kernel function. 8359 if (FD && FD->hasAttr<OpenCLKernelAttr>()) { 8360 if (!getCurScope()->isFunctionScope()) { 8361 if (T.getAddressSpace() == LangAS::opencl_constant) 8362 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 8363 << "constant"; 8364 else 8365 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 8366 << "local"; 8367 NewVD->setInvalidDecl(); 8368 return; 8369 } 8370 } 8371 } else if (T.getAddressSpace() != LangAS::opencl_private && 8372 // If we are parsing a template we didn't deduce an addr 8373 // space yet. 8374 T.getAddressSpace() != LangAS::Default) { 8375 // Do not allow other address spaces on automatic variable. 8376 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; 8377 NewVD->setInvalidDecl(); 8378 return; 8379 } 8380 } 8381 } 8382 8383 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 8384 && !NewVD->hasAttr<BlocksAttr>()) { 8385 if (getLangOpts().getGC() != LangOptions::NonGC) 8386 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 8387 else { 8388 assert(!getLangOpts().ObjCAutoRefCount); 8389 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 8390 } 8391 } 8392 8393 bool isVM = T->isVariablyModifiedType(); 8394 if (isVM || NewVD->hasAttr<CleanupAttr>() || 8395 NewVD->hasAttr<BlocksAttr>()) 8396 setFunctionHasBranchProtectedScope(); 8397 8398 if ((isVM && NewVD->hasLinkage()) || 8399 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 8400 bool SizeIsNegative; 8401 llvm::APSInt Oversized; 8402 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 8403 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized); 8404 QualType FixedT; 8405 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType()) 8406 FixedT = FixedTInfo->getType(); 8407 else if (FixedTInfo) { 8408 // Type and type-as-written are canonically different. We need to fix up 8409 // both types separately. 8410 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 8411 Oversized); 8412 } 8413 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) { 8414 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 8415 // FIXME: This won't give the correct result for 8416 // int a[10][n]; 8417 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 8418 8419 if (NewVD->isFileVarDecl()) 8420 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 8421 << SizeRange; 8422 else if (NewVD->isStaticLocal()) 8423 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 8424 << SizeRange; 8425 else 8426 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 8427 << SizeRange; 8428 NewVD->setInvalidDecl(); 8429 return; 8430 } 8431 8432 if (!FixedTInfo) { 8433 if (NewVD->isFileVarDecl()) 8434 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 8435 else 8436 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 8437 NewVD->setInvalidDecl(); 8438 return; 8439 } 8440 8441 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant); 8442 NewVD->setType(FixedT); 8443 NewVD->setTypeSourceInfo(FixedTInfo); 8444 } 8445 8446 if (T->isVoidType()) { 8447 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 8448 // of objects and functions. 8449 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 8450 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 8451 << T; 8452 NewVD->setInvalidDecl(); 8453 return; 8454 } 8455 } 8456 8457 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 8458 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 8459 NewVD->setInvalidDecl(); 8460 return; 8461 } 8462 8463 if (!NewVD->hasLocalStorage() && T->isSizelessType()) { 8464 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T; 8465 NewVD->setInvalidDecl(); 8466 return; 8467 } 8468 8469 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 8470 Diag(NewVD->getLocation(), diag::err_block_on_vm); 8471 NewVD->setInvalidDecl(); 8472 return; 8473 } 8474 8475 if (NewVD->isConstexpr() && !T->isDependentType() && 8476 RequireLiteralType(NewVD->getLocation(), T, 8477 diag::err_constexpr_var_non_literal)) { 8478 NewVD->setInvalidDecl(); 8479 return; 8480 } 8481 8482 // PPC MMA non-pointer types are not allowed as non-local variable types. 8483 if (Context.getTargetInfo().getTriple().isPPC64() && 8484 !NewVD->isLocalVarDecl() && 8485 CheckPPCMMAType(T, NewVD->getLocation())) { 8486 NewVD->setInvalidDecl(); 8487 return; 8488 } 8489 } 8490 8491 /// Perform semantic checking on a newly-created variable 8492 /// declaration. 8493 /// 8494 /// This routine performs all of the type-checking required for a 8495 /// variable declaration once it has been built. It is used both to 8496 /// check variables after they have been parsed and their declarators 8497 /// have been translated into a declaration, and to check variables 8498 /// that have been instantiated from a template. 8499 /// 8500 /// Sets NewVD->isInvalidDecl() if an error was encountered. 8501 /// 8502 /// Returns true if the variable declaration is a redeclaration. 8503 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 8504 CheckVariableDeclarationType(NewVD); 8505 8506 // If the decl is already known invalid, don't check it. 8507 if (NewVD->isInvalidDecl()) 8508 return false; 8509 8510 // If we did not find anything by this name, look for a non-visible 8511 // extern "C" declaration with the same name. 8512 if (Previous.empty() && 8513 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 8514 Previous.setShadowed(); 8515 8516 if (!Previous.empty()) { 8517 MergeVarDecl(NewVD, Previous); 8518 return true; 8519 } 8520 return false; 8521 } 8522 8523 /// AddOverriddenMethods - See if a method overrides any in the base classes, 8524 /// and if so, check that it's a valid override and remember it. 8525 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 8526 llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden; 8527 8528 // Look for methods in base classes that this method might override. 8529 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false, 8530 /*DetectVirtual=*/false); 8531 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 8532 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl(); 8533 DeclarationName Name = MD->getDeclName(); 8534 8535 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8536 // We really want to find the base class destructor here. 8537 QualType T = Context.getTypeDeclType(BaseRecord); 8538 CanQualType CT = Context.getCanonicalType(T); 8539 Name = Context.DeclarationNames.getCXXDestructorName(CT); 8540 } 8541 8542 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) { 8543 CXXMethodDecl *BaseMD = 8544 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl()); 8545 if (!BaseMD || !BaseMD->isVirtual() || 8546 IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false, 8547 /*ConsiderCudaAttrs=*/true, 8548 // C++2a [class.virtual]p2 does not consider requires 8549 // clauses when overriding. 8550 /*ConsiderRequiresClauses=*/false)) 8551 continue; 8552 8553 if (Overridden.insert(BaseMD).second) { 8554 MD->addOverriddenMethod(BaseMD); 8555 CheckOverridingFunctionReturnType(MD, BaseMD); 8556 CheckOverridingFunctionAttributes(MD, BaseMD); 8557 CheckOverridingFunctionExceptionSpec(MD, BaseMD); 8558 CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD); 8559 } 8560 8561 // A method can only override one function from each base class. We 8562 // don't track indirectly overridden methods from bases of bases. 8563 return true; 8564 } 8565 8566 return false; 8567 }; 8568 8569 DC->lookupInBases(VisitBase, Paths); 8570 return !Overridden.empty(); 8571 } 8572 8573 namespace { 8574 // Struct for holding all of the extra arguments needed by 8575 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 8576 struct ActOnFDArgs { 8577 Scope *S; 8578 Declarator &D; 8579 MultiTemplateParamsArg TemplateParamLists; 8580 bool AddToScope; 8581 }; 8582 } // end anonymous namespace 8583 8584 namespace { 8585 8586 // Callback to only accept typo corrections that have a non-zero edit distance. 8587 // Also only accept corrections that have the same parent decl. 8588 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback { 8589 public: 8590 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 8591 CXXRecordDecl *Parent) 8592 : Context(Context), OriginalFD(TypoFD), 8593 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 8594 8595 bool ValidateCandidate(const TypoCorrection &candidate) override { 8596 if (candidate.getEditDistance() == 0) 8597 return false; 8598 8599 SmallVector<unsigned, 1> MismatchedParams; 8600 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 8601 CDeclEnd = candidate.end(); 8602 CDecl != CDeclEnd; ++CDecl) { 8603 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8604 8605 if (FD && !FD->hasBody() && 8606 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 8607 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 8608 CXXRecordDecl *Parent = MD->getParent(); 8609 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 8610 return true; 8611 } else if (!ExpectedParent) { 8612 return true; 8613 } 8614 } 8615 } 8616 8617 return false; 8618 } 8619 8620 std::unique_ptr<CorrectionCandidateCallback> clone() override { 8621 return std::make_unique<DifferentNameValidatorCCC>(*this); 8622 } 8623 8624 private: 8625 ASTContext &Context; 8626 FunctionDecl *OriginalFD; 8627 CXXRecordDecl *ExpectedParent; 8628 }; 8629 8630 } // end anonymous namespace 8631 8632 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { 8633 TypoCorrectedFunctionDefinitions.insert(F); 8634 } 8635 8636 /// Generate diagnostics for an invalid function redeclaration. 8637 /// 8638 /// This routine handles generating the diagnostic messages for an invalid 8639 /// function redeclaration, including finding possible similar declarations 8640 /// or performing typo correction if there are no previous declarations with 8641 /// the same name. 8642 /// 8643 /// Returns a NamedDecl iff typo correction was performed and substituting in 8644 /// the new declaration name does not cause new errors. 8645 static NamedDecl *DiagnoseInvalidRedeclaration( 8646 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 8647 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 8648 DeclarationName Name = NewFD->getDeclName(); 8649 DeclContext *NewDC = NewFD->getDeclContext(); 8650 SmallVector<unsigned, 1> MismatchedParams; 8651 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 8652 TypoCorrection Correction; 8653 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 8654 unsigned DiagMsg = 8655 IsLocalFriend ? diag::err_no_matching_local_friend : 8656 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match : 8657 diag::err_member_decl_does_not_match; 8658 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 8659 IsLocalFriend ? Sema::LookupLocalFriendName 8660 : Sema::LookupOrdinaryName, 8661 Sema::ForVisibleRedeclaration); 8662 8663 NewFD->setInvalidDecl(); 8664 if (IsLocalFriend) 8665 SemaRef.LookupName(Prev, S); 8666 else 8667 SemaRef.LookupQualifiedName(Prev, NewDC); 8668 assert(!Prev.isAmbiguous() && 8669 "Cannot have an ambiguity in previous-declaration lookup"); 8670 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 8671 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD, 8672 MD ? MD->getParent() : nullptr); 8673 if (!Prev.empty()) { 8674 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 8675 Func != FuncEnd; ++Func) { 8676 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 8677 if (FD && 8678 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8679 // Add 1 to the index so that 0 can mean the mismatch didn't 8680 // involve a parameter 8681 unsigned ParamNum = 8682 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 8683 NearMatches.push_back(std::make_pair(FD, ParamNum)); 8684 } 8685 } 8686 // If the qualified name lookup yielded nothing, try typo correction 8687 } else if ((Correction = SemaRef.CorrectTypo( 8688 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 8689 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery, 8690 IsLocalFriend ? nullptr : NewDC))) { 8691 // Set up everything for the call to ActOnFunctionDeclarator 8692 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 8693 ExtraArgs.D.getIdentifierLoc()); 8694 Previous.clear(); 8695 Previous.setLookupName(Correction.getCorrection()); 8696 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 8697 CDeclEnd = Correction.end(); 8698 CDecl != CDeclEnd; ++CDecl) { 8699 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8700 if (FD && !FD->hasBody() && 8701 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8702 Previous.addDecl(FD); 8703 } 8704 } 8705 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 8706 8707 NamedDecl *Result; 8708 // Retry building the function declaration with the new previous 8709 // declarations, and with errors suppressed. 8710 { 8711 // Trap errors. 8712 Sema::SFINAETrap Trap(SemaRef); 8713 8714 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 8715 // pieces need to verify the typo-corrected C++ declaration and hopefully 8716 // eliminate the need for the parameter pack ExtraArgs. 8717 Result = SemaRef.ActOnFunctionDeclarator( 8718 ExtraArgs.S, ExtraArgs.D, 8719 Correction.getCorrectionDecl()->getDeclContext(), 8720 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 8721 ExtraArgs.AddToScope); 8722 8723 if (Trap.hasErrorOccurred()) 8724 Result = nullptr; 8725 } 8726 8727 if (Result) { 8728 // Determine which correction we picked. 8729 Decl *Canonical = Result->getCanonicalDecl(); 8730 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 8731 I != E; ++I) 8732 if ((*I)->getCanonicalDecl() == Canonical) 8733 Correction.setCorrectionDecl(*I); 8734 8735 // Let Sema know about the correction. 8736 SemaRef.MarkTypoCorrectedFunctionDefinition(Result); 8737 SemaRef.diagnoseTypo( 8738 Correction, 8739 SemaRef.PDiag(IsLocalFriend 8740 ? diag::err_no_matching_local_friend_suggest 8741 : diag::err_member_decl_does_not_match_suggest) 8742 << Name << NewDC << IsDefinition); 8743 return Result; 8744 } 8745 8746 // Pretend the typo correction never occurred 8747 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 8748 ExtraArgs.D.getIdentifierLoc()); 8749 ExtraArgs.D.setRedeclaration(wasRedeclaration); 8750 Previous.clear(); 8751 Previous.setLookupName(Name); 8752 } 8753 8754 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 8755 << Name << NewDC << IsDefinition << NewFD->getLocation(); 8756 8757 bool NewFDisConst = false; 8758 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 8759 NewFDisConst = NewMD->isConst(); 8760 8761 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 8762 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 8763 NearMatch != NearMatchEnd; ++NearMatch) { 8764 FunctionDecl *FD = NearMatch->first; 8765 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 8766 bool FDisConst = MD && MD->isConst(); 8767 bool IsMember = MD || !IsLocalFriend; 8768 8769 // FIXME: These notes are poorly worded for the local friend case. 8770 if (unsigned Idx = NearMatch->second) { 8771 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 8772 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 8773 if (Loc.isInvalid()) Loc = FD->getLocation(); 8774 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 8775 : diag::note_local_decl_close_param_match) 8776 << Idx << FDParam->getType() 8777 << NewFD->getParamDecl(Idx - 1)->getType(); 8778 } else if (FDisConst != NewFDisConst) { 8779 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 8780 << NewFDisConst << FD->getSourceRange().getEnd() 8781 << (NewFDisConst 8782 ? FixItHint::CreateRemoval(ExtraArgs.D.getFunctionTypeInfo() 8783 .getConstQualifierLoc()) 8784 : FixItHint::CreateInsertion(ExtraArgs.D.getFunctionTypeInfo() 8785 .getRParenLoc() 8786 .getLocWithOffset(1), 8787 " const")); 8788 } else 8789 SemaRef.Diag(FD->getLocation(), 8790 IsMember ? diag::note_member_def_close_match 8791 : diag::note_local_decl_close_match); 8792 } 8793 return nullptr; 8794 } 8795 8796 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 8797 switch (D.getDeclSpec().getStorageClassSpec()) { 8798 default: llvm_unreachable("Unknown storage class!"); 8799 case DeclSpec::SCS_auto: 8800 case DeclSpec::SCS_register: 8801 case DeclSpec::SCS_mutable: 8802 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8803 diag::err_typecheck_sclass_func); 8804 D.getMutableDeclSpec().ClearStorageClassSpecs(); 8805 D.setInvalidType(); 8806 break; 8807 case DeclSpec::SCS_unspecified: break; 8808 case DeclSpec::SCS_extern: 8809 if (D.getDeclSpec().isExternInLinkageSpec()) 8810 return SC_None; 8811 return SC_Extern; 8812 case DeclSpec::SCS_static: { 8813 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 8814 // C99 6.7.1p5: 8815 // The declaration of an identifier for a function that has 8816 // block scope shall have no explicit storage-class specifier 8817 // other than extern 8818 // See also (C++ [dcl.stc]p4). 8819 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8820 diag::err_static_block_func); 8821 break; 8822 } else 8823 return SC_Static; 8824 } 8825 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 8826 } 8827 8828 // No explicit storage class has already been returned 8829 return SC_None; 8830 } 8831 8832 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 8833 DeclContext *DC, QualType &R, 8834 TypeSourceInfo *TInfo, 8835 StorageClass SC, 8836 bool &IsVirtualOkay) { 8837 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 8838 DeclarationName Name = NameInfo.getName(); 8839 8840 FunctionDecl *NewFD = nullptr; 8841 bool isInline = D.getDeclSpec().isInlineSpecified(); 8842 8843 if (!SemaRef.getLangOpts().CPlusPlus) { 8844 // Determine whether the function was written with a prototype. This is 8845 // true when: 8846 // - there is a prototype in the declarator, or 8847 // - the type R of the function is some kind of typedef or other non- 8848 // attributed reference to a type name (which eventually refers to a 8849 // function type). Note, we can't always look at the adjusted type to 8850 // check this case because attributes may cause a non-function 8851 // declarator to still have a function type. e.g., 8852 // typedef void func(int a); 8853 // __attribute__((noreturn)) func other_func; // This has a prototype 8854 bool HasPrototype = 8855 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 8856 (D.getDeclSpec().isTypeRep() && 8857 D.getDeclSpec().getRepAsType().get()->isFunctionProtoType()) || 8858 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 8859 assert( 8860 (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) && 8861 "Strict prototypes are required"); 8862 8863 NewFD = FunctionDecl::Create( 8864 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC, 8865 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype, 8866 ConstexprSpecKind::Unspecified, 8867 /*TrailingRequiresClause=*/nullptr); 8868 if (D.isInvalidType()) 8869 NewFD->setInvalidDecl(); 8870 8871 return NewFD; 8872 } 8873 8874 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier(); 8875 8876 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 8877 if (ConstexprKind == ConstexprSpecKind::Constinit) { 8878 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(), 8879 diag::err_constexpr_wrong_decl_kind) 8880 << static_cast<int>(ConstexprKind); 8881 ConstexprKind = ConstexprSpecKind::Unspecified; 8882 D.getMutableDeclSpec().ClearConstexprSpec(); 8883 } 8884 Expr *TrailingRequiresClause = D.getTrailingRequiresClause(); 8885 8886 // Check that the return type is not an abstract class type. 8887 // For record types, this is done by the AbstractClassUsageDiagnoser once 8888 // the class has been completely parsed. 8889 if (!DC->isRecord() && 8890 SemaRef.RequireNonAbstractType( 8891 D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(), 8892 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 8893 D.setInvalidType(); 8894 8895 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 8896 // This is a C++ constructor declaration. 8897 assert(DC->isRecord() && 8898 "Constructors can only be declared in a member context"); 8899 8900 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 8901 return CXXConstructorDecl::Create( 8902 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8903 TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(), 8904 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind, 8905 InheritedConstructor(), TrailingRequiresClause); 8906 8907 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8908 // This is a C++ destructor declaration. 8909 if (DC->isRecord()) { 8910 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 8911 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 8912 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 8913 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo, 8914 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 8915 /*isImplicitlyDeclared=*/false, ConstexprKind, 8916 TrailingRequiresClause); 8917 // User defined destructors start as not selected if the class definition is still 8918 // not done. 8919 if (Record->isBeingDefined()) 8920 NewDD->setIneligibleOrNotSelected(true); 8921 8922 // If the destructor needs an implicit exception specification, set it 8923 // now. FIXME: It'd be nice to be able to create the right type to start 8924 // with, but the type needs to reference the destructor declaration. 8925 if (SemaRef.getLangOpts().CPlusPlus11) 8926 SemaRef.AdjustDestructorExceptionSpec(NewDD); 8927 8928 IsVirtualOkay = true; 8929 return NewDD; 8930 8931 } else { 8932 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 8933 D.setInvalidType(); 8934 8935 // Create a FunctionDecl to satisfy the function definition parsing 8936 // code path. 8937 return FunctionDecl::Create( 8938 SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R, 8939 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 8940 /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause); 8941 } 8942 8943 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 8944 if (!DC->isRecord()) { 8945 SemaRef.Diag(D.getIdentifierLoc(), 8946 diag::err_conv_function_not_member); 8947 return nullptr; 8948 } 8949 8950 SemaRef.CheckConversionDeclarator(D, R, SC); 8951 if (D.isInvalidType()) 8952 return nullptr; 8953 8954 IsVirtualOkay = true; 8955 return CXXConversionDecl::Create( 8956 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8957 TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 8958 ExplicitSpecifier, ConstexprKind, SourceLocation(), 8959 TrailingRequiresClause); 8960 8961 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 8962 if (TrailingRequiresClause) 8963 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(), 8964 diag::err_trailing_requires_clause_on_deduction_guide) 8965 << TrailingRequiresClause->getSourceRange(); 8966 SemaRef.CheckDeductionGuideDeclarator(D, R, SC); 8967 8968 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8969 ExplicitSpecifier, NameInfo, R, TInfo, 8970 D.getEndLoc()); 8971 } else if (DC->isRecord()) { 8972 // If the name of the function is the same as the name of the record, 8973 // then this must be an invalid constructor that has a return type. 8974 // (The parser checks for a return type and makes the declarator a 8975 // constructor if it has no return type). 8976 if (Name.getAsIdentifierInfo() && 8977 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 8978 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 8979 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8980 << SourceRange(D.getIdentifierLoc()); 8981 return nullptr; 8982 } 8983 8984 // This is a C++ method declaration. 8985 CXXMethodDecl *Ret = CXXMethodDecl::Create( 8986 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8987 TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 8988 ConstexprKind, SourceLocation(), TrailingRequiresClause); 8989 IsVirtualOkay = !Ret->isStatic(); 8990 return Ret; 8991 } else { 8992 bool isFriend = 8993 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 8994 if (!isFriend && SemaRef.CurContext->isRecord()) 8995 return nullptr; 8996 8997 // Determine whether the function was written with a 8998 // prototype. This true when: 8999 // - we're in C++ (where every function has a prototype), 9000 return FunctionDecl::Create( 9001 SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC, 9002 SemaRef.getCurFPFeatures().isFPConstrained(), isInline, 9003 true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause); 9004 } 9005 } 9006 9007 enum OpenCLParamType { 9008 ValidKernelParam, 9009 PtrPtrKernelParam, 9010 PtrKernelParam, 9011 InvalidAddrSpacePtrKernelParam, 9012 InvalidKernelParam, 9013 RecordKernelParam 9014 }; 9015 9016 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) { 9017 // Size dependent types are just typedefs to normal integer types 9018 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to 9019 // integers other than by their names. 9020 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"}; 9021 9022 // Remove typedefs one by one until we reach a typedef 9023 // for a size dependent type. 9024 QualType DesugaredTy = Ty; 9025 do { 9026 ArrayRef<StringRef> Names(SizeTypeNames); 9027 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString()); 9028 if (Names.end() != Match) 9029 return true; 9030 9031 Ty = DesugaredTy; 9032 DesugaredTy = Ty.getSingleStepDesugaredType(C); 9033 } while (DesugaredTy != Ty); 9034 9035 return false; 9036 } 9037 9038 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 9039 if (PT->isDependentType()) 9040 return InvalidKernelParam; 9041 9042 if (PT->isPointerType() || PT->isReferenceType()) { 9043 QualType PointeeType = PT->getPointeeType(); 9044 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 9045 PointeeType.getAddressSpace() == LangAS::opencl_private || 9046 PointeeType.getAddressSpace() == LangAS::Default) 9047 return InvalidAddrSpacePtrKernelParam; 9048 9049 if (PointeeType->isPointerType()) { 9050 // This is a pointer to pointer parameter. 9051 // Recursively check inner type. 9052 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType); 9053 if (ParamKind == InvalidAddrSpacePtrKernelParam || 9054 ParamKind == InvalidKernelParam) 9055 return ParamKind; 9056 9057 return PtrPtrKernelParam; 9058 } 9059 9060 // C++ for OpenCL v1.0 s2.4: 9061 // Moreover the types used in parameters of the kernel functions must be: 9062 // Standard layout types for pointer parameters. The same applies to 9063 // reference if an implementation supports them in kernel parameters. 9064 if (S.getLangOpts().OpenCLCPlusPlus && 9065 !S.getOpenCLOptions().isAvailableOption( 9066 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) && 9067 !PointeeType->isAtomicType() && !PointeeType->isVoidType() && 9068 !PointeeType->isStandardLayoutType()) 9069 return InvalidKernelParam; 9070 9071 return PtrKernelParam; 9072 } 9073 9074 // OpenCL v1.2 s6.9.k: 9075 // Arguments to kernel functions in a program cannot be declared with the 9076 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 9077 // uintptr_t or a struct and/or union that contain fields declared to be one 9078 // of these built-in scalar types. 9079 if (isOpenCLSizeDependentType(S.getASTContext(), PT)) 9080 return InvalidKernelParam; 9081 9082 if (PT->isImageType()) 9083 return PtrKernelParam; 9084 9085 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) 9086 return InvalidKernelParam; 9087 9088 // OpenCL extension spec v1.2 s9.5: 9089 // This extension adds support for half scalar and vector types as built-in 9090 // types that can be used for arithmetic operations, conversions etc. 9091 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) && 9092 PT->isHalfType()) 9093 return InvalidKernelParam; 9094 9095 // Look into an array argument to check if it has a forbidden type. 9096 if (PT->isArrayType()) { 9097 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType(); 9098 // Call ourself to check an underlying type of an array. Since the 9099 // getPointeeOrArrayElementType returns an innermost type which is not an 9100 // array, this recursive call only happens once. 9101 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0)); 9102 } 9103 9104 // C++ for OpenCL v1.0 s2.4: 9105 // Moreover the types used in parameters of the kernel functions must be: 9106 // Trivial and standard-layout types C++17 [basic.types] (plain old data 9107 // types) for parameters passed by value; 9108 if (S.getLangOpts().OpenCLCPlusPlus && 9109 !S.getOpenCLOptions().isAvailableOption( 9110 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) && 9111 !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context)) 9112 return InvalidKernelParam; 9113 9114 if (PT->isRecordType()) 9115 return RecordKernelParam; 9116 9117 return ValidKernelParam; 9118 } 9119 9120 static void checkIsValidOpenCLKernelParameter( 9121 Sema &S, 9122 Declarator &D, 9123 ParmVarDecl *Param, 9124 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 9125 QualType PT = Param->getType(); 9126 9127 // Cache the valid types we encounter to avoid rechecking structs that are 9128 // used again 9129 if (ValidTypes.count(PT.getTypePtr())) 9130 return; 9131 9132 switch (getOpenCLKernelParameterType(S, PT)) { 9133 case PtrPtrKernelParam: 9134 // OpenCL v3.0 s6.11.a: 9135 // A kernel function argument cannot be declared as a pointer to a pointer 9136 // type. [...] This restriction only applies to OpenCL C 1.2 or below. 9137 if (S.getLangOpts().getOpenCLCompatibleVersion() <= 120) { 9138 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 9139 D.setInvalidType(); 9140 return; 9141 } 9142 9143 ValidTypes.insert(PT.getTypePtr()); 9144 return; 9145 9146 case InvalidAddrSpacePtrKernelParam: 9147 // OpenCL v1.0 s6.5: 9148 // __kernel function arguments declared to be a pointer of a type can point 9149 // to one of the following address spaces only : __global, __local or 9150 // __constant. 9151 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 9152 D.setInvalidType(); 9153 return; 9154 9155 // OpenCL v1.2 s6.9.k: 9156 // Arguments to kernel functions in a program cannot be declared with the 9157 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 9158 // uintptr_t or a struct and/or union that contain fields declared to be 9159 // one of these built-in scalar types. 9160 9161 case InvalidKernelParam: 9162 // OpenCL v1.2 s6.8 n: 9163 // A kernel function argument cannot be declared 9164 // of event_t type. 9165 // Do not diagnose half type since it is diagnosed as invalid argument 9166 // type for any function elsewhere. 9167 if (!PT->isHalfType()) { 9168 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 9169 9170 // Explain what typedefs are involved. 9171 const TypedefType *Typedef = nullptr; 9172 while ((Typedef = PT->getAs<TypedefType>())) { 9173 SourceLocation Loc = Typedef->getDecl()->getLocation(); 9174 // SourceLocation may be invalid for a built-in type. 9175 if (Loc.isValid()) 9176 S.Diag(Loc, diag::note_entity_declared_at) << PT; 9177 PT = Typedef->desugar(); 9178 } 9179 } 9180 9181 D.setInvalidType(); 9182 return; 9183 9184 case PtrKernelParam: 9185 case ValidKernelParam: 9186 ValidTypes.insert(PT.getTypePtr()); 9187 return; 9188 9189 case RecordKernelParam: 9190 break; 9191 } 9192 9193 // Track nested structs we will inspect 9194 SmallVector<const Decl *, 4> VisitStack; 9195 9196 // Track where we are in the nested structs. Items will migrate from 9197 // VisitStack to HistoryStack as we do the DFS for bad field. 9198 SmallVector<const FieldDecl *, 4> HistoryStack; 9199 HistoryStack.push_back(nullptr); 9200 9201 // At this point we already handled everything except of a RecordType or 9202 // an ArrayType of a RecordType. 9203 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type."); 9204 const RecordType *RecTy = 9205 PT->getPointeeOrArrayElementType()->getAs<RecordType>(); 9206 const RecordDecl *OrigRecDecl = RecTy->getDecl(); 9207 9208 VisitStack.push_back(RecTy->getDecl()); 9209 assert(VisitStack.back() && "First decl null?"); 9210 9211 do { 9212 const Decl *Next = VisitStack.pop_back_val(); 9213 if (!Next) { 9214 assert(!HistoryStack.empty()); 9215 // Found a marker, we have gone up a level 9216 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 9217 ValidTypes.insert(Hist->getType().getTypePtr()); 9218 9219 continue; 9220 } 9221 9222 // Adds everything except the original parameter declaration (which is not a 9223 // field itself) to the history stack. 9224 const RecordDecl *RD; 9225 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 9226 HistoryStack.push_back(Field); 9227 9228 QualType FieldTy = Field->getType(); 9229 // Other field types (known to be valid or invalid) are handled while we 9230 // walk around RecordDecl::fields(). 9231 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) && 9232 "Unexpected type."); 9233 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType(); 9234 9235 RD = FieldRecTy->castAs<RecordType>()->getDecl(); 9236 } else { 9237 RD = cast<RecordDecl>(Next); 9238 } 9239 9240 // Add a null marker so we know when we've gone back up a level 9241 VisitStack.push_back(nullptr); 9242 9243 for (const auto *FD : RD->fields()) { 9244 QualType QT = FD->getType(); 9245 9246 if (ValidTypes.count(QT.getTypePtr())) 9247 continue; 9248 9249 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 9250 if (ParamType == ValidKernelParam) 9251 continue; 9252 9253 if (ParamType == RecordKernelParam) { 9254 VisitStack.push_back(FD); 9255 continue; 9256 } 9257 9258 // OpenCL v1.2 s6.9.p: 9259 // Arguments to kernel functions that are declared to be a struct or union 9260 // do not allow OpenCL objects to be passed as elements of the struct or 9261 // union. 9262 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 9263 ParamType == InvalidAddrSpacePtrKernelParam) { 9264 S.Diag(Param->getLocation(), 9265 diag::err_record_with_pointers_kernel_param) 9266 << PT->isUnionType() 9267 << PT; 9268 } else { 9269 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 9270 } 9271 9272 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type) 9273 << OrigRecDecl->getDeclName(); 9274 9275 // We have an error, now let's go back up through history and show where 9276 // the offending field came from 9277 for (ArrayRef<const FieldDecl *>::const_iterator 9278 I = HistoryStack.begin() + 1, 9279 E = HistoryStack.end(); 9280 I != E; ++I) { 9281 const FieldDecl *OuterField = *I; 9282 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 9283 << OuterField->getType(); 9284 } 9285 9286 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 9287 << QT->isPointerType() 9288 << QT; 9289 D.setInvalidType(); 9290 return; 9291 } 9292 } while (!VisitStack.empty()); 9293 } 9294 9295 /// Find the DeclContext in which a tag is implicitly declared if we see an 9296 /// elaborated type specifier in the specified context, and lookup finds 9297 /// nothing. 9298 static DeclContext *getTagInjectionContext(DeclContext *DC) { 9299 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 9300 DC = DC->getParent(); 9301 return DC; 9302 } 9303 9304 /// Find the Scope in which a tag is implicitly declared if we see an 9305 /// elaborated type specifier in the specified context, and lookup finds 9306 /// nothing. 9307 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 9308 while (S->isClassScope() || 9309 (LangOpts.CPlusPlus && 9310 S->isFunctionPrototypeScope()) || 9311 ((S->getFlags() & Scope::DeclScope) == 0) || 9312 (S->getEntity() && S->getEntity()->isTransparentContext())) 9313 S = S->getParent(); 9314 return S; 9315 } 9316 9317 /// Determine whether a declaration matches a known function in namespace std. 9318 static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD, 9319 unsigned BuiltinID) { 9320 switch (BuiltinID) { 9321 case Builtin::BI__GetExceptionInfo: 9322 // No type checking whatsoever. 9323 return Ctx.getTargetInfo().getCXXABI().isMicrosoft(); 9324 9325 case Builtin::BIaddressof: 9326 case Builtin::BI__addressof: 9327 case Builtin::BIforward: 9328 case Builtin::BImove: 9329 case Builtin::BImove_if_noexcept: 9330 case Builtin::BIas_const: { 9331 // Ensure that we don't treat the algorithm 9332 // OutputIt std::move(InputIt, InputIt, OutputIt) 9333 // as the builtin std::move. 9334 const auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 9335 return FPT->getNumParams() == 1 && !FPT->isVariadic(); 9336 } 9337 9338 default: 9339 return false; 9340 } 9341 } 9342 9343 NamedDecl* 9344 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 9345 TypeSourceInfo *TInfo, LookupResult &Previous, 9346 MultiTemplateParamsArg TemplateParamListsRef, 9347 bool &AddToScope) { 9348 QualType R = TInfo->getType(); 9349 9350 assert(R->isFunctionType()); 9351 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr()) 9352 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call); 9353 9354 SmallVector<TemplateParameterList *, 4> TemplateParamLists; 9355 llvm::append_range(TemplateParamLists, TemplateParamListsRef); 9356 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) { 9357 if (!TemplateParamLists.empty() && 9358 Invented->getDepth() == TemplateParamLists.back()->getDepth()) 9359 TemplateParamLists.back() = Invented; 9360 else 9361 TemplateParamLists.push_back(Invented); 9362 } 9363 9364 // TODO: consider using NameInfo for diagnostic. 9365 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 9366 DeclarationName Name = NameInfo.getName(); 9367 StorageClass SC = getFunctionStorageClass(*this, D); 9368 9369 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 9370 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 9371 diag::err_invalid_thread) 9372 << DeclSpec::getSpecifierName(TSCS); 9373 9374 if (D.isFirstDeclarationOfMember()) 9375 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 9376 D.getIdentifierLoc()); 9377 9378 bool isFriend = false; 9379 FunctionTemplateDecl *FunctionTemplate = nullptr; 9380 bool isMemberSpecialization = false; 9381 bool isFunctionTemplateSpecialization = false; 9382 9383 bool isDependentClassScopeExplicitSpecialization = false; 9384 bool HasExplicitTemplateArgs = false; 9385 TemplateArgumentListInfo TemplateArgs; 9386 9387 bool isVirtualOkay = false; 9388 9389 DeclContext *OriginalDC = DC; 9390 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 9391 9392 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 9393 isVirtualOkay); 9394 if (!NewFD) return nullptr; 9395 9396 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 9397 NewFD->setTopLevelDeclInObjCContainer(); 9398 9399 // Set the lexical context. If this is a function-scope declaration, or has a 9400 // C++ scope specifier, or is the object of a friend declaration, the lexical 9401 // context will be different from the semantic context. 9402 NewFD->setLexicalDeclContext(CurContext); 9403 9404 if (IsLocalExternDecl) 9405 NewFD->setLocalExternDecl(); 9406 9407 if (getLangOpts().CPlusPlus) { 9408 bool isInline = D.getDeclSpec().isInlineSpecified(); 9409 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 9410 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier(); 9411 isFriend = D.getDeclSpec().isFriendSpecified(); 9412 if (isFriend && !isInline && D.isFunctionDefinition()) { 9413 // C++ [class.friend]p5 9414 // A function can be defined in a friend declaration of a 9415 // class . . . . Such a function is implicitly inline. 9416 NewFD->setImplicitlyInline(); 9417 } 9418 9419 // If this is a method defined in an __interface, and is not a constructor 9420 // or an overloaded operator, then set the pure flag (isVirtual will already 9421 // return true). 9422 if (const CXXRecordDecl *Parent = 9423 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 9424 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 9425 NewFD->setPure(true); 9426 9427 // C++ [class.union]p2 9428 // A union can have member functions, but not virtual functions. 9429 if (isVirtual && Parent->isUnion()) { 9430 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 9431 NewFD->setInvalidDecl(); 9432 } 9433 if ((Parent->isClass() || Parent->isStruct()) && 9434 Parent->hasAttr<SYCLSpecialClassAttr>() && 9435 NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() && 9436 NewFD->getName() == "__init" && D.isFunctionDefinition()) { 9437 if (auto *Def = Parent->getDefinition()) 9438 Def->setInitMethod(true); 9439 } 9440 } 9441 9442 SetNestedNameSpecifier(*this, NewFD, D); 9443 isMemberSpecialization = false; 9444 isFunctionTemplateSpecialization = false; 9445 if (D.isInvalidType()) 9446 NewFD->setInvalidDecl(); 9447 9448 // Match up the template parameter lists with the scope specifier, then 9449 // determine whether we have a template or a template specialization. 9450 bool Invalid = false; 9451 TemplateParameterList *TemplateParams = 9452 MatchTemplateParametersToScopeSpecifier( 9453 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 9454 D.getCXXScopeSpec(), 9455 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 9456 ? D.getName().TemplateId 9457 : nullptr, 9458 TemplateParamLists, isFriend, isMemberSpecialization, 9459 Invalid); 9460 if (TemplateParams) { 9461 // Check that we can declare a template here. 9462 if (CheckTemplateDeclScope(S, TemplateParams)) 9463 NewFD->setInvalidDecl(); 9464 9465 if (TemplateParams->size() > 0) { 9466 // This is a function template 9467 9468 // A destructor cannot be a template. 9469 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 9470 Diag(NewFD->getLocation(), diag::err_destructor_template); 9471 NewFD->setInvalidDecl(); 9472 } 9473 9474 // If we're adding a template to a dependent context, we may need to 9475 // rebuilding some of the types used within the template parameter list, 9476 // now that we know what the current instantiation is. 9477 if (DC->isDependentContext()) { 9478 ContextRAII SavedContext(*this, DC); 9479 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 9480 Invalid = true; 9481 } 9482 9483 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 9484 NewFD->getLocation(), 9485 Name, TemplateParams, 9486 NewFD); 9487 FunctionTemplate->setLexicalDeclContext(CurContext); 9488 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 9489 9490 // For source fidelity, store the other template param lists. 9491 if (TemplateParamLists.size() > 1) { 9492 NewFD->setTemplateParameterListsInfo(Context, 9493 ArrayRef<TemplateParameterList *>(TemplateParamLists) 9494 .drop_back(1)); 9495 } 9496 } else { 9497 // This is a function template specialization. 9498 isFunctionTemplateSpecialization = true; 9499 // For source fidelity, store all the template param lists. 9500 if (TemplateParamLists.size() > 0) 9501 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 9502 9503 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 9504 if (isFriend) { 9505 // We want to remove the "template<>", found here. 9506 SourceRange RemoveRange = TemplateParams->getSourceRange(); 9507 9508 // If we remove the template<> and the name is not a 9509 // template-id, we're actually silently creating a problem: 9510 // the friend declaration will refer to an untemplated decl, 9511 // and clearly the user wants a template specialization. So 9512 // we need to insert '<>' after the name. 9513 SourceLocation InsertLoc; 9514 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 9515 InsertLoc = D.getName().getSourceRange().getEnd(); 9516 InsertLoc = getLocForEndOfToken(InsertLoc); 9517 } 9518 9519 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 9520 << Name << RemoveRange 9521 << FixItHint::CreateRemoval(RemoveRange) 9522 << FixItHint::CreateInsertion(InsertLoc, "<>"); 9523 Invalid = true; 9524 } 9525 } 9526 } else { 9527 // Check that we can declare a template here. 9528 if (!TemplateParamLists.empty() && isMemberSpecialization && 9529 CheckTemplateDeclScope(S, TemplateParamLists.back())) 9530 NewFD->setInvalidDecl(); 9531 9532 // All template param lists were matched against the scope specifier: 9533 // this is NOT (an explicit specialization of) a template. 9534 if (TemplateParamLists.size() > 0) 9535 // For source fidelity, store all the template param lists. 9536 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 9537 } 9538 9539 if (Invalid) { 9540 NewFD->setInvalidDecl(); 9541 if (FunctionTemplate) 9542 FunctionTemplate->setInvalidDecl(); 9543 } 9544 9545 // C++ [dcl.fct.spec]p5: 9546 // The virtual specifier shall only be used in declarations of 9547 // nonstatic class member functions that appear within a 9548 // member-specification of a class declaration; see 10.3. 9549 // 9550 if (isVirtual && !NewFD->isInvalidDecl()) { 9551 if (!isVirtualOkay) { 9552 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9553 diag::err_virtual_non_function); 9554 } else if (!CurContext->isRecord()) { 9555 // 'virtual' was specified outside of the class. 9556 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9557 diag::err_virtual_out_of_class) 9558 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 9559 } else if (NewFD->getDescribedFunctionTemplate()) { 9560 // C++ [temp.mem]p3: 9561 // A member function template shall not be virtual. 9562 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9563 diag::err_virtual_member_function_template) 9564 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 9565 } else { 9566 // Okay: Add virtual to the method. 9567 NewFD->setVirtualAsWritten(true); 9568 } 9569 9570 if (getLangOpts().CPlusPlus14 && 9571 NewFD->getReturnType()->isUndeducedType()) 9572 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 9573 } 9574 9575 if (getLangOpts().CPlusPlus14 && 9576 (NewFD->isDependentContext() || 9577 (isFriend && CurContext->isDependentContext())) && 9578 NewFD->getReturnType()->isUndeducedType()) { 9579 // If the function template is referenced directly (for instance, as a 9580 // member of the current instantiation), pretend it has a dependent type. 9581 // This is not really justified by the standard, but is the only sane 9582 // thing to do. 9583 // FIXME: For a friend function, we have not marked the function as being 9584 // a friend yet, so 'isDependentContext' on the FD doesn't work. 9585 const FunctionProtoType *FPT = 9586 NewFD->getType()->castAs<FunctionProtoType>(); 9587 QualType Result = SubstAutoTypeDependent(FPT->getReturnType()); 9588 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 9589 FPT->getExtProtoInfo())); 9590 } 9591 9592 // C++ [dcl.fct.spec]p3: 9593 // The inline specifier shall not appear on a block scope function 9594 // declaration. 9595 if (isInline && !NewFD->isInvalidDecl()) { 9596 if (CurContext->isFunctionOrMethod()) { 9597 // 'inline' is not allowed on block scope function declaration. 9598 Diag(D.getDeclSpec().getInlineSpecLoc(), 9599 diag::err_inline_declaration_block_scope) << Name 9600 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 9601 } 9602 } 9603 9604 // C++ [dcl.fct.spec]p6: 9605 // The explicit specifier shall be used only in the declaration of a 9606 // constructor or conversion function within its class definition; 9607 // see 12.3.1 and 12.3.2. 9608 if (hasExplicit && !NewFD->isInvalidDecl() && 9609 !isa<CXXDeductionGuideDecl>(NewFD)) { 9610 if (!CurContext->isRecord()) { 9611 // 'explicit' was specified outside of the class. 9612 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9613 diag::err_explicit_out_of_class) 9614 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9615 } else if (!isa<CXXConstructorDecl>(NewFD) && 9616 !isa<CXXConversionDecl>(NewFD)) { 9617 // 'explicit' was specified on a function that wasn't a constructor 9618 // or conversion function. 9619 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9620 diag::err_explicit_non_ctor_or_conv_function) 9621 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9622 } 9623 } 9624 9625 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 9626 if (ConstexprKind != ConstexprSpecKind::Unspecified) { 9627 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 9628 // are implicitly inline. 9629 NewFD->setImplicitlyInline(); 9630 9631 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 9632 // be either constructors or to return a literal type. Therefore, 9633 // destructors cannot be declared constexpr. 9634 if (isa<CXXDestructorDecl>(NewFD) && 9635 (!getLangOpts().CPlusPlus20 || 9636 ConstexprKind == ConstexprSpecKind::Consteval)) { 9637 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor) 9638 << static_cast<int>(ConstexprKind); 9639 NewFD->setConstexprKind(getLangOpts().CPlusPlus20 9640 ? ConstexprSpecKind::Unspecified 9641 : ConstexprSpecKind::Constexpr); 9642 } 9643 // C++20 [dcl.constexpr]p2: An allocation function, or a 9644 // deallocation function shall not be declared with the consteval 9645 // specifier. 9646 if (ConstexprKind == ConstexprSpecKind::Consteval && 9647 (NewFD->getOverloadedOperator() == OO_New || 9648 NewFD->getOverloadedOperator() == OO_Array_New || 9649 NewFD->getOverloadedOperator() == OO_Delete || 9650 NewFD->getOverloadedOperator() == OO_Array_Delete)) { 9651 Diag(D.getDeclSpec().getConstexprSpecLoc(), 9652 diag::err_invalid_consteval_decl_kind) 9653 << NewFD; 9654 NewFD->setConstexprKind(ConstexprSpecKind::Constexpr); 9655 } 9656 } 9657 9658 // If __module_private__ was specified, mark the function accordingly. 9659 if (D.getDeclSpec().isModulePrivateSpecified()) { 9660 if (isFunctionTemplateSpecialization) { 9661 SourceLocation ModulePrivateLoc 9662 = D.getDeclSpec().getModulePrivateSpecLoc(); 9663 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 9664 << 0 9665 << FixItHint::CreateRemoval(ModulePrivateLoc); 9666 } else { 9667 NewFD->setModulePrivate(); 9668 if (FunctionTemplate) 9669 FunctionTemplate->setModulePrivate(); 9670 } 9671 } 9672 9673 if (isFriend) { 9674 if (FunctionTemplate) { 9675 FunctionTemplate->setObjectOfFriendDecl(); 9676 FunctionTemplate->setAccess(AS_public); 9677 } 9678 NewFD->setObjectOfFriendDecl(); 9679 NewFD->setAccess(AS_public); 9680 } 9681 9682 // If a function is defined as defaulted or deleted, mark it as such now. 9683 // We'll do the relevant checks on defaulted / deleted functions later. 9684 switch (D.getFunctionDefinitionKind()) { 9685 case FunctionDefinitionKind::Declaration: 9686 case FunctionDefinitionKind::Definition: 9687 break; 9688 9689 case FunctionDefinitionKind::Defaulted: 9690 NewFD->setDefaulted(); 9691 break; 9692 9693 case FunctionDefinitionKind::Deleted: 9694 NewFD->setDeletedAsWritten(); 9695 break; 9696 } 9697 9698 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 9699 D.isFunctionDefinition()) { 9700 // C++ [class.mfct]p2: 9701 // A member function may be defined (8.4) in its class definition, in 9702 // which case it is an inline member function (7.1.2) 9703 NewFD->setImplicitlyInline(); 9704 } 9705 9706 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 9707 !CurContext->isRecord()) { 9708 // C++ [class.static]p1: 9709 // A data or function member of a class may be declared static 9710 // in a class definition, in which case it is a static member of 9711 // the class. 9712 9713 // Complain about the 'static' specifier if it's on an out-of-line 9714 // member function definition. 9715 9716 // MSVC permits the use of a 'static' storage specifier on an out-of-line 9717 // member function template declaration and class member template 9718 // declaration (MSVC versions before 2015), warn about this. 9719 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 9720 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 9721 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) || 9722 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate())) 9723 ? diag::ext_static_out_of_line : diag::err_static_out_of_line) 9724 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 9725 } 9726 9727 // C++11 [except.spec]p15: 9728 // A deallocation function with no exception-specification is treated 9729 // as if it were specified with noexcept(true). 9730 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 9731 if ((Name.getCXXOverloadedOperator() == OO_Delete || 9732 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 9733 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 9734 NewFD->setType(Context.getFunctionType( 9735 FPT->getReturnType(), FPT->getParamTypes(), 9736 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 9737 } 9738 9739 // Filter out previous declarations that don't match the scope. 9740 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 9741 D.getCXXScopeSpec().isNotEmpty() || 9742 isMemberSpecialization || 9743 isFunctionTemplateSpecialization); 9744 9745 // Handle GNU asm-label extension (encoded as an attribute). 9746 if (Expr *E = (Expr*) D.getAsmLabel()) { 9747 // The parser guarantees this is a string. 9748 StringLiteral *SE = cast<StringLiteral>(E); 9749 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(), 9750 /*IsLiteralLabel=*/true, 9751 SE->getStrTokenLoc(0))); 9752 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 9753 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 9754 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 9755 if (I != ExtnameUndeclaredIdentifiers.end()) { 9756 if (isDeclExternC(NewFD)) { 9757 NewFD->addAttr(I->second); 9758 ExtnameUndeclaredIdentifiers.erase(I); 9759 } else 9760 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 9761 << /*Variable*/0 << NewFD; 9762 } 9763 } 9764 9765 // Copy the parameter declarations from the declarator D to the function 9766 // declaration NewFD, if they are available. First scavenge them into Params. 9767 SmallVector<ParmVarDecl*, 16> Params; 9768 unsigned FTIIdx; 9769 if (D.isFunctionDeclarator(FTIIdx)) { 9770 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 9771 9772 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 9773 // function that takes no arguments, not a function that takes a 9774 // single void argument. 9775 // We let through "const void" here because Sema::GetTypeForDeclarator 9776 // already checks for that case. 9777 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 9778 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 9779 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 9780 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 9781 Param->setDeclContext(NewFD); 9782 Params.push_back(Param); 9783 9784 if (Param->isInvalidDecl()) 9785 NewFD->setInvalidDecl(); 9786 } 9787 } 9788 9789 if (!getLangOpts().CPlusPlus) { 9790 // In C, find all the tag declarations from the prototype and move them 9791 // into the function DeclContext. Remove them from the surrounding tag 9792 // injection context of the function, which is typically but not always 9793 // the TU. 9794 DeclContext *PrototypeTagContext = 9795 getTagInjectionContext(NewFD->getLexicalDeclContext()); 9796 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 9797 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 9798 9799 // We don't want to reparent enumerators. Look at their parent enum 9800 // instead. 9801 if (!TD) { 9802 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 9803 TD = cast<EnumDecl>(ECD->getDeclContext()); 9804 } 9805 if (!TD) 9806 continue; 9807 DeclContext *TagDC = TD->getLexicalDeclContext(); 9808 if (!TagDC->containsDecl(TD)) 9809 continue; 9810 TagDC->removeDecl(TD); 9811 TD->setDeclContext(NewFD); 9812 NewFD->addDecl(TD); 9813 9814 // Preserve the lexical DeclContext if it is not the surrounding tag 9815 // injection context of the FD. In this example, the semantic context of 9816 // E will be f and the lexical context will be S, while both the 9817 // semantic and lexical contexts of S will be f: 9818 // void f(struct S { enum E { a } f; } s); 9819 if (TagDC != PrototypeTagContext) 9820 TD->setLexicalDeclContext(TagDC); 9821 } 9822 } 9823 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 9824 // When we're declaring a function with a typedef, typeof, etc as in the 9825 // following example, we'll need to synthesize (unnamed) 9826 // parameters for use in the declaration. 9827 // 9828 // @code 9829 // typedef void fn(int); 9830 // fn f; 9831 // @endcode 9832 9833 // Synthesize a parameter for each argument type. 9834 for (const auto &AI : FT->param_types()) { 9835 ParmVarDecl *Param = 9836 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 9837 Param->setScopeInfo(0, Params.size()); 9838 Params.push_back(Param); 9839 } 9840 } else { 9841 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 9842 "Should not need args for typedef of non-prototype fn"); 9843 } 9844 9845 // Finally, we know we have the right number of parameters, install them. 9846 NewFD->setParams(Params); 9847 9848 if (D.getDeclSpec().isNoreturnSpecified()) 9849 NewFD->addAttr(C11NoReturnAttr::Create(Context, 9850 D.getDeclSpec().getNoreturnSpecLoc(), 9851 AttributeCommonInfo::AS_Keyword)); 9852 9853 // Functions returning a variably modified type violate C99 6.7.5.2p2 9854 // because all functions have linkage. 9855 if (!NewFD->isInvalidDecl() && 9856 NewFD->getReturnType()->isVariablyModifiedType()) { 9857 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 9858 NewFD->setInvalidDecl(); 9859 } 9860 9861 // Apply an implicit SectionAttr if '#pragma clang section text' is active 9862 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && 9863 !NewFD->hasAttr<SectionAttr>()) 9864 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit( 9865 Context, PragmaClangTextSection.SectionName, 9866 PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma)); 9867 9868 // Apply an implicit SectionAttr if #pragma code_seg is active. 9869 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 9870 !NewFD->hasAttr<SectionAttr>()) { 9871 NewFD->addAttr(SectionAttr::CreateImplicit( 9872 Context, CodeSegStack.CurrentValue->getString(), 9873 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 9874 SectionAttr::Declspec_allocate)); 9875 if (UnifySection(CodeSegStack.CurrentValue->getString(), 9876 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 9877 ASTContext::PSF_Read, 9878 NewFD)) 9879 NewFD->dropAttr<SectionAttr>(); 9880 } 9881 9882 // Apply an implicit CodeSegAttr from class declspec or 9883 // apply an implicit SectionAttr from #pragma code_seg if active. 9884 if (!NewFD->hasAttr<CodeSegAttr>()) { 9885 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD, 9886 D.isFunctionDefinition())) { 9887 NewFD->addAttr(SAttr); 9888 } 9889 } 9890 9891 // Handle attributes. 9892 ProcessDeclAttributes(S, NewFD, D); 9893 9894 if (getLangOpts().OpenCL) { 9895 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 9896 // type declaration will generate a compilation error. 9897 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); 9898 if (AddressSpace != LangAS::Default) { 9899 Diag(NewFD->getLocation(), 9900 diag::err_opencl_return_value_with_address_space); 9901 NewFD->setInvalidDecl(); 9902 } 9903 } 9904 9905 if (!getLangOpts().CPlusPlus) { 9906 // Perform semantic checking on the function declaration. 9907 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9908 CheckMain(NewFD, D.getDeclSpec()); 9909 9910 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9911 CheckMSVCRTEntryPoint(NewFD); 9912 9913 if (!NewFD->isInvalidDecl()) 9914 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9915 isMemberSpecialization, 9916 D.isFunctionDefinition())); 9917 else if (!Previous.empty()) 9918 // Recover gracefully from an invalid redeclaration. 9919 D.setRedeclaration(true); 9920 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9921 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9922 "previous declaration set still overloaded"); 9923 9924 // Diagnose no-prototype function declarations with calling conventions that 9925 // don't support variadic calls. Only do this in C and do it after merging 9926 // possibly prototyped redeclarations. 9927 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 9928 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 9929 CallingConv CC = FT->getExtInfo().getCC(); 9930 if (!supportsVariadicCall(CC)) { 9931 // Windows system headers sometimes accidentally use stdcall without 9932 // (void) parameters, so we relax this to a warning. 9933 int DiagID = 9934 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 9935 Diag(NewFD->getLocation(), DiagID) 9936 << FunctionType::getNameForCallConv(CC); 9937 } 9938 } 9939 9940 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() || 9941 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion()) 9942 checkNonTrivialCUnion(NewFD->getReturnType(), 9943 NewFD->getReturnTypeSourceRange().getBegin(), 9944 NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy); 9945 } else { 9946 // C++11 [replacement.functions]p3: 9947 // The program's definitions shall not be specified as inline. 9948 // 9949 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 9950 // 9951 // Suppress the diagnostic if the function is __attribute__((used)), since 9952 // that forces an external definition to be emitted. 9953 if (D.getDeclSpec().isInlineSpecified() && 9954 NewFD->isReplaceableGlobalAllocationFunction() && 9955 !NewFD->hasAttr<UsedAttr>()) 9956 Diag(D.getDeclSpec().getInlineSpecLoc(), 9957 diag::ext_operator_new_delete_declared_inline) 9958 << NewFD->getDeclName(); 9959 9960 // If the declarator is a template-id, translate the parser's template 9961 // argument list into our AST format. 9962 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 9963 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 9964 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 9965 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 9966 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 9967 TemplateId->NumArgs); 9968 translateTemplateArguments(TemplateArgsPtr, 9969 TemplateArgs); 9970 9971 HasExplicitTemplateArgs = true; 9972 9973 if (NewFD->isInvalidDecl()) { 9974 HasExplicitTemplateArgs = false; 9975 } else if (FunctionTemplate) { 9976 // Function template with explicit template arguments. 9977 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 9978 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 9979 9980 HasExplicitTemplateArgs = false; 9981 } else { 9982 assert((isFunctionTemplateSpecialization || 9983 D.getDeclSpec().isFriendSpecified()) && 9984 "should have a 'template<>' for this decl"); 9985 // "friend void foo<>(int);" is an implicit specialization decl. 9986 isFunctionTemplateSpecialization = true; 9987 } 9988 } else if (isFriend && isFunctionTemplateSpecialization) { 9989 // This combination is only possible in a recovery case; the user 9990 // wrote something like: 9991 // template <> friend void foo(int); 9992 // which we're recovering from as if the user had written: 9993 // friend void foo<>(int); 9994 // Go ahead and fake up a template id. 9995 HasExplicitTemplateArgs = true; 9996 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 9997 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 9998 } 9999 10000 // We do not add HD attributes to specializations here because 10001 // they may have different constexpr-ness compared to their 10002 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 10003 // may end up with different effective targets. Instead, a 10004 // specialization inherits its target attributes from its template 10005 // in the CheckFunctionTemplateSpecialization() call below. 10006 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization) 10007 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 10008 10009 // If it's a friend (and only if it's a friend), it's possible 10010 // that either the specialized function type or the specialized 10011 // template is dependent, and therefore matching will fail. In 10012 // this case, don't check the specialization yet. 10013 if (isFunctionTemplateSpecialization && isFriend && 10014 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 10015 TemplateSpecializationType::anyInstantiationDependentTemplateArguments( 10016 TemplateArgs.arguments()))) { 10017 assert(HasExplicitTemplateArgs && 10018 "friend function specialization without template args"); 10019 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 10020 Previous)) 10021 NewFD->setInvalidDecl(); 10022 } else if (isFunctionTemplateSpecialization) { 10023 if (CurContext->isDependentContext() && CurContext->isRecord() 10024 && !isFriend) { 10025 isDependentClassScopeExplicitSpecialization = true; 10026 } else if (!NewFD->isInvalidDecl() && 10027 CheckFunctionTemplateSpecialization( 10028 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), 10029 Previous)) 10030 NewFD->setInvalidDecl(); 10031 10032 // C++ [dcl.stc]p1: 10033 // A storage-class-specifier shall not be specified in an explicit 10034 // specialization (14.7.3) 10035 FunctionTemplateSpecializationInfo *Info = 10036 NewFD->getTemplateSpecializationInfo(); 10037 if (Info && SC != SC_None) { 10038 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 10039 Diag(NewFD->getLocation(), 10040 diag::err_explicit_specialization_inconsistent_storage_class) 10041 << SC 10042 << FixItHint::CreateRemoval( 10043 D.getDeclSpec().getStorageClassSpecLoc()); 10044 10045 else 10046 Diag(NewFD->getLocation(), 10047 diag::ext_explicit_specialization_storage_class) 10048 << FixItHint::CreateRemoval( 10049 D.getDeclSpec().getStorageClassSpecLoc()); 10050 } 10051 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 10052 if (CheckMemberSpecialization(NewFD, Previous)) 10053 NewFD->setInvalidDecl(); 10054 } 10055 10056 // Perform semantic checking on the function declaration. 10057 if (!isDependentClassScopeExplicitSpecialization) { 10058 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 10059 CheckMain(NewFD, D.getDeclSpec()); 10060 10061 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 10062 CheckMSVCRTEntryPoint(NewFD); 10063 10064 if (!NewFD->isInvalidDecl()) 10065 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 10066 isMemberSpecialization, 10067 D.isFunctionDefinition())); 10068 else if (!Previous.empty()) 10069 // Recover gracefully from an invalid redeclaration. 10070 D.setRedeclaration(true); 10071 } 10072 10073 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 10074 Previous.getResultKind() != LookupResult::FoundOverloaded) && 10075 "previous declaration set still overloaded"); 10076 10077 NamedDecl *PrincipalDecl = (FunctionTemplate 10078 ? cast<NamedDecl>(FunctionTemplate) 10079 : NewFD); 10080 10081 if (isFriend && NewFD->getPreviousDecl()) { 10082 AccessSpecifier Access = AS_public; 10083 if (!NewFD->isInvalidDecl()) 10084 Access = NewFD->getPreviousDecl()->getAccess(); 10085 10086 NewFD->setAccess(Access); 10087 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 10088 } 10089 10090 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 10091 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 10092 PrincipalDecl->setNonMemberOperator(); 10093 10094 // If we have a function template, check the template parameter 10095 // list. This will check and merge default template arguments. 10096 if (FunctionTemplate) { 10097 FunctionTemplateDecl *PrevTemplate = 10098 FunctionTemplate->getPreviousDecl(); 10099 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 10100 PrevTemplate ? PrevTemplate->getTemplateParameters() 10101 : nullptr, 10102 D.getDeclSpec().isFriendSpecified() 10103 ? (D.isFunctionDefinition() 10104 ? TPC_FriendFunctionTemplateDefinition 10105 : TPC_FriendFunctionTemplate) 10106 : (D.getCXXScopeSpec().isSet() && 10107 DC && DC->isRecord() && 10108 DC->isDependentContext()) 10109 ? TPC_ClassTemplateMember 10110 : TPC_FunctionTemplate); 10111 } 10112 10113 if (NewFD->isInvalidDecl()) { 10114 // Ignore all the rest of this. 10115 } else if (!D.isRedeclaration()) { 10116 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 10117 AddToScope }; 10118 // Fake up an access specifier if it's supposed to be a class member. 10119 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 10120 NewFD->setAccess(AS_public); 10121 10122 // Qualified decls generally require a previous declaration. 10123 if (D.getCXXScopeSpec().isSet()) { 10124 // ...with the major exception of templated-scope or 10125 // dependent-scope friend declarations. 10126 10127 // TODO: we currently also suppress this check in dependent 10128 // contexts because (1) the parameter depth will be off when 10129 // matching friend templates and (2) we might actually be 10130 // selecting a friend based on a dependent factor. But there 10131 // are situations where these conditions don't apply and we 10132 // can actually do this check immediately. 10133 // 10134 // Unless the scope is dependent, it's always an error if qualified 10135 // redeclaration lookup found nothing at all. Diagnose that now; 10136 // nothing will diagnose that error later. 10137 if (isFriend && 10138 (D.getCXXScopeSpec().getScopeRep()->isDependent() || 10139 (!Previous.empty() && CurContext->isDependentContext()))) { 10140 // ignore these 10141 } else if (NewFD->isCPUDispatchMultiVersion() || 10142 NewFD->isCPUSpecificMultiVersion()) { 10143 // ignore this, we allow the redeclaration behavior here to create new 10144 // versions of the function. 10145 } else { 10146 // The user tried to provide an out-of-line definition for a 10147 // function that is a member of a class or namespace, but there 10148 // was no such member function declared (C++ [class.mfct]p2, 10149 // C++ [namespace.memdef]p2). For example: 10150 // 10151 // class X { 10152 // void f() const; 10153 // }; 10154 // 10155 // void X::f() { } // ill-formed 10156 // 10157 // Complain about this problem, and attempt to suggest close 10158 // matches (e.g., those that differ only in cv-qualifiers and 10159 // whether the parameter types are references). 10160 10161 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 10162 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 10163 AddToScope = ExtraArgs.AddToScope; 10164 return Result; 10165 } 10166 } 10167 10168 // Unqualified local friend declarations are required to resolve 10169 // to something. 10170 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 10171 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 10172 *this, Previous, NewFD, ExtraArgs, true, S)) { 10173 AddToScope = ExtraArgs.AddToScope; 10174 return Result; 10175 } 10176 } 10177 } else if (!D.isFunctionDefinition() && 10178 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 10179 !isFriend && !isFunctionTemplateSpecialization && 10180 !isMemberSpecialization) { 10181 // An out-of-line member function declaration must also be a 10182 // definition (C++ [class.mfct]p2). 10183 // Note that this is not the case for explicit specializations of 10184 // function templates or member functions of class templates, per 10185 // C++ [temp.expl.spec]p2. We also allow these declarations as an 10186 // extension for compatibility with old SWIG code which likes to 10187 // generate them. 10188 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 10189 << D.getCXXScopeSpec().getRange(); 10190 } 10191 } 10192 10193 // If this is the first declaration of a library builtin function, add 10194 // attributes as appropriate. 10195 if (!D.isRedeclaration()) { 10196 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) { 10197 if (unsigned BuiltinID = II->getBuiltinID()) { 10198 bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID); 10199 if (!InStdNamespace && 10200 NewFD->getDeclContext()->getRedeclContext()->isFileContext()) { 10201 if (NewFD->getLanguageLinkage() == CLanguageLinkage) { 10202 // Validate the type matches unless this builtin is specified as 10203 // matching regardless of its declared type. 10204 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) { 10205 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 10206 } else { 10207 ASTContext::GetBuiltinTypeError Error; 10208 LookupNecessaryTypesForBuiltin(S, BuiltinID); 10209 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error); 10210 10211 if (!Error && !BuiltinType.isNull() && 10212 Context.hasSameFunctionTypeIgnoringExceptionSpec( 10213 NewFD->getType(), BuiltinType)) 10214 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 10215 } 10216 } 10217 } else if (InStdNamespace && NewFD->isInStdNamespace() && 10218 isStdBuiltin(Context, NewFD, BuiltinID)) { 10219 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); 10220 } 10221 } 10222 } 10223 } 10224 10225 ProcessPragmaWeak(S, NewFD); 10226 checkAttributesAfterMerging(*this, *NewFD); 10227 10228 AddKnownFunctionAttributes(NewFD); 10229 10230 if (NewFD->hasAttr<OverloadableAttr>() && 10231 !NewFD->getType()->getAs<FunctionProtoType>()) { 10232 Diag(NewFD->getLocation(), 10233 diag::err_attribute_overloadable_no_prototype) 10234 << NewFD; 10235 10236 // Turn this into a variadic function with no parameters. 10237 const auto *FT = NewFD->getType()->castAs<FunctionType>(); 10238 FunctionProtoType::ExtProtoInfo EPI( 10239 Context.getDefaultCallingConvention(true, false)); 10240 EPI.Variadic = true; 10241 EPI.ExtInfo = FT->getExtInfo(); 10242 10243 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 10244 NewFD->setType(R); 10245 } 10246 10247 // If there's a #pragma GCC visibility in scope, and this isn't a class 10248 // member, set the visibility of this function. 10249 if (!DC->isRecord() && NewFD->isExternallyVisible()) 10250 AddPushedVisibilityAttribute(NewFD); 10251 10252 // If there's a #pragma clang arc_cf_code_audited in scope, consider 10253 // marking the function. 10254 AddCFAuditedAttribute(NewFD); 10255 10256 // If this is a function definition, check if we have to apply any 10257 // attributes (i.e. optnone and no_builtin) due to a pragma. 10258 if (D.isFunctionDefinition()) { 10259 AddRangeBasedOptnone(NewFD); 10260 AddImplicitMSFunctionNoBuiltinAttr(NewFD); 10261 AddSectionMSAllocText(NewFD); 10262 ModifyFnAttributesMSPragmaOptimize(NewFD); 10263 } 10264 10265 // If this is the first declaration of an extern C variable, update 10266 // the map of such variables. 10267 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 10268 isIncompleteDeclExternC(*this, NewFD)) 10269 RegisterLocallyScopedExternCDecl(NewFD, S); 10270 10271 // Set this FunctionDecl's range up to the right paren. 10272 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 10273 10274 if (D.isRedeclaration() && !Previous.empty()) { 10275 NamedDecl *Prev = Previous.getRepresentativeDecl(); 10276 checkDLLAttributeRedeclaration(*this, Prev, NewFD, 10277 isMemberSpecialization || 10278 isFunctionTemplateSpecialization, 10279 D.isFunctionDefinition()); 10280 } 10281 10282 if (getLangOpts().CUDA) { 10283 IdentifierInfo *II = NewFD->getIdentifier(); 10284 if (II && II->isStr(getCudaConfigureFuncName()) && 10285 !NewFD->isInvalidDecl() && 10286 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 10287 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType()) 10288 Diag(NewFD->getLocation(), diag::err_config_scalar_return) 10289 << getCudaConfigureFuncName(); 10290 Context.setcudaConfigureCallDecl(NewFD); 10291 } 10292 10293 // Variadic functions, other than a *declaration* of printf, are not allowed 10294 // in device-side CUDA code, unless someone passed 10295 // -fcuda-allow-variadic-functions. 10296 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 10297 (NewFD->hasAttr<CUDADeviceAttr>() || 10298 NewFD->hasAttr<CUDAGlobalAttr>()) && 10299 !(II && II->isStr("printf") && NewFD->isExternC() && 10300 !D.isFunctionDefinition())) { 10301 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 10302 } 10303 } 10304 10305 MarkUnusedFileScopedDecl(NewFD); 10306 10307 10308 10309 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) { 10310 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 10311 if (SC == SC_Static) { 10312 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 10313 D.setInvalidType(); 10314 } 10315 10316 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 10317 if (!NewFD->getReturnType()->isVoidType()) { 10318 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 10319 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 10320 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 10321 : FixItHint()); 10322 D.setInvalidType(); 10323 } 10324 10325 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 10326 for (auto Param : NewFD->parameters()) 10327 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 10328 10329 if (getLangOpts().OpenCLCPlusPlus) { 10330 if (DC->isRecord()) { 10331 Diag(D.getIdentifierLoc(), diag::err_method_kernel); 10332 D.setInvalidType(); 10333 } 10334 if (FunctionTemplate) { 10335 Diag(D.getIdentifierLoc(), diag::err_template_kernel); 10336 D.setInvalidType(); 10337 } 10338 } 10339 } 10340 10341 if (getLangOpts().CPlusPlus) { 10342 if (FunctionTemplate) { 10343 if (NewFD->isInvalidDecl()) 10344 FunctionTemplate->setInvalidDecl(); 10345 return FunctionTemplate; 10346 } 10347 10348 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 10349 CompleteMemberSpecialization(NewFD, Previous); 10350 } 10351 10352 for (const ParmVarDecl *Param : NewFD->parameters()) { 10353 QualType PT = Param->getType(); 10354 10355 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 10356 // types. 10357 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) { 10358 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 10359 QualType ElemTy = PipeTy->getElementType(); 10360 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 10361 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 10362 D.setInvalidType(); 10363 } 10364 } 10365 } 10366 } 10367 10368 // Here we have an function template explicit specialization at class scope. 10369 // The actual specialization will be postponed to template instatiation 10370 // time via the ClassScopeFunctionSpecializationDecl node. 10371 if (isDependentClassScopeExplicitSpecialization) { 10372 ClassScopeFunctionSpecializationDecl *NewSpec = 10373 ClassScopeFunctionSpecializationDecl::Create( 10374 Context, CurContext, NewFD->getLocation(), 10375 cast<CXXMethodDecl>(NewFD), 10376 HasExplicitTemplateArgs, TemplateArgs); 10377 CurContext->addDecl(NewSpec); 10378 AddToScope = false; 10379 } 10380 10381 // Diagnose availability attributes. Availability cannot be used on functions 10382 // that are run during load/unload. 10383 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { 10384 if (NewFD->hasAttr<ConstructorAttr>()) { 10385 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 10386 << 1; 10387 NewFD->dropAttr<AvailabilityAttr>(); 10388 } 10389 if (NewFD->hasAttr<DestructorAttr>()) { 10390 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 10391 << 2; 10392 NewFD->dropAttr<AvailabilityAttr>(); 10393 } 10394 } 10395 10396 // Diagnose no_builtin attribute on function declaration that are not a 10397 // definition. 10398 // FIXME: We should really be doing this in 10399 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to 10400 // the FunctionDecl and at this point of the code 10401 // FunctionDecl::isThisDeclarationADefinition() which always returns `false` 10402 // because Sema::ActOnStartOfFunctionDef has not been called yet. 10403 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>()) 10404 switch (D.getFunctionDefinitionKind()) { 10405 case FunctionDefinitionKind::Defaulted: 10406 case FunctionDefinitionKind::Deleted: 10407 Diag(NBA->getLocation(), 10408 diag::err_attribute_no_builtin_on_defaulted_deleted_function) 10409 << NBA->getSpelling(); 10410 break; 10411 case FunctionDefinitionKind::Declaration: 10412 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition) 10413 << NBA->getSpelling(); 10414 break; 10415 case FunctionDefinitionKind::Definition: 10416 break; 10417 } 10418 10419 return NewFD; 10420 } 10421 10422 /// Return a CodeSegAttr from a containing class. The Microsoft docs say 10423 /// when __declspec(code_seg) "is applied to a class, all member functions of 10424 /// the class and nested classes -- this includes compiler-generated special 10425 /// member functions -- are put in the specified segment." 10426 /// The actual behavior is a little more complicated. The Microsoft compiler 10427 /// won't check outer classes if there is an active value from #pragma code_seg. 10428 /// The CodeSeg is always applied from the direct parent but only from outer 10429 /// classes when the #pragma code_seg stack is empty. See: 10430 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer 10431 /// available since MS has removed the page. 10432 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) { 10433 const auto *Method = dyn_cast<CXXMethodDecl>(FD); 10434 if (!Method) 10435 return nullptr; 10436 const CXXRecordDecl *Parent = Method->getParent(); 10437 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 10438 Attr *NewAttr = SAttr->clone(S.getASTContext()); 10439 NewAttr->setImplicit(true); 10440 return NewAttr; 10441 } 10442 10443 // The Microsoft compiler won't check outer classes for the CodeSeg 10444 // when the #pragma code_seg stack is active. 10445 if (S.CodeSegStack.CurrentValue) 10446 return nullptr; 10447 10448 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) { 10449 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 10450 Attr *NewAttr = SAttr->clone(S.getASTContext()); 10451 NewAttr->setImplicit(true); 10452 return NewAttr; 10453 } 10454 } 10455 return nullptr; 10456 } 10457 10458 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a 10459 /// containing class. Otherwise it will return implicit SectionAttr if the 10460 /// function is a definition and there is an active value on CodeSegStack 10461 /// (from the current #pragma code-seg value). 10462 /// 10463 /// \param FD Function being declared. 10464 /// \param IsDefinition Whether it is a definition or just a declarartion. 10465 /// \returns A CodeSegAttr or SectionAttr to apply to the function or 10466 /// nullptr if no attribute should be added. 10467 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, 10468 bool IsDefinition) { 10469 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD)) 10470 return A; 10471 if (!FD->hasAttr<SectionAttr>() && IsDefinition && 10472 CodeSegStack.CurrentValue) 10473 return SectionAttr::CreateImplicit( 10474 getASTContext(), CodeSegStack.CurrentValue->getString(), 10475 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 10476 SectionAttr::Declspec_allocate); 10477 return nullptr; 10478 } 10479 10480 /// Determines if we can perform a correct type check for \p D as a 10481 /// redeclaration of \p PrevDecl. If not, we can generally still perform a 10482 /// best-effort check. 10483 /// 10484 /// \param NewD The new declaration. 10485 /// \param OldD The old declaration. 10486 /// \param NewT The portion of the type of the new declaration to check. 10487 /// \param OldT The portion of the type of the old declaration to check. 10488 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, 10489 QualType NewT, QualType OldT) { 10490 if (!NewD->getLexicalDeclContext()->isDependentContext()) 10491 return true; 10492 10493 // For dependently-typed local extern declarations and friends, we can't 10494 // perform a correct type check in general until instantiation: 10495 // 10496 // int f(); 10497 // template<typename T> void g() { T f(); } 10498 // 10499 // (valid if g() is only instantiated with T = int). 10500 if (NewT->isDependentType() && 10501 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind())) 10502 return false; 10503 10504 // Similarly, if the previous declaration was a dependent local extern 10505 // declaration, we don't really know its type yet. 10506 if (OldT->isDependentType() && OldD->isLocalExternDecl()) 10507 return false; 10508 10509 return true; 10510 } 10511 10512 /// Checks if the new declaration declared in dependent context must be 10513 /// put in the same redeclaration chain as the specified declaration. 10514 /// 10515 /// \param D Declaration that is checked. 10516 /// \param PrevDecl Previous declaration found with proper lookup method for the 10517 /// same declaration name. 10518 /// \returns True if D must be added to the redeclaration chain which PrevDecl 10519 /// belongs to. 10520 /// 10521 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 10522 if (!D->getLexicalDeclContext()->isDependentContext()) 10523 return true; 10524 10525 // Don't chain dependent friend function definitions until instantiation, to 10526 // permit cases like 10527 // 10528 // void func(); 10529 // template<typename T> class C1 { friend void func() {} }; 10530 // template<typename T> class C2 { friend void func() {} }; 10531 // 10532 // ... which is valid if only one of C1 and C2 is ever instantiated. 10533 // 10534 // FIXME: This need only apply to function definitions. For now, we proxy 10535 // this by checking for a file-scope function. We do not want this to apply 10536 // to friend declarations nominating member functions, because that gets in 10537 // the way of access checks. 10538 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext()) 10539 return false; 10540 10541 auto *VD = dyn_cast<ValueDecl>(D); 10542 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl); 10543 return !VD || !PrevVD || 10544 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(), 10545 PrevVD->getType()); 10546 } 10547 10548 /// Check the target attribute of the function for MultiVersion 10549 /// validity. 10550 /// 10551 /// Returns true if there was an error, false otherwise. 10552 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { 10553 const auto *TA = FD->getAttr<TargetAttr>(); 10554 assert(TA && "MultiVersion Candidate requires a target attribute"); 10555 ParsedTargetAttr ParseInfo = TA->parse(); 10556 const TargetInfo &TargetInfo = S.Context.getTargetInfo(); 10557 enum ErrType { Feature = 0, Architecture = 1 }; 10558 10559 if (!ParseInfo.Architecture.empty() && 10560 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) { 10561 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10562 << Architecture << ParseInfo.Architecture; 10563 return true; 10564 } 10565 10566 for (const auto &Feat : ParseInfo.Features) { 10567 auto BareFeat = StringRef{Feat}.substr(1); 10568 if (Feat[0] == '-') { 10569 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10570 << Feature << ("no-" + BareFeat).str(); 10571 return true; 10572 } 10573 10574 if (!TargetInfo.validateCpuSupports(BareFeat) || 10575 !TargetInfo.isValidFeatureName(BareFeat)) { 10576 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 10577 << Feature << BareFeat; 10578 return true; 10579 } 10580 } 10581 return false; 10582 } 10583 10584 // Provide a white-list of attributes that are allowed to be combined with 10585 // multiversion functions. 10586 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, 10587 MultiVersionKind MVKind) { 10588 // Note: this list/diagnosis must match the list in 10589 // checkMultiversionAttributesAllSame. 10590 switch (Kind) { 10591 default: 10592 return false; 10593 case attr::Used: 10594 return MVKind == MultiVersionKind::Target; 10595 case attr::NonNull: 10596 case attr::NoThrow: 10597 return true; 10598 } 10599 } 10600 10601 static bool checkNonMultiVersionCompatAttributes(Sema &S, 10602 const FunctionDecl *FD, 10603 const FunctionDecl *CausedFD, 10604 MultiVersionKind MVKind) { 10605 const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) { 10606 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr) 10607 << static_cast<unsigned>(MVKind) << A; 10608 if (CausedFD) 10609 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here); 10610 return true; 10611 }; 10612 10613 for (const Attr *A : FD->attrs()) { 10614 switch (A->getKind()) { 10615 case attr::CPUDispatch: 10616 case attr::CPUSpecific: 10617 if (MVKind != MultiVersionKind::CPUDispatch && 10618 MVKind != MultiVersionKind::CPUSpecific) 10619 return Diagnose(S, A); 10620 break; 10621 case attr::Target: 10622 if (MVKind != MultiVersionKind::Target) 10623 return Diagnose(S, A); 10624 break; 10625 case attr::TargetClones: 10626 if (MVKind != MultiVersionKind::TargetClones) 10627 return Diagnose(S, A); 10628 break; 10629 default: 10630 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind)) 10631 return Diagnose(S, A); 10632 break; 10633 } 10634 } 10635 return false; 10636 } 10637 10638 bool Sema::areMultiversionVariantFunctionsCompatible( 10639 const FunctionDecl *OldFD, const FunctionDecl *NewFD, 10640 const PartialDiagnostic &NoProtoDiagID, 10641 const PartialDiagnosticAt &NoteCausedDiagIDAt, 10642 const PartialDiagnosticAt &NoSupportDiagIDAt, 10643 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, 10644 bool ConstexprSupported, bool CLinkageMayDiffer) { 10645 enum DoesntSupport { 10646 FuncTemplates = 0, 10647 VirtFuncs = 1, 10648 DeducedReturn = 2, 10649 Constructors = 3, 10650 Destructors = 4, 10651 DeletedFuncs = 5, 10652 DefaultedFuncs = 6, 10653 ConstexprFuncs = 7, 10654 ConstevalFuncs = 8, 10655 Lambda = 9, 10656 }; 10657 enum Different { 10658 CallingConv = 0, 10659 ReturnType = 1, 10660 ConstexprSpec = 2, 10661 InlineSpec = 3, 10662 Linkage = 4, 10663 LanguageLinkage = 5, 10664 }; 10665 10666 if (NoProtoDiagID.getDiagID() != 0 && OldFD && 10667 !OldFD->getType()->getAs<FunctionProtoType>()) { 10668 Diag(OldFD->getLocation(), NoProtoDiagID); 10669 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second); 10670 return true; 10671 } 10672 10673 if (NoProtoDiagID.getDiagID() != 0 && 10674 !NewFD->getType()->getAs<FunctionProtoType>()) 10675 return Diag(NewFD->getLocation(), NoProtoDiagID); 10676 10677 if (!TemplatesSupported && 10678 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 10679 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10680 << FuncTemplates; 10681 10682 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { 10683 if (NewCXXFD->isVirtual()) 10684 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10685 << VirtFuncs; 10686 10687 if (isa<CXXConstructorDecl>(NewCXXFD)) 10688 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10689 << Constructors; 10690 10691 if (isa<CXXDestructorDecl>(NewCXXFD)) 10692 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10693 << Destructors; 10694 } 10695 10696 if (NewFD->isDeleted()) 10697 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10698 << DeletedFuncs; 10699 10700 if (NewFD->isDefaulted()) 10701 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10702 << DefaultedFuncs; 10703 10704 if (!ConstexprSupported && NewFD->isConstexpr()) 10705 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10706 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs); 10707 10708 QualType NewQType = Context.getCanonicalType(NewFD->getType()); 10709 const auto *NewType = cast<FunctionType>(NewQType); 10710 QualType NewReturnType = NewType->getReturnType(); 10711 10712 if (NewReturnType->isUndeducedType()) 10713 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10714 << DeducedReturn; 10715 10716 // Ensure the return type is identical. 10717 if (OldFD) { 10718 QualType OldQType = Context.getCanonicalType(OldFD->getType()); 10719 const auto *OldType = cast<FunctionType>(OldQType); 10720 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 10721 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 10722 10723 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) 10724 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv; 10725 10726 QualType OldReturnType = OldType->getReturnType(); 10727 10728 if (OldReturnType != NewReturnType) 10729 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType; 10730 10731 if (OldFD->getConstexprKind() != NewFD->getConstexprKind()) 10732 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec; 10733 10734 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) 10735 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec; 10736 10737 if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage()) 10738 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage; 10739 10740 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC()) 10741 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage; 10742 10743 if (CheckEquivalentExceptionSpec( 10744 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), 10745 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) 10746 return true; 10747 } 10748 return false; 10749 } 10750 10751 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, 10752 const FunctionDecl *NewFD, 10753 bool CausesMV, 10754 MultiVersionKind MVKind) { 10755 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10756 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10757 if (OldFD) 10758 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10759 return true; 10760 } 10761 10762 bool IsCPUSpecificCPUDispatchMVKind = 10763 MVKind == MultiVersionKind::CPUDispatch || 10764 MVKind == MultiVersionKind::CPUSpecific; 10765 10766 if (CausesMV && OldFD && 10767 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind)) 10768 return true; 10769 10770 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind)) 10771 return true; 10772 10773 // Only allow transition to MultiVersion if it hasn't been used. 10774 if (OldFD && CausesMV && OldFD->isUsed(false)) 10775 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 10776 10777 return S.areMultiversionVariantFunctionsCompatible( 10778 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto), 10779 PartialDiagnosticAt(NewFD->getLocation(), 10780 S.PDiag(diag::note_multiversioning_caused_here)), 10781 PartialDiagnosticAt(NewFD->getLocation(), 10782 S.PDiag(diag::err_multiversion_doesnt_support) 10783 << static_cast<unsigned>(MVKind)), 10784 PartialDiagnosticAt(NewFD->getLocation(), 10785 S.PDiag(diag::err_multiversion_diff)), 10786 /*TemplatesSupported=*/false, 10787 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind, 10788 /*CLinkageMayDiffer=*/false); 10789 } 10790 10791 /// Check the validity of a multiversion function declaration that is the 10792 /// first of its kind. Also sets the multiversion'ness' of the function itself. 10793 /// 10794 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10795 /// 10796 /// Returns true if there was an error, false otherwise. 10797 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD, 10798 MultiVersionKind MVKind, 10799 const TargetAttr *TA) { 10800 assert(MVKind != MultiVersionKind::None && 10801 "Function lacks multiversion attribute"); 10802 10803 // Target only causes MV if it is default, otherwise this is a normal 10804 // function. 10805 if (MVKind == MultiVersionKind::Target && !TA->isDefaultVersion()) 10806 return false; 10807 10808 if (MVKind == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) { 10809 FD->setInvalidDecl(); 10810 return true; 10811 } 10812 10813 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) { 10814 FD->setInvalidDecl(); 10815 return true; 10816 } 10817 10818 FD->setIsMultiVersion(); 10819 return false; 10820 } 10821 10822 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) { 10823 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) { 10824 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None) 10825 return true; 10826 } 10827 10828 return false; 10829 } 10830 10831 static bool CheckTargetCausesMultiVersioning( 10832 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA, 10833 bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous) { 10834 const auto *OldTA = OldFD->getAttr<TargetAttr>(); 10835 ParsedTargetAttr NewParsed = NewTA->parse(); 10836 // Sort order doesn't matter, it just needs to be consistent. 10837 llvm::sort(NewParsed.Features); 10838 10839 // If the old decl is NOT MultiVersioned yet, and we don't cause that 10840 // to change, this is a simple redeclaration. 10841 if (!NewTA->isDefaultVersion() && 10842 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) 10843 return false; 10844 10845 // Otherwise, this decl causes MultiVersioning. 10846 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true, 10847 MultiVersionKind::Target)) { 10848 NewFD->setInvalidDecl(); 10849 return true; 10850 } 10851 10852 if (CheckMultiVersionValue(S, NewFD)) { 10853 NewFD->setInvalidDecl(); 10854 return true; 10855 } 10856 10857 // If this is 'default', permit the forward declaration. 10858 if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) { 10859 Redeclaration = true; 10860 OldDecl = OldFD; 10861 OldFD->setIsMultiVersion(); 10862 NewFD->setIsMultiVersion(); 10863 return false; 10864 } 10865 10866 if (CheckMultiVersionValue(S, OldFD)) { 10867 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10868 NewFD->setInvalidDecl(); 10869 return true; 10870 } 10871 10872 ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>()); 10873 10874 if (OldParsed == NewParsed) { 10875 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10876 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10877 NewFD->setInvalidDecl(); 10878 return true; 10879 } 10880 10881 for (const auto *FD : OldFD->redecls()) { 10882 const auto *CurTA = FD->getAttr<TargetAttr>(); 10883 // We allow forward declarations before ANY multiversioning attributes, but 10884 // nothing after the fact. 10885 if (PreviousDeclsHaveMultiVersionAttribute(FD) && 10886 (!CurTA || CurTA->isInherited())) { 10887 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl) 10888 << 0; 10889 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10890 NewFD->setInvalidDecl(); 10891 return true; 10892 } 10893 } 10894 10895 OldFD->setIsMultiVersion(); 10896 NewFD->setIsMultiVersion(); 10897 Redeclaration = false; 10898 OldDecl = nullptr; 10899 Previous.clear(); 10900 return false; 10901 } 10902 10903 static bool MultiVersionTypesCompatible(MultiVersionKind Old, 10904 MultiVersionKind New) { 10905 if (Old == New || Old == MultiVersionKind::None || 10906 New == MultiVersionKind::None) 10907 return true; 10908 10909 return (Old == MultiVersionKind::CPUDispatch && 10910 New == MultiVersionKind::CPUSpecific) || 10911 (Old == MultiVersionKind::CPUSpecific && 10912 New == MultiVersionKind::CPUDispatch); 10913 } 10914 10915 /// Check the validity of a new function declaration being added to an existing 10916 /// multiversioned declaration collection. 10917 static bool CheckMultiVersionAdditionalDecl( 10918 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, 10919 MultiVersionKind NewMVKind, const TargetAttr *NewTA, 10920 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, 10921 const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl, 10922 LookupResult &Previous) { 10923 10924 MultiVersionKind OldMVKind = OldFD->getMultiVersionKind(); 10925 // Disallow mixing of multiversioning types. 10926 if (!MultiVersionTypesCompatible(OldMVKind, NewMVKind)) { 10927 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10928 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10929 NewFD->setInvalidDecl(); 10930 return true; 10931 } 10932 10933 ParsedTargetAttr NewParsed; 10934 if (NewTA) { 10935 NewParsed = NewTA->parse(); 10936 llvm::sort(NewParsed.Features); 10937 } 10938 10939 bool UseMemberUsingDeclRules = 10940 S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); 10941 10942 bool MayNeedOverloadableChecks = 10943 AllowOverloadingOfFunction(Previous, S.Context, NewFD); 10944 10945 // Next, check ALL non-overloads to see if this is a redeclaration of a 10946 // previous member of the MultiVersion set. 10947 for (NamedDecl *ND : Previous) { 10948 FunctionDecl *CurFD = ND->getAsFunction(); 10949 if (!CurFD) 10950 continue; 10951 if (MayNeedOverloadableChecks && 10952 S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) 10953 continue; 10954 10955 switch (NewMVKind) { 10956 case MultiVersionKind::None: 10957 assert(OldMVKind == MultiVersionKind::TargetClones && 10958 "Only target_clones can be omitted in subsequent declarations"); 10959 break; 10960 case MultiVersionKind::Target: { 10961 const auto *CurTA = CurFD->getAttr<TargetAttr>(); 10962 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { 10963 NewFD->setIsMultiVersion(); 10964 Redeclaration = true; 10965 OldDecl = ND; 10966 return false; 10967 } 10968 10969 ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>()); 10970 if (CurParsed == NewParsed) { 10971 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10972 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10973 NewFD->setInvalidDecl(); 10974 return true; 10975 } 10976 break; 10977 } 10978 case MultiVersionKind::TargetClones: { 10979 const auto *CurClones = CurFD->getAttr<TargetClonesAttr>(); 10980 Redeclaration = true; 10981 OldDecl = CurFD; 10982 NewFD->setIsMultiVersion(); 10983 10984 if (CurClones && NewClones && 10985 (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() || 10986 !std::equal(CurClones->featuresStrs_begin(), 10987 CurClones->featuresStrs_end(), 10988 NewClones->featuresStrs_begin()))) { 10989 S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match); 10990 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10991 NewFD->setInvalidDecl(); 10992 return true; 10993 } 10994 10995 return false; 10996 } 10997 case MultiVersionKind::CPUSpecific: 10998 case MultiVersionKind::CPUDispatch: { 10999 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>(); 11000 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>(); 11001 // Handle CPUDispatch/CPUSpecific versions. 11002 // Only 1 CPUDispatch function is allowed, this will make it go through 11003 // the redeclaration errors. 11004 if (NewMVKind == MultiVersionKind::CPUDispatch && 11005 CurFD->hasAttr<CPUDispatchAttr>()) { 11006 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() && 11007 std::equal( 11008 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(), 11009 NewCPUDisp->cpus_begin(), 11010 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 11011 return Cur->getName() == New->getName(); 11012 })) { 11013 NewFD->setIsMultiVersion(); 11014 Redeclaration = true; 11015 OldDecl = ND; 11016 return false; 11017 } 11018 11019 // If the declarations don't match, this is an error condition. 11020 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch); 11021 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 11022 NewFD->setInvalidDecl(); 11023 return true; 11024 } 11025 if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) { 11026 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() && 11027 std::equal( 11028 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(), 11029 NewCPUSpec->cpus_begin(), 11030 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 11031 return Cur->getName() == New->getName(); 11032 })) { 11033 NewFD->setIsMultiVersion(); 11034 Redeclaration = true; 11035 OldDecl = ND; 11036 return false; 11037 } 11038 11039 // Only 1 version of CPUSpecific is allowed for each CPU. 11040 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) { 11041 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) { 11042 if (CurII == NewII) { 11043 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs) 11044 << NewII; 11045 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 11046 NewFD->setInvalidDecl(); 11047 return true; 11048 } 11049 } 11050 } 11051 } 11052 break; 11053 } 11054 } 11055 } 11056 11057 // Else, this is simply a non-redecl case. Checking the 'value' is only 11058 // necessary in the Target case, since The CPUSpecific/Dispatch cases are 11059 // handled in the attribute adding step. 11060 if (NewMVKind == MultiVersionKind::Target && 11061 CheckMultiVersionValue(S, NewFD)) { 11062 NewFD->setInvalidDecl(); 11063 return true; 11064 } 11065 11066 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, 11067 !OldFD->isMultiVersion(), NewMVKind)) { 11068 NewFD->setInvalidDecl(); 11069 return true; 11070 } 11071 11072 // Permit forward declarations in the case where these two are compatible. 11073 if (!OldFD->isMultiVersion()) { 11074 OldFD->setIsMultiVersion(); 11075 NewFD->setIsMultiVersion(); 11076 Redeclaration = true; 11077 OldDecl = OldFD; 11078 return false; 11079 } 11080 11081 NewFD->setIsMultiVersion(); 11082 Redeclaration = false; 11083 OldDecl = nullptr; 11084 Previous.clear(); 11085 return false; 11086 } 11087 11088 /// Check the validity of a mulitversion function declaration. 11089 /// Also sets the multiversion'ness' of the function itself. 11090 /// 11091 /// This sets NewFD->isInvalidDecl() to true if there was an error. 11092 /// 11093 /// Returns true if there was an error, false otherwise. 11094 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, 11095 bool &Redeclaration, NamedDecl *&OldDecl, 11096 LookupResult &Previous) { 11097 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 11098 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>(); 11099 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>(); 11100 const auto *NewClones = NewFD->getAttr<TargetClonesAttr>(); 11101 MultiVersionKind MVKind = NewFD->getMultiVersionKind(); 11102 11103 // Main isn't allowed to become a multiversion function, however it IS 11104 // permitted to have 'main' be marked with the 'target' optimization hint. 11105 if (NewFD->isMain()) { 11106 if (MVKind != MultiVersionKind::None && 11107 !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion())) { 11108 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); 11109 NewFD->setInvalidDecl(); 11110 return true; 11111 } 11112 return false; 11113 } 11114 11115 if (!OldDecl || !OldDecl->getAsFunction() || 11116 OldDecl->getDeclContext()->getRedeclContext() != 11117 NewFD->getDeclContext()->getRedeclContext()) { 11118 // If there's no previous declaration, AND this isn't attempting to cause 11119 // multiversioning, this isn't an error condition. 11120 if (MVKind == MultiVersionKind::None) 11121 return false; 11122 return CheckMultiVersionFirstFunction(S, NewFD, MVKind, NewTA); 11123 } 11124 11125 FunctionDecl *OldFD = OldDecl->getAsFunction(); 11126 11127 if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None) 11128 return false; 11129 11130 // Multiversioned redeclarations aren't allowed to omit the attribute, except 11131 // for target_clones. 11132 if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None && 11133 OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones) { 11134 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl) 11135 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target); 11136 NewFD->setInvalidDecl(); 11137 return true; 11138 } 11139 11140 if (!OldFD->isMultiVersion()) { 11141 switch (MVKind) { 11142 case MultiVersionKind::Target: 11143 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA, 11144 Redeclaration, OldDecl, Previous); 11145 case MultiVersionKind::TargetClones: 11146 if (OldFD->isUsed(false)) { 11147 NewFD->setInvalidDecl(); 11148 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 11149 } 11150 OldFD->setIsMultiVersion(); 11151 break; 11152 case MultiVersionKind::CPUDispatch: 11153 case MultiVersionKind::CPUSpecific: 11154 case MultiVersionKind::None: 11155 break; 11156 } 11157 } 11158 11159 // At this point, we have a multiversion function decl (in OldFD) AND an 11160 // appropriate attribute in the current function decl. Resolve that these are 11161 // still compatible with previous declarations. 11162 return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, MVKind, NewTA, 11163 NewCPUDisp, NewCPUSpec, NewClones, 11164 Redeclaration, OldDecl, Previous); 11165 } 11166 11167 /// Perform semantic checking of a new function declaration. 11168 /// 11169 /// Performs semantic analysis of the new function declaration 11170 /// NewFD. This routine performs all semantic checking that does not 11171 /// require the actual declarator involved in the declaration, and is 11172 /// used both for the declaration of functions as they are parsed 11173 /// (called via ActOnDeclarator) and for the declaration of functions 11174 /// that have been instantiated via C++ template instantiation (called 11175 /// via InstantiateDecl). 11176 /// 11177 /// \param IsMemberSpecialization whether this new function declaration is 11178 /// a member specialization (that replaces any definition provided by the 11179 /// previous declaration). 11180 /// 11181 /// This sets NewFD->isInvalidDecl() to true if there was an error. 11182 /// 11183 /// \returns true if the function declaration is a redeclaration. 11184 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 11185 LookupResult &Previous, 11186 bool IsMemberSpecialization, 11187 bool DeclIsDefn) { 11188 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 11189 "Variably modified return types are not handled here"); 11190 11191 // Determine whether the type of this function should be merged with 11192 // a previous visible declaration. This never happens for functions in C++, 11193 // and always happens in C if the previous declaration was visible. 11194 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 11195 !Previous.isShadowed(); 11196 11197 bool Redeclaration = false; 11198 NamedDecl *OldDecl = nullptr; 11199 bool MayNeedOverloadableChecks = false; 11200 11201 // Merge or overload the declaration with an existing declaration of 11202 // the same name, if appropriate. 11203 if (!Previous.empty()) { 11204 // Determine whether NewFD is an overload of PrevDecl or 11205 // a declaration that requires merging. If it's an overload, 11206 // there's no more work to do here; we'll just add the new 11207 // function to the scope. 11208 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { 11209 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 11210 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 11211 Redeclaration = true; 11212 OldDecl = Candidate; 11213 } 11214 } else { 11215 MayNeedOverloadableChecks = true; 11216 switch (CheckOverload(S, NewFD, Previous, OldDecl, 11217 /*NewIsUsingDecl*/ false)) { 11218 case Ovl_Match: 11219 Redeclaration = true; 11220 break; 11221 11222 case Ovl_NonFunction: 11223 Redeclaration = true; 11224 break; 11225 11226 case Ovl_Overload: 11227 Redeclaration = false; 11228 break; 11229 } 11230 } 11231 } 11232 11233 // Check for a previous extern "C" declaration with this name. 11234 if (!Redeclaration && 11235 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 11236 if (!Previous.empty()) { 11237 // This is an extern "C" declaration with the same name as a previous 11238 // declaration, and thus redeclares that entity... 11239 Redeclaration = true; 11240 OldDecl = Previous.getFoundDecl(); 11241 MergeTypeWithPrevious = false; 11242 11243 // ... except in the presence of __attribute__((overloadable)). 11244 if (OldDecl->hasAttr<OverloadableAttr>() || 11245 NewFD->hasAttr<OverloadableAttr>()) { 11246 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 11247 MayNeedOverloadableChecks = true; 11248 Redeclaration = false; 11249 OldDecl = nullptr; 11250 } 11251 } 11252 } 11253 } 11254 11255 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous)) 11256 return Redeclaration; 11257 11258 // PPC MMA non-pointer types are not allowed as function return types. 11259 if (Context.getTargetInfo().getTriple().isPPC64() && 11260 CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) { 11261 NewFD->setInvalidDecl(); 11262 } 11263 11264 // C++11 [dcl.constexpr]p8: 11265 // A constexpr specifier for a non-static member function that is not 11266 // a constructor declares that member function to be const. 11267 // 11268 // This needs to be delayed until we know whether this is an out-of-line 11269 // definition of a static member function. 11270 // 11271 // This rule is not present in C++1y, so we produce a backwards 11272 // compatibility warning whenever it happens in C++11. 11273 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 11274 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 11275 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 11276 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) { 11277 CXXMethodDecl *OldMD = nullptr; 11278 if (OldDecl) 11279 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 11280 if (!OldMD || !OldMD->isStatic()) { 11281 const FunctionProtoType *FPT = 11282 MD->getType()->castAs<FunctionProtoType>(); 11283 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 11284 EPI.TypeQuals.addConst(); 11285 MD->setType(Context.getFunctionType(FPT->getReturnType(), 11286 FPT->getParamTypes(), EPI)); 11287 11288 // Warn that we did this, if we're not performing template instantiation. 11289 // In that case, we'll have warned already when the template was defined. 11290 if (!inTemplateInstantiation()) { 11291 SourceLocation AddConstLoc; 11292 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 11293 .IgnoreParens().getAs<FunctionTypeLoc>()) 11294 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 11295 11296 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 11297 << FixItHint::CreateInsertion(AddConstLoc, " const"); 11298 } 11299 } 11300 } 11301 11302 if (Redeclaration) { 11303 // NewFD and OldDecl represent declarations that need to be 11304 // merged. 11305 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious, 11306 DeclIsDefn)) { 11307 NewFD->setInvalidDecl(); 11308 return Redeclaration; 11309 } 11310 11311 Previous.clear(); 11312 Previous.addDecl(OldDecl); 11313 11314 if (FunctionTemplateDecl *OldTemplateDecl = 11315 dyn_cast<FunctionTemplateDecl>(OldDecl)) { 11316 auto *OldFD = OldTemplateDecl->getTemplatedDecl(); 11317 FunctionTemplateDecl *NewTemplateDecl 11318 = NewFD->getDescribedFunctionTemplate(); 11319 assert(NewTemplateDecl && "Template/non-template mismatch"); 11320 11321 // The call to MergeFunctionDecl above may have created some state in 11322 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we 11323 // can add it as a redeclaration. 11324 NewTemplateDecl->mergePrevDecl(OldTemplateDecl); 11325 11326 NewFD->setPreviousDeclaration(OldFD); 11327 if (NewFD->isCXXClassMember()) { 11328 NewFD->setAccess(OldTemplateDecl->getAccess()); 11329 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 11330 } 11331 11332 // If this is an explicit specialization of a member that is a function 11333 // template, mark it as a member specialization. 11334 if (IsMemberSpecialization && 11335 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 11336 NewTemplateDecl->setMemberSpecialization(); 11337 assert(OldTemplateDecl->isMemberSpecialization()); 11338 // Explicit specializations of a member template do not inherit deleted 11339 // status from the parent member template that they are specializing. 11340 if (OldFD->isDeleted()) { 11341 // FIXME: This assert will not hold in the presence of modules. 11342 assert(OldFD->getCanonicalDecl() == OldFD); 11343 // FIXME: We need an update record for this AST mutation. 11344 OldFD->setDeletedAsWritten(false); 11345 } 11346 } 11347 11348 } else { 11349 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 11350 auto *OldFD = cast<FunctionDecl>(OldDecl); 11351 // This needs to happen first so that 'inline' propagates. 11352 NewFD->setPreviousDeclaration(OldFD); 11353 if (NewFD->isCXXClassMember()) 11354 NewFD->setAccess(OldFD->getAccess()); 11355 } 11356 } 11357 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && 11358 !NewFD->getAttr<OverloadableAttr>()) { 11359 assert((Previous.empty() || 11360 llvm::any_of(Previous, 11361 [](const NamedDecl *ND) { 11362 return ND->hasAttr<OverloadableAttr>(); 11363 })) && 11364 "Non-redecls shouldn't happen without overloadable present"); 11365 11366 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { 11367 const auto *FD = dyn_cast<FunctionDecl>(ND); 11368 return FD && !FD->hasAttr<OverloadableAttr>(); 11369 }); 11370 11371 if (OtherUnmarkedIter != Previous.end()) { 11372 Diag(NewFD->getLocation(), 11373 diag::err_attribute_overloadable_multiple_unmarked_overloads); 11374 Diag((*OtherUnmarkedIter)->getLocation(), 11375 diag::note_attribute_overloadable_prev_overload) 11376 << false; 11377 11378 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 11379 } 11380 } 11381 11382 if (LangOpts.OpenMP) 11383 ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD); 11384 11385 // Semantic checking for this function declaration (in isolation). 11386 11387 if (getLangOpts().CPlusPlus) { 11388 // C++-specific checks. 11389 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 11390 CheckConstructor(Constructor); 11391 } else if (CXXDestructorDecl *Destructor = 11392 dyn_cast<CXXDestructorDecl>(NewFD)) { 11393 CXXRecordDecl *Record = Destructor->getParent(); 11394 QualType ClassType = Context.getTypeDeclType(Record); 11395 11396 // FIXME: Shouldn't we be able to perform this check even when the class 11397 // type is dependent? Both gcc and edg can handle that. 11398 if (!ClassType->isDependentType()) { 11399 DeclarationName Name 11400 = Context.DeclarationNames.getCXXDestructorName( 11401 Context.getCanonicalType(ClassType)); 11402 if (NewFD->getDeclName() != Name) { 11403 Diag(NewFD->getLocation(), diag::err_destructor_name); 11404 NewFD->setInvalidDecl(); 11405 return Redeclaration; 11406 } 11407 } 11408 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 11409 if (auto *TD = Guide->getDescribedFunctionTemplate()) 11410 CheckDeductionGuideTemplate(TD); 11411 11412 // A deduction guide is not on the list of entities that can be 11413 // explicitly specialized. 11414 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 11415 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized) 11416 << /*explicit specialization*/ 1; 11417 } 11418 11419 // Find any virtual functions that this function overrides. 11420 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 11421 if (!Method->isFunctionTemplateSpecialization() && 11422 !Method->getDescribedFunctionTemplate() && 11423 Method->isCanonicalDecl()) { 11424 AddOverriddenMethods(Method->getParent(), Method); 11425 } 11426 if (Method->isVirtual() && NewFD->getTrailingRequiresClause()) 11427 // C++2a [class.virtual]p6 11428 // A virtual method shall not have a requires-clause. 11429 Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(), 11430 diag::err_constrained_virtual_method); 11431 11432 if (Method->isStatic()) 11433 checkThisInStaticMemberFunctionType(Method); 11434 } 11435 11436 // C++20: dcl.decl.general p4: 11437 // The optional requires-clause ([temp.pre]) in an init-declarator or 11438 // member-declarator shall be present only if the declarator declares a 11439 // templated function ([dcl.fct]). 11440 if (Expr *TRC = NewFD->getTrailingRequiresClause()) { 11441 if (!NewFD->isTemplated() && !NewFD->isTemplateInstantiation()) 11442 Diag(TRC->getBeginLoc(), diag::err_constrained_non_templated_function); 11443 } 11444 11445 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD)) 11446 ActOnConversionDeclarator(Conversion); 11447 11448 // Extra checking for C++ overloaded operators (C++ [over.oper]). 11449 if (NewFD->isOverloadedOperator() && 11450 CheckOverloadedOperatorDeclaration(NewFD)) { 11451 NewFD->setInvalidDecl(); 11452 return Redeclaration; 11453 } 11454 11455 // Extra checking for C++0x literal operators (C++0x [over.literal]). 11456 if (NewFD->getLiteralIdentifier() && 11457 CheckLiteralOperatorDeclaration(NewFD)) { 11458 NewFD->setInvalidDecl(); 11459 return Redeclaration; 11460 } 11461 11462 // In C++, check default arguments now that we have merged decls. Unless 11463 // the lexical context is the class, because in this case this is done 11464 // during delayed parsing anyway. 11465 if (!CurContext->isRecord()) 11466 CheckCXXDefaultArguments(NewFD); 11467 11468 // If this function is declared as being extern "C", then check to see if 11469 // the function returns a UDT (class, struct, or union type) that is not C 11470 // compatible, and if it does, warn the user. 11471 // But, issue any diagnostic on the first declaration only. 11472 if (Previous.empty() && NewFD->isExternC()) { 11473 QualType R = NewFD->getReturnType(); 11474 if (R->isIncompleteType() && !R->isVoidType()) 11475 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 11476 << NewFD << R; 11477 else if (!R.isPODType(Context) && !R->isVoidType() && 11478 !R->isObjCObjectPointerType()) 11479 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 11480 } 11481 11482 // C++1z [dcl.fct]p6: 11483 // [...] whether the function has a non-throwing exception-specification 11484 // [is] part of the function type 11485 // 11486 // This results in an ABI break between C++14 and C++17 for functions whose 11487 // declared type includes an exception-specification in a parameter or 11488 // return type. (Exception specifications on the function itself are OK in 11489 // most cases, and exception specifications are not permitted in most other 11490 // contexts where they could make it into a mangling.) 11491 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { 11492 auto HasNoexcept = [&](QualType T) -> bool { 11493 // Strip off declarator chunks that could be between us and a function 11494 // type. We don't need to look far, exception specifications are very 11495 // restricted prior to C++17. 11496 if (auto *RT = T->getAs<ReferenceType>()) 11497 T = RT->getPointeeType(); 11498 else if (T->isAnyPointerType()) 11499 T = T->getPointeeType(); 11500 else if (auto *MPT = T->getAs<MemberPointerType>()) 11501 T = MPT->getPointeeType(); 11502 if (auto *FPT = T->getAs<FunctionProtoType>()) 11503 if (FPT->isNothrow()) 11504 return true; 11505 return false; 11506 }; 11507 11508 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 11509 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 11510 for (QualType T : FPT->param_types()) 11511 AnyNoexcept |= HasNoexcept(T); 11512 if (AnyNoexcept) 11513 Diag(NewFD->getLocation(), 11514 diag::warn_cxx17_compat_exception_spec_in_signature) 11515 << NewFD; 11516 } 11517 11518 if (!Redeclaration && LangOpts.CUDA) 11519 checkCUDATargetOverload(NewFD, Previous); 11520 } 11521 return Redeclaration; 11522 } 11523 11524 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 11525 // C++11 [basic.start.main]p3: 11526 // A program that [...] declares main to be inline, static or 11527 // constexpr is ill-formed. 11528 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 11529 // appear in a declaration of main. 11530 // static main is not an error under C99, but we should warn about it. 11531 // We accept _Noreturn main as an extension. 11532 if (FD->getStorageClass() == SC_Static) 11533 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 11534 ? diag::err_static_main : diag::warn_static_main) 11535 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 11536 if (FD->isInlineSpecified()) 11537 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 11538 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 11539 if (DS.isNoreturnSpecified()) { 11540 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 11541 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 11542 Diag(NoreturnLoc, diag::ext_noreturn_main); 11543 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 11544 << FixItHint::CreateRemoval(NoreturnRange); 11545 } 11546 if (FD->isConstexpr()) { 11547 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 11548 << FD->isConsteval() 11549 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 11550 FD->setConstexprKind(ConstexprSpecKind::Unspecified); 11551 } 11552 11553 if (getLangOpts().OpenCL) { 11554 Diag(FD->getLocation(), diag::err_opencl_no_main) 11555 << FD->hasAttr<OpenCLKernelAttr>(); 11556 FD->setInvalidDecl(); 11557 return; 11558 } 11559 11560 // Functions named main in hlsl are default entries, but don't have specific 11561 // signatures they are required to conform to. 11562 if (getLangOpts().HLSL) 11563 return; 11564 11565 QualType T = FD->getType(); 11566 assert(T->isFunctionType() && "function decl is not of function type"); 11567 const FunctionType* FT = T->castAs<FunctionType>(); 11568 11569 // Set default calling convention for main() 11570 if (FT->getCallConv() != CC_C) { 11571 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); 11572 FD->setType(QualType(FT, 0)); 11573 T = Context.getCanonicalType(FD->getType()); 11574 } 11575 11576 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 11577 // In C with GNU extensions we allow main() to have non-integer return 11578 // type, but we should warn about the extension, and we disable the 11579 // implicit-return-zero rule. 11580 11581 // GCC in C mode accepts qualified 'int'. 11582 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 11583 FD->setHasImplicitReturnZero(true); 11584 else { 11585 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 11586 SourceRange RTRange = FD->getReturnTypeSourceRange(); 11587 if (RTRange.isValid()) 11588 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 11589 << FixItHint::CreateReplacement(RTRange, "int"); 11590 } 11591 } else { 11592 // In C and C++, main magically returns 0 if you fall off the end; 11593 // set the flag which tells us that. 11594 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 11595 11596 // All the standards say that main() should return 'int'. 11597 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 11598 FD->setHasImplicitReturnZero(true); 11599 else { 11600 // Otherwise, this is just a flat-out error. 11601 SourceRange RTRange = FD->getReturnTypeSourceRange(); 11602 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 11603 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 11604 : FixItHint()); 11605 FD->setInvalidDecl(true); 11606 } 11607 } 11608 11609 // Treat protoless main() as nullary. 11610 if (isa<FunctionNoProtoType>(FT)) return; 11611 11612 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 11613 unsigned nparams = FTP->getNumParams(); 11614 assert(FD->getNumParams() == nparams); 11615 11616 bool HasExtraParameters = (nparams > 3); 11617 11618 if (FTP->isVariadic()) { 11619 Diag(FD->getLocation(), diag::ext_variadic_main); 11620 // FIXME: if we had information about the location of the ellipsis, we 11621 // could add a FixIt hint to remove it as a parameter. 11622 } 11623 11624 // Darwin passes an undocumented fourth argument of type char**. If 11625 // other platforms start sprouting these, the logic below will start 11626 // getting shifty. 11627 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 11628 HasExtraParameters = false; 11629 11630 if (HasExtraParameters) { 11631 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 11632 FD->setInvalidDecl(true); 11633 nparams = 3; 11634 } 11635 11636 // FIXME: a lot of the following diagnostics would be improved 11637 // if we had some location information about types. 11638 11639 QualType CharPP = 11640 Context.getPointerType(Context.getPointerType(Context.CharTy)); 11641 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 11642 11643 for (unsigned i = 0; i < nparams; ++i) { 11644 QualType AT = FTP->getParamType(i); 11645 11646 bool mismatch = true; 11647 11648 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 11649 mismatch = false; 11650 else if (Expected[i] == CharPP) { 11651 // As an extension, the following forms are okay: 11652 // char const ** 11653 // char const * const * 11654 // char * const * 11655 11656 QualifierCollector qs; 11657 const PointerType* PT; 11658 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 11659 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 11660 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 11661 Context.CharTy)) { 11662 qs.removeConst(); 11663 mismatch = !qs.empty(); 11664 } 11665 } 11666 11667 if (mismatch) { 11668 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 11669 // TODO: suggest replacing given type with expected type 11670 FD->setInvalidDecl(true); 11671 } 11672 } 11673 11674 if (nparams == 1 && !FD->isInvalidDecl()) { 11675 Diag(FD->getLocation(), diag::warn_main_one_arg); 11676 } 11677 11678 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11679 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11680 FD->setInvalidDecl(); 11681 } 11682 } 11683 11684 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) { 11685 11686 // Default calling convention for main and wmain is __cdecl 11687 if (FD->getName() == "main" || FD->getName() == "wmain") 11688 return false; 11689 11690 // Default calling convention for MinGW is __cdecl 11691 const llvm::Triple &T = S.Context.getTargetInfo().getTriple(); 11692 if (T.isWindowsGNUEnvironment()) 11693 return false; 11694 11695 // Default calling convention for WinMain, wWinMain and DllMain 11696 // is __stdcall on 32 bit Windows 11697 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86) 11698 return true; 11699 11700 return false; 11701 } 11702 11703 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 11704 QualType T = FD->getType(); 11705 assert(T->isFunctionType() && "function decl is not of function type"); 11706 const FunctionType *FT = T->castAs<FunctionType>(); 11707 11708 // Set an implicit return of 'zero' if the function can return some integral, 11709 // enumeration, pointer or nullptr type. 11710 if (FT->getReturnType()->isIntegralOrEnumerationType() || 11711 FT->getReturnType()->isAnyPointerType() || 11712 FT->getReturnType()->isNullPtrType()) 11713 // DllMain is exempt because a return value of zero means it failed. 11714 if (FD->getName() != "DllMain") 11715 FD->setHasImplicitReturnZero(true); 11716 11717 // Explicity specified calling conventions are applied to MSVC entry points 11718 if (!hasExplicitCallingConv(T)) { 11719 if (isDefaultStdCall(FD, *this)) { 11720 if (FT->getCallConv() != CC_X86StdCall) { 11721 FT = Context.adjustFunctionType( 11722 FT, FT->getExtInfo().withCallingConv(CC_X86StdCall)); 11723 FD->setType(QualType(FT, 0)); 11724 } 11725 } else if (FT->getCallConv() != CC_C) { 11726 FT = Context.adjustFunctionType(FT, 11727 FT->getExtInfo().withCallingConv(CC_C)); 11728 FD->setType(QualType(FT, 0)); 11729 } 11730 } 11731 11732 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11733 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11734 FD->setInvalidDecl(); 11735 } 11736 } 11737 11738 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 11739 // FIXME: Need strict checking. In C89, we need to check for 11740 // any assignment, increment, decrement, function-calls, or 11741 // commas outside of a sizeof. In C99, it's the same list, 11742 // except that the aforementioned are allowed in unevaluated 11743 // expressions. Everything else falls under the 11744 // "may accept other forms of constant expressions" exception. 11745 // 11746 // Regular C++ code will not end up here (exceptions: language extensions, 11747 // OpenCL C++ etc), so the constant expression rules there don't matter. 11748 if (Init->isValueDependent()) { 11749 assert(Init->containsErrors() && 11750 "Dependent code should only occur in error-recovery path."); 11751 return true; 11752 } 11753 const Expr *Culprit; 11754 if (Init->isConstantInitializer(Context, false, &Culprit)) 11755 return false; 11756 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 11757 << Culprit->getSourceRange(); 11758 return true; 11759 } 11760 11761 namespace { 11762 // Visits an initialization expression to see if OrigDecl is evaluated in 11763 // its own initialization and throws a warning if it does. 11764 class SelfReferenceChecker 11765 : public EvaluatedExprVisitor<SelfReferenceChecker> { 11766 Sema &S; 11767 Decl *OrigDecl; 11768 bool isRecordType; 11769 bool isPODType; 11770 bool isReferenceType; 11771 11772 bool isInitList; 11773 llvm::SmallVector<unsigned, 4> InitFieldIndex; 11774 11775 public: 11776 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 11777 11778 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 11779 S(S), OrigDecl(OrigDecl) { 11780 isPODType = false; 11781 isRecordType = false; 11782 isReferenceType = false; 11783 isInitList = false; 11784 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 11785 isPODType = VD->getType().isPODType(S.Context); 11786 isRecordType = VD->getType()->isRecordType(); 11787 isReferenceType = VD->getType()->isReferenceType(); 11788 } 11789 } 11790 11791 // For most expressions, just call the visitor. For initializer lists, 11792 // track the index of the field being initialized since fields are 11793 // initialized in order allowing use of previously initialized fields. 11794 void CheckExpr(Expr *E) { 11795 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 11796 if (!InitList) { 11797 Visit(E); 11798 return; 11799 } 11800 11801 // Track and increment the index here. 11802 isInitList = true; 11803 InitFieldIndex.push_back(0); 11804 for (auto Child : InitList->children()) { 11805 CheckExpr(cast<Expr>(Child)); 11806 ++InitFieldIndex.back(); 11807 } 11808 InitFieldIndex.pop_back(); 11809 } 11810 11811 // Returns true if MemberExpr is checked and no further checking is needed. 11812 // Returns false if additional checking is required. 11813 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 11814 llvm::SmallVector<FieldDecl*, 4> Fields; 11815 Expr *Base = E; 11816 bool ReferenceField = false; 11817 11818 // Get the field members used. 11819 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11820 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 11821 if (!FD) 11822 return false; 11823 Fields.push_back(FD); 11824 if (FD->getType()->isReferenceType()) 11825 ReferenceField = true; 11826 Base = ME->getBase()->IgnoreParenImpCasts(); 11827 } 11828 11829 // Keep checking only if the base Decl is the same. 11830 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 11831 if (!DRE || DRE->getDecl() != OrigDecl) 11832 return false; 11833 11834 // A reference field can be bound to an unininitialized field. 11835 if (CheckReference && !ReferenceField) 11836 return true; 11837 11838 // Convert FieldDecls to their index number. 11839 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 11840 for (const FieldDecl *I : llvm::reverse(Fields)) 11841 UsedFieldIndex.push_back(I->getFieldIndex()); 11842 11843 // See if a warning is needed by checking the first difference in index 11844 // numbers. If field being used has index less than the field being 11845 // initialized, then the use is safe. 11846 for (auto UsedIter = UsedFieldIndex.begin(), 11847 UsedEnd = UsedFieldIndex.end(), 11848 OrigIter = InitFieldIndex.begin(), 11849 OrigEnd = InitFieldIndex.end(); 11850 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 11851 if (*UsedIter < *OrigIter) 11852 return true; 11853 if (*UsedIter > *OrigIter) 11854 break; 11855 } 11856 11857 // TODO: Add a different warning which will print the field names. 11858 HandleDeclRefExpr(DRE); 11859 return true; 11860 } 11861 11862 // For most expressions, the cast is directly above the DeclRefExpr. 11863 // For conditional operators, the cast can be outside the conditional 11864 // operator if both expressions are DeclRefExpr's. 11865 void HandleValue(Expr *E) { 11866 E = E->IgnoreParens(); 11867 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 11868 HandleDeclRefExpr(DRE); 11869 return; 11870 } 11871 11872 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 11873 Visit(CO->getCond()); 11874 HandleValue(CO->getTrueExpr()); 11875 HandleValue(CO->getFalseExpr()); 11876 return; 11877 } 11878 11879 if (BinaryConditionalOperator *BCO = 11880 dyn_cast<BinaryConditionalOperator>(E)) { 11881 Visit(BCO->getCond()); 11882 HandleValue(BCO->getFalseExpr()); 11883 return; 11884 } 11885 11886 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 11887 HandleValue(OVE->getSourceExpr()); 11888 return; 11889 } 11890 11891 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11892 if (BO->getOpcode() == BO_Comma) { 11893 Visit(BO->getLHS()); 11894 HandleValue(BO->getRHS()); 11895 return; 11896 } 11897 } 11898 11899 if (isa<MemberExpr>(E)) { 11900 if (isInitList) { 11901 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 11902 false /*CheckReference*/)) 11903 return; 11904 } 11905 11906 Expr *Base = E->IgnoreParenImpCasts(); 11907 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11908 // Check for static member variables and don't warn on them. 11909 if (!isa<FieldDecl>(ME->getMemberDecl())) 11910 return; 11911 Base = ME->getBase()->IgnoreParenImpCasts(); 11912 } 11913 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 11914 HandleDeclRefExpr(DRE); 11915 return; 11916 } 11917 11918 Visit(E); 11919 } 11920 11921 // Reference types not handled in HandleValue are handled here since all 11922 // uses of references are bad, not just r-value uses. 11923 void VisitDeclRefExpr(DeclRefExpr *E) { 11924 if (isReferenceType) 11925 HandleDeclRefExpr(E); 11926 } 11927 11928 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 11929 if (E->getCastKind() == CK_LValueToRValue) { 11930 HandleValue(E->getSubExpr()); 11931 return; 11932 } 11933 11934 Inherited::VisitImplicitCastExpr(E); 11935 } 11936 11937 void VisitMemberExpr(MemberExpr *E) { 11938 if (isInitList) { 11939 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 11940 return; 11941 } 11942 11943 // Don't warn on arrays since they can be treated as pointers. 11944 if (E->getType()->canDecayToPointerType()) return; 11945 11946 // Warn when a non-static method call is followed by non-static member 11947 // field accesses, which is followed by a DeclRefExpr. 11948 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 11949 bool Warn = (MD && !MD->isStatic()); 11950 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 11951 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11952 if (!isa<FieldDecl>(ME->getMemberDecl())) 11953 Warn = false; 11954 Base = ME->getBase()->IgnoreParenImpCasts(); 11955 } 11956 11957 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 11958 if (Warn) 11959 HandleDeclRefExpr(DRE); 11960 return; 11961 } 11962 11963 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 11964 // Visit that expression. 11965 Visit(Base); 11966 } 11967 11968 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 11969 Expr *Callee = E->getCallee(); 11970 11971 if (isa<UnresolvedLookupExpr>(Callee)) 11972 return Inherited::VisitCXXOperatorCallExpr(E); 11973 11974 Visit(Callee); 11975 for (auto Arg: E->arguments()) 11976 HandleValue(Arg->IgnoreParenImpCasts()); 11977 } 11978 11979 void VisitUnaryOperator(UnaryOperator *E) { 11980 // For POD record types, addresses of its own members are well-defined. 11981 if (E->getOpcode() == UO_AddrOf && isRecordType && 11982 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 11983 if (!isPODType) 11984 HandleValue(E->getSubExpr()); 11985 return; 11986 } 11987 11988 if (E->isIncrementDecrementOp()) { 11989 HandleValue(E->getSubExpr()); 11990 return; 11991 } 11992 11993 Inherited::VisitUnaryOperator(E); 11994 } 11995 11996 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 11997 11998 void VisitCXXConstructExpr(CXXConstructExpr *E) { 11999 if (E->getConstructor()->isCopyConstructor()) { 12000 Expr *ArgExpr = E->getArg(0); 12001 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 12002 if (ILE->getNumInits() == 1) 12003 ArgExpr = ILE->getInit(0); 12004 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 12005 if (ICE->getCastKind() == CK_NoOp) 12006 ArgExpr = ICE->getSubExpr(); 12007 HandleValue(ArgExpr); 12008 return; 12009 } 12010 Inherited::VisitCXXConstructExpr(E); 12011 } 12012 12013 void VisitCallExpr(CallExpr *E) { 12014 // Treat std::move as a use. 12015 if (E->isCallToStdMove()) { 12016 HandleValue(E->getArg(0)); 12017 return; 12018 } 12019 12020 Inherited::VisitCallExpr(E); 12021 } 12022 12023 void VisitBinaryOperator(BinaryOperator *E) { 12024 if (E->isCompoundAssignmentOp()) { 12025 HandleValue(E->getLHS()); 12026 Visit(E->getRHS()); 12027 return; 12028 } 12029 12030 Inherited::VisitBinaryOperator(E); 12031 } 12032 12033 // A custom visitor for BinaryConditionalOperator is needed because the 12034 // regular visitor would check the condition and true expression separately 12035 // but both point to the same place giving duplicate diagnostics. 12036 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 12037 Visit(E->getCond()); 12038 Visit(E->getFalseExpr()); 12039 } 12040 12041 void HandleDeclRefExpr(DeclRefExpr *DRE) { 12042 Decl* ReferenceDecl = DRE->getDecl(); 12043 if (OrigDecl != ReferenceDecl) return; 12044 unsigned diag; 12045 if (isReferenceType) { 12046 diag = diag::warn_uninit_self_reference_in_reference_init; 12047 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 12048 diag = diag::warn_static_self_reference_in_init; 12049 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 12050 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 12051 DRE->getDecl()->getType()->isRecordType()) { 12052 diag = diag::warn_uninit_self_reference_in_init; 12053 } else { 12054 // Local variables will be handled by the CFG analysis. 12055 return; 12056 } 12057 12058 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE, 12059 S.PDiag(diag) 12060 << DRE->getDecl() << OrigDecl->getLocation() 12061 << DRE->getSourceRange()); 12062 } 12063 }; 12064 12065 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 12066 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 12067 bool DirectInit) { 12068 // Parameters arguments are occassionially constructed with itself, 12069 // for instance, in recursive functions. Skip them. 12070 if (isa<ParmVarDecl>(OrigDecl)) 12071 return; 12072 12073 E = E->IgnoreParens(); 12074 12075 // Skip checking T a = a where T is not a record or reference type. 12076 // Doing so is a way to silence uninitialized warnings. 12077 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 12078 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 12079 if (ICE->getCastKind() == CK_LValueToRValue) 12080 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 12081 if (DRE->getDecl() == OrigDecl) 12082 return; 12083 12084 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 12085 } 12086 } // end anonymous namespace 12087 12088 namespace { 12089 // Simple wrapper to add the name of a variable or (if no variable is 12090 // available) a DeclarationName into a diagnostic. 12091 struct VarDeclOrName { 12092 VarDecl *VDecl; 12093 DeclarationName Name; 12094 12095 friend const Sema::SemaDiagnosticBuilder & 12096 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 12097 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 12098 } 12099 }; 12100 } // end anonymous namespace 12101 12102 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 12103 DeclarationName Name, QualType Type, 12104 TypeSourceInfo *TSI, 12105 SourceRange Range, bool DirectInit, 12106 Expr *Init) { 12107 bool IsInitCapture = !VDecl; 12108 assert((!VDecl || !VDecl->isInitCapture()) && 12109 "init captures are expected to be deduced prior to initialization"); 12110 12111 VarDeclOrName VN{VDecl, Name}; 12112 12113 DeducedType *Deduced = Type->getContainedDeducedType(); 12114 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 12115 12116 // C++11 [dcl.spec.auto]p3 12117 if (!Init) { 12118 assert(VDecl && "no init for init capture deduction?"); 12119 12120 // Except for class argument deduction, and then for an initializing 12121 // declaration only, i.e. no static at class scope or extern. 12122 if (!isa<DeducedTemplateSpecializationType>(Deduced) || 12123 VDecl->hasExternalStorage() || 12124 VDecl->isStaticDataMember()) { 12125 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 12126 << VDecl->getDeclName() << Type; 12127 return QualType(); 12128 } 12129 } 12130 12131 ArrayRef<Expr*> DeduceInits; 12132 if (Init) 12133 DeduceInits = Init; 12134 12135 if (DirectInit) { 12136 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) 12137 DeduceInits = PL->exprs(); 12138 } 12139 12140 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 12141 assert(VDecl && "non-auto type for init capture deduction?"); 12142 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 12143 InitializationKind Kind = InitializationKind::CreateForInit( 12144 VDecl->getLocation(), DirectInit, Init); 12145 // FIXME: Initialization should not be taking a mutable list of inits. 12146 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 12147 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 12148 InitsCopy); 12149 } 12150 12151 if (DirectInit) { 12152 if (auto *IL = dyn_cast<InitListExpr>(Init)) 12153 DeduceInits = IL->inits(); 12154 } 12155 12156 // Deduction only works if we have exactly one source expression. 12157 if (DeduceInits.empty()) { 12158 // It isn't possible to write this directly, but it is possible to 12159 // end up in this situation with "auto x(some_pack...);" 12160 Diag(Init->getBeginLoc(), IsInitCapture 12161 ? diag::err_init_capture_no_expression 12162 : diag::err_auto_var_init_no_expression) 12163 << VN << Type << Range; 12164 return QualType(); 12165 } 12166 12167 if (DeduceInits.size() > 1) { 12168 Diag(DeduceInits[1]->getBeginLoc(), 12169 IsInitCapture ? diag::err_init_capture_multiple_expressions 12170 : diag::err_auto_var_init_multiple_expressions) 12171 << VN << Type << Range; 12172 return QualType(); 12173 } 12174 12175 Expr *DeduceInit = DeduceInits[0]; 12176 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 12177 Diag(Init->getBeginLoc(), IsInitCapture 12178 ? diag::err_init_capture_paren_braces 12179 : diag::err_auto_var_init_paren_braces) 12180 << isa<InitListExpr>(Init) << VN << Type << Range; 12181 return QualType(); 12182 } 12183 12184 // Expressions default to 'id' when we're in a debugger. 12185 bool DefaultedAnyToId = false; 12186 if (getLangOpts().DebuggerCastResultToId && 12187 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 12188 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 12189 if (Result.isInvalid()) { 12190 return QualType(); 12191 } 12192 Init = Result.get(); 12193 DefaultedAnyToId = true; 12194 } 12195 12196 // C++ [dcl.decomp]p1: 12197 // If the assignment-expression [...] has array type A and no ref-qualifier 12198 // is present, e has type cv A 12199 if (VDecl && isa<DecompositionDecl>(VDecl) && 12200 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 12201 DeduceInit->getType()->isConstantArrayType()) 12202 return Context.getQualifiedType(DeduceInit->getType(), 12203 Type.getQualifiers()); 12204 12205 QualType DeducedType; 12206 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 12207 if (!IsInitCapture) 12208 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 12209 else if (isa<InitListExpr>(Init)) 12210 Diag(Range.getBegin(), 12211 diag::err_init_capture_deduction_failure_from_init_list) 12212 << VN 12213 << (DeduceInit->getType().isNull() ? TSI->getType() 12214 : DeduceInit->getType()) 12215 << DeduceInit->getSourceRange(); 12216 else 12217 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 12218 << VN << TSI->getType() 12219 << (DeduceInit->getType().isNull() ? TSI->getType() 12220 : DeduceInit->getType()) 12221 << DeduceInit->getSourceRange(); 12222 } 12223 12224 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 12225 // 'id' instead of a specific object type prevents most of our usual 12226 // checks. 12227 // We only want to warn outside of template instantiations, though: 12228 // inside a template, the 'id' could have come from a parameter. 12229 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 12230 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 12231 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 12232 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 12233 } 12234 12235 return DeducedType; 12236 } 12237 12238 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 12239 Expr *Init) { 12240 assert(!Init || !Init->containsErrors()); 12241 QualType DeducedType = deduceVarTypeFromInitializer( 12242 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 12243 VDecl->getSourceRange(), DirectInit, Init); 12244 if (DeducedType.isNull()) { 12245 VDecl->setInvalidDecl(); 12246 return true; 12247 } 12248 12249 VDecl->setType(DeducedType); 12250 assert(VDecl->isLinkageValid()); 12251 12252 // In ARC, infer lifetime. 12253 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 12254 VDecl->setInvalidDecl(); 12255 12256 if (getLangOpts().OpenCL) 12257 deduceOpenCLAddressSpace(VDecl); 12258 12259 // If this is a redeclaration, check that the type we just deduced matches 12260 // the previously declared type. 12261 if (VarDecl *Old = VDecl->getPreviousDecl()) { 12262 // We never need to merge the type, because we cannot form an incomplete 12263 // array of auto, nor deduce such a type. 12264 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 12265 } 12266 12267 // Check the deduced type is valid for a variable declaration. 12268 CheckVariableDeclarationType(VDecl); 12269 return VDecl->isInvalidDecl(); 12270 } 12271 12272 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init, 12273 SourceLocation Loc) { 12274 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init)) 12275 Init = EWC->getSubExpr(); 12276 12277 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 12278 Init = CE->getSubExpr(); 12279 12280 QualType InitType = Init->getType(); 12281 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12282 InitType.hasNonTrivialToPrimitiveCopyCUnion()) && 12283 "shouldn't be called if type doesn't have a non-trivial C struct"); 12284 if (auto *ILE = dyn_cast<InitListExpr>(Init)) { 12285 for (auto I : ILE->inits()) { 12286 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() && 12287 !I->getType().hasNonTrivialToPrimitiveCopyCUnion()) 12288 continue; 12289 SourceLocation SL = I->getExprLoc(); 12290 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc); 12291 } 12292 return; 12293 } 12294 12295 if (isa<ImplicitValueInitExpr>(Init)) { 12296 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 12297 checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject, 12298 NTCUK_Init); 12299 } else { 12300 // Assume all other explicit initializers involving copying some existing 12301 // object. 12302 // TODO: ignore any explicit initializers where we can guarantee 12303 // copy-elision. 12304 if (InitType.hasNonTrivialToPrimitiveCopyCUnion()) 12305 checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy); 12306 } 12307 } 12308 12309 namespace { 12310 12311 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) { 12312 // Ignore unavailable fields. A field can be marked as unavailable explicitly 12313 // in the source code or implicitly by the compiler if it is in a union 12314 // defined in a system header and has non-trivial ObjC ownership 12315 // qualifications. We don't want those fields to participate in determining 12316 // whether the containing union is non-trivial. 12317 return FD->hasAttr<UnavailableAttr>(); 12318 } 12319 12320 struct DiagNonTrivalCUnionDefaultInitializeVisitor 12321 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 12322 void> { 12323 using Super = 12324 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 12325 void>; 12326 12327 DiagNonTrivalCUnionDefaultInitializeVisitor( 12328 QualType OrigTy, SourceLocation OrigLoc, 12329 Sema::NonTrivialCUnionContext UseContext, Sema &S) 12330 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 12331 12332 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT, 12333 const FieldDecl *FD, bool InNonTrivialUnion) { 12334 if (const auto *AT = S.Context.getAsArrayType(QT)) 12335 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 12336 InNonTrivialUnion); 12337 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion); 12338 } 12339 12340 void visitARCStrong(QualType QT, const FieldDecl *FD, 12341 bool InNonTrivialUnion) { 12342 if (InNonTrivialUnion) 12343 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12344 << 1 << 0 << QT << FD->getName(); 12345 } 12346 12347 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12348 if (InNonTrivialUnion) 12349 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12350 << 1 << 0 << QT << FD->getName(); 12351 } 12352 12353 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12354 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 12355 if (RD->isUnion()) { 12356 if (OrigLoc.isValid()) { 12357 bool IsUnion = false; 12358 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 12359 IsUnion = OrigRD->isUnion(); 12360 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 12361 << 0 << OrigTy << IsUnion << UseContext; 12362 // Reset OrigLoc so that this diagnostic is emitted only once. 12363 OrigLoc = SourceLocation(); 12364 } 12365 InNonTrivialUnion = true; 12366 } 12367 12368 if (InNonTrivialUnion) 12369 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 12370 << 0 << 0 << QT.getUnqualifiedType() << ""; 12371 12372 for (const FieldDecl *FD : RD->fields()) 12373 if (!shouldIgnoreForRecordTriviality(FD)) 12374 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 12375 } 12376 12377 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 12378 12379 // The non-trivial C union type or the struct/union type that contains a 12380 // non-trivial C union. 12381 QualType OrigTy; 12382 SourceLocation OrigLoc; 12383 Sema::NonTrivialCUnionContext UseContext; 12384 Sema &S; 12385 }; 12386 12387 struct DiagNonTrivalCUnionDestructedTypeVisitor 12388 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> { 12389 using Super = 12390 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>; 12391 12392 DiagNonTrivalCUnionDestructedTypeVisitor( 12393 QualType OrigTy, SourceLocation OrigLoc, 12394 Sema::NonTrivialCUnionContext UseContext, Sema &S) 12395 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 12396 12397 void visitWithKind(QualType::DestructionKind DK, QualType QT, 12398 const FieldDecl *FD, bool InNonTrivialUnion) { 12399 if (const auto *AT = S.Context.getAsArrayType(QT)) 12400 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 12401 InNonTrivialUnion); 12402 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion); 12403 } 12404 12405 void visitARCStrong(QualType QT, const FieldDecl *FD, 12406 bool InNonTrivialUnion) { 12407 if (InNonTrivialUnion) 12408 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12409 << 1 << 1 << QT << FD->getName(); 12410 } 12411 12412 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12413 if (InNonTrivialUnion) 12414 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12415 << 1 << 1 << QT << FD->getName(); 12416 } 12417 12418 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12419 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 12420 if (RD->isUnion()) { 12421 if (OrigLoc.isValid()) { 12422 bool IsUnion = false; 12423 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 12424 IsUnion = OrigRD->isUnion(); 12425 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 12426 << 1 << OrigTy << IsUnion << UseContext; 12427 // Reset OrigLoc so that this diagnostic is emitted only once. 12428 OrigLoc = SourceLocation(); 12429 } 12430 InNonTrivialUnion = true; 12431 } 12432 12433 if (InNonTrivialUnion) 12434 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 12435 << 0 << 1 << QT.getUnqualifiedType() << ""; 12436 12437 for (const FieldDecl *FD : RD->fields()) 12438 if (!shouldIgnoreForRecordTriviality(FD)) 12439 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 12440 } 12441 12442 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 12443 void visitCXXDestructor(QualType QT, const FieldDecl *FD, 12444 bool InNonTrivialUnion) {} 12445 12446 // The non-trivial C union type or the struct/union type that contains a 12447 // non-trivial C union. 12448 QualType OrigTy; 12449 SourceLocation OrigLoc; 12450 Sema::NonTrivialCUnionContext UseContext; 12451 Sema &S; 12452 }; 12453 12454 struct DiagNonTrivalCUnionCopyVisitor 12455 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> { 12456 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>; 12457 12458 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc, 12459 Sema::NonTrivialCUnionContext UseContext, 12460 Sema &S) 12461 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 12462 12463 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT, 12464 const FieldDecl *FD, bool InNonTrivialUnion) { 12465 if (const auto *AT = S.Context.getAsArrayType(QT)) 12466 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 12467 InNonTrivialUnion); 12468 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion); 12469 } 12470 12471 void visitARCStrong(QualType QT, const FieldDecl *FD, 12472 bool InNonTrivialUnion) { 12473 if (InNonTrivialUnion) 12474 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12475 << 1 << 2 << QT << FD->getName(); 12476 } 12477 12478 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12479 if (InNonTrivialUnion) 12480 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 12481 << 1 << 2 << QT << FD->getName(); 12482 } 12483 12484 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 12485 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 12486 if (RD->isUnion()) { 12487 if (OrigLoc.isValid()) { 12488 bool IsUnion = false; 12489 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 12490 IsUnion = OrigRD->isUnion(); 12491 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 12492 << 2 << OrigTy << IsUnion << UseContext; 12493 // Reset OrigLoc so that this diagnostic is emitted only once. 12494 OrigLoc = SourceLocation(); 12495 } 12496 InNonTrivialUnion = true; 12497 } 12498 12499 if (InNonTrivialUnion) 12500 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 12501 << 0 << 2 << QT.getUnqualifiedType() << ""; 12502 12503 for (const FieldDecl *FD : RD->fields()) 12504 if (!shouldIgnoreForRecordTriviality(FD)) 12505 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 12506 } 12507 12508 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT, 12509 const FieldDecl *FD, bool InNonTrivialUnion) {} 12510 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 12511 void visitVolatileTrivial(QualType QT, const FieldDecl *FD, 12512 bool InNonTrivialUnion) {} 12513 12514 // The non-trivial C union type or the struct/union type that contains a 12515 // non-trivial C union. 12516 QualType OrigTy; 12517 SourceLocation OrigLoc; 12518 Sema::NonTrivialCUnionContext UseContext; 12519 Sema &S; 12520 }; 12521 12522 } // namespace 12523 12524 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc, 12525 NonTrivialCUnionContext UseContext, 12526 unsigned NonTrivialKind) { 12527 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12528 QT.hasNonTrivialToPrimitiveDestructCUnion() || 12529 QT.hasNonTrivialToPrimitiveCopyCUnion()) && 12530 "shouldn't be called if type doesn't have a non-trivial C union"); 12531 12532 if ((NonTrivialKind & NTCUK_Init) && 12533 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 12534 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this) 12535 .visit(QT, nullptr, false); 12536 if ((NonTrivialKind & NTCUK_Destruct) && 12537 QT.hasNonTrivialToPrimitiveDestructCUnion()) 12538 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this) 12539 .visit(QT, nullptr, false); 12540 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion()) 12541 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this) 12542 .visit(QT, nullptr, false); 12543 } 12544 12545 /// AddInitializerToDecl - Adds the initializer Init to the 12546 /// declaration dcl. If DirectInit is true, this is C++ direct 12547 /// initialization rather than copy initialization. 12548 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 12549 // If there is no declaration, there was an error parsing it. Just ignore 12550 // the initializer. 12551 if (!RealDecl || RealDecl->isInvalidDecl()) { 12552 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 12553 return; 12554 } 12555 12556 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 12557 // Pure-specifiers are handled in ActOnPureSpecifier. 12558 Diag(Method->getLocation(), diag::err_member_function_initialization) 12559 << Method->getDeclName() << Init->getSourceRange(); 12560 Method->setInvalidDecl(); 12561 return; 12562 } 12563 12564 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 12565 if (!VDecl) { 12566 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 12567 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 12568 RealDecl->setInvalidDecl(); 12569 return; 12570 } 12571 12572 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 12573 if (VDecl->getType()->isUndeducedType()) { 12574 // Attempt typo correction early so that the type of the init expression can 12575 // be deduced based on the chosen correction if the original init contains a 12576 // TypoExpr. 12577 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 12578 if (!Res.isUsable()) { 12579 // There are unresolved typos in Init, just drop them. 12580 // FIXME: improve the recovery strategy to preserve the Init. 12581 RealDecl->setInvalidDecl(); 12582 return; 12583 } 12584 if (Res.get()->containsErrors()) { 12585 // Invalidate the decl as we don't know the type for recovery-expr yet. 12586 RealDecl->setInvalidDecl(); 12587 VDecl->setInit(Res.get()); 12588 return; 12589 } 12590 Init = Res.get(); 12591 12592 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 12593 return; 12594 } 12595 12596 // dllimport cannot be used on variable definitions. 12597 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 12598 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 12599 VDecl->setInvalidDecl(); 12600 return; 12601 } 12602 12603 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 12604 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 12605 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 12606 VDecl->setInvalidDecl(); 12607 return; 12608 } 12609 12610 if (!VDecl->getType()->isDependentType()) { 12611 // A definition must end up with a complete type, which means it must be 12612 // complete with the restriction that an array type might be completed by 12613 // the initializer; note that later code assumes this restriction. 12614 QualType BaseDeclType = VDecl->getType(); 12615 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 12616 BaseDeclType = Array->getElementType(); 12617 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 12618 diag::err_typecheck_decl_incomplete_type)) { 12619 RealDecl->setInvalidDecl(); 12620 return; 12621 } 12622 12623 // The variable can not have an abstract class type. 12624 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 12625 diag::err_abstract_type_in_decl, 12626 AbstractVariableType)) 12627 VDecl->setInvalidDecl(); 12628 } 12629 12630 // If adding the initializer will turn this declaration into a definition, 12631 // and we already have a definition for this variable, diagnose or otherwise 12632 // handle the situation. 12633 if (VarDecl *Def = VDecl->getDefinition()) 12634 if (Def != VDecl && 12635 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 12636 !VDecl->isThisDeclarationADemotedDefinition() && 12637 checkVarDeclRedefinition(Def, VDecl)) 12638 return; 12639 12640 if (getLangOpts().CPlusPlus) { 12641 // C++ [class.static.data]p4 12642 // If a static data member is of const integral or const 12643 // enumeration type, its declaration in the class definition can 12644 // specify a constant-initializer which shall be an integral 12645 // constant expression (5.19). In that case, the member can appear 12646 // in integral constant expressions. The member shall still be 12647 // defined in a namespace scope if it is used in the program and the 12648 // namespace scope definition shall not contain an initializer. 12649 // 12650 // We already performed a redefinition check above, but for static 12651 // data members we also need to check whether there was an in-class 12652 // declaration with an initializer. 12653 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 12654 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 12655 << VDecl->getDeclName(); 12656 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 12657 diag::note_previous_initializer) 12658 << 0; 12659 return; 12660 } 12661 12662 if (VDecl->hasLocalStorage()) 12663 setFunctionHasBranchProtectedScope(); 12664 12665 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 12666 VDecl->setInvalidDecl(); 12667 return; 12668 } 12669 } 12670 12671 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 12672 // a kernel function cannot be initialized." 12673 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 12674 Diag(VDecl->getLocation(), diag::err_local_cant_init); 12675 VDecl->setInvalidDecl(); 12676 return; 12677 } 12678 12679 // The LoaderUninitialized attribute acts as a definition (of undef). 12680 if (VDecl->hasAttr<LoaderUninitializedAttr>()) { 12681 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init); 12682 VDecl->setInvalidDecl(); 12683 return; 12684 } 12685 12686 // Get the decls type and save a reference for later, since 12687 // CheckInitializerTypes may change it. 12688 QualType DclT = VDecl->getType(), SavT = DclT; 12689 12690 // Expressions default to 'id' when we're in a debugger 12691 // and we are assigning it to a variable of Objective-C pointer type. 12692 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 12693 Init->getType() == Context.UnknownAnyTy) { 12694 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 12695 if (Result.isInvalid()) { 12696 VDecl->setInvalidDecl(); 12697 return; 12698 } 12699 Init = Result.get(); 12700 } 12701 12702 // Perform the initialization. 12703 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 12704 if (!VDecl->isInvalidDecl()) { 12705 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 12706 InitializationKind Kind = InitializationKind::CreateForInit( 12707 VDecl->getLocation(), DirectInit, Init); 12708 12709 MultiExprArg Args = Init; 12710 if (CXXDirectInit) 12711 Args = MultiExprArg(CXXDirectInit->getExprs(), 12712 CXXDirectInit->getNumExprs()); 12713 12714 // Try to correct any TypoExprs in the initialization arguments. 12715 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 12716 ExprResult Res = CorrectDelayedTyposInExpr( 12717 Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true, 12718 [this, Entity, Kind](Expr *E) { 12719 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 12720 return Init.Failed() ? ExprError() : E; 12721 }); 12722 if (Res.isInvalid()) { 12723 VDecl->setInvalidDecl(); 12724 } else if (Res.get() != Args[Idx]) { 12725 Args[Idx] = Res.get(); 12726 } 12727 } 12728 if (VDecl->isInvalidDecl()) 12729 return; 12730 12731 InitializationSequence InitSeq(*this, Entity, Kind, Args, 12732 /*TopLevelOfInitList=*/false, 12733 /*TreatUnavailableAsInvalid=*/false); 12734 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 12735 if (Result.isInvalid()) { 12736 // If the provided initializer fails to initialize the var decl, 12737 // we attach a recovery expr for better recovery. 12738 auto RecoveryExpr = 12739 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args); 12740 if (RecoveryExpr.get()) 12741 VDecl->setInit(RecoveryExpr.get()); 12742 return; 12743 } 12744 12745 Init = Result.getAs<Expr>(); 12746 } 12747 12748 // Check for self-references within variable initializers. 12749 // Variables declared within a function/method body (except for references) 12750 // are handled by a dataflow analysis. 12751 // This is undefined behavior in C++, but valid in C. 12752 if (getLangOpts().CPlusPlus) 12753 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 12754 VDecl->getType()->isReferenceType()) 12755 CheckSelfReference(*this, RealDecl, Init, DirectInit); 12756 12757 // If the type changed, it means we had an incomplete type that was 12758 // completed by the initializer. For example: 12759 // int ary[] = { 1, 3, 5 }; 12760 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 12761 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 12762 VDecl->setType(DclT); 12763 12764 if (!VDecl->isInvalidDecl()) { 12765 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 12766 12767 if (VDecl->hasAttr<BlocksAttr>()) 12768 checkRetainCycles(VDecl, Init); 12769 12770 // It is safe to assign a weak reference into a strong variable. 12771 // Although this code can still have problems: 12772 // id x = self.weakProp; 12773 // id y = self.weakProp; 12774 // we do not warn to warn spuriously when 'x' and 'y' are on separate 12775 // paths through the function. This should be revisited if 12776 // -Wrepeated-use-of-weak is made flow-sensitive. 12777 if (FunctionScopeInfo *FSI = getCurFunction()) 12778 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 12779 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 12780 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 12781 Init->getBeginLoc())) 12782 FSI->markSafeWeakUse(Init); 12783 } 12784 12785 // The initialization is usually a full-expression. 12786 // 12787 // FIXME: If this is a braced initialization of an aggregate, it is not 12788 // an expression, and each individual field initializer is a separate 12789 // full-expression. For instance, in: 12790 // 12791 // struct Temp { ~Temp(); }; 12792 // struct S { S(Temp); }; 12793 // struct T { S a, b; } t = { Temp(), Temp() } 12794 // 12795 // we should destroy the first Temp before constructing the second. 12796 ExprResult Result = 12797 ActOnFinishFullExpr(Init, VDecl->getLocation(), 12798 /*DiscardedValue*/ false, VDecl->isConstexpr()); 12799 if (Result.isInvalid()) { 12800 VDecl->setInvalidDecl(); 12801 return; 12802 } 12803 Init = Result.get(); 12804 12805 // Attach the initializer to the decl. 12806 VDecl->setInit(Init); 12807 12808 if (VDecl->isLocalVarDecl()) { 12809 // Don't check the initializer if the declaration is malformed. 12810 if (VDecl->isInvalidDecl()) { 12811 // do nothing 12812 12813 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 12814 // This is true even in C++ for OpenCL. 12815 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 12816 CheckForConstantInitializer(Init, DclT); 12817 12818 // Otherwise, C++ does not restrict the initializer. 12819 } else if (getLangOpts().CPlusPlus) { 12820 // do nothing 12821 12822 // C99 6.7.8p4: All the expressions in an initializer for an object that has 12823 // static storage duration shall be constant expressions or string literals. 12824 } else if (VDecl->getStorageClass() == SC_Static) { 12825 CheckForConstantInitializer(Init, DclT); 12826 12827 // C89 is stricter than C99 for aggregate initializers. 12828 // C89 6.5.7p3: All the expressions [...] in an initializer list 12829 // for an object that has aggregate or union type shall be 12830 // constant expressions. 12831 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 12832 isa<InitListExpr>(Init)) { 12833 const Expr *Culprit; 12834 if (!Init->isConstantInitializer(Context, false, &Culprit)) { 12835 Diag(Culprit->getExprLoc(), 12836 diag::ext_aggregate_init_not_constant) 12837 << Culprit->getSourceRange(); 12838 } 12839 } 12840 12841 if (auto *E = dyn_cast<ExprWithCleanups>(Init)) 12842 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens())) 12843 if (VDecl->hasLocalStorage()) 12844 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 12845 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 12846 VDecl->getLexicalDeclContext()->isRecord()) { 12847 // This is an in-class initialization for a static data member, e.g., 12848 // 12849 // struct S { 12850 // static const int value = 17; 12851 // }; 12852 12853 // C++ [class.mem]p4: 12854 // A member-declarator can contain a constant-initializer only 12855 // if it declares a static member (9.4) of const integral or 12856 // const enumeration type, see 9.4.2. 12857 // 12858 // C++11 [class.static.data]p3: 12859 // If a non-volatile non-inline const static data member is of integral 12860 // or enumeration type, its declaration in the class definition can 12861 // specify a brace-or-equal-initializer in which every initializer-clause 12862 // that is an assignment-expression is a constant expression. A static 12863 // data member of literal type can be declared in the class definition 12864 // with the constexpr specifier; if so, its declaration shall specify a 12865 // brace-or-equal-initializer in which every initializer-clause that is 12866 // an assignment-expression is a constant expression. 12867 12868 // Do nothing on dependent types. 12869 if (DclT->isDependentType()) { 12870 12871 // Allow any 'static constexpr' members, whether or not they are of literal 12872 // type. We separately check that every constexpr variable is of literal 12873 // type. 12874 } else if (VDecl->isConstexpr()) { 12875 12876 // Require constness. 12877 } else if (!DclT.isConstQualified()) { 12878 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 12879 << Init->getSourceRange(); 12880 VDecl->setInvalidDecl(); 12881 12882 // We allow integer constant expressions in all cases. 12883 } else if (DclT->isIntegralOrEnumerationType()) { 12884 // Check whether the expression is a constant expression. 12885 SourceLocation Loc; 12886 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 12887 // In C++11, a non-constexpr const static data member with an 12888 // in-class initializer cannot be volatile. 12889 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 12890 else if (Init->isValueDependent()) 12891 ; // Nothing to check. 12892 else if (Init->isIntegerConstantExpr(Context, &Loc)) 12893 ; // Ok, it's an ICE! 12894 else if (Init->getType()->isScopedEnumeralType() && 12895 Init->isCXX11ConstantExpr(Context)) 12896 ; // Ok, it is a scoped-enum constant expression. 12897 else if (Init->isEvaluatable(Context)) { 12898 // If we can constant fold the initializer through heroics, accept it, 12899 // but report this as a use of an extension for -pedantic. 12900 Diag(Loc, diag::ext_in_class_initializer_non_constant) 12901 << Init->getSourceRange(); 12902 } else { 12903 // Otherwise, this is some crazy unknown case. Report the issue at the 12904 // location provided by the isIntegerConstantExpr failed check. 12905 Diag(Loc, diag::err_in_class_initializer_non_constant) 12906 << Init->getSourceRange(); 12907 VDecl->setInvalidDecl(); 12908 } 12909 12910 // We allow foldable floating-point constants as an extension. 12911 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 12912 // In C++98, this is a GNU extension. In C++11, it is not, but we support 12913 // it anyway and provide a fixit to add the 'constexpr'. 12914 if (getLangOpts().CPlusPlus11) { 12915 Diag(VDecl->getLocation(), 12916 diag::ext_in_class_initializer_float_type_cxx11) 12917 << DclT << Init->getSourceRange(); 12918 Diag(VDecl->getBeginLoc(), 12919 diag::note_in_class_initializer_float_type_cxx11) 12920 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12921 } else { 12922 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 12923 << DclT << Init->getSourceRange(); 12924 12925 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 12926 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 12927 << Init->getSourceRange(); 12928 VDecl->setInvalidDecl(); 12929 } 12930 } 12931 12932 // Suggest adding 'constexpr' in C++11 for literal types. 12933 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 12934 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 12935 << DclT << Init->getSourceRange() 12936 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12937 VDecl->setConstexpr(true); 12938 12939 } else { 12940 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 12941 << DclT << Init->getSourceRange(); 12942 VDecl->setInvalidDecl(); 12943 } 12944 } else if (VDecl->isFileVarDecl()) { 12945 // In C, extern is typically used to avoid tentative definitions when 12946 // declaring variables in headers, but adding an intializer makes it a 12947 // definition. This is somewhat confusing, so GCC and Clang both warn on it. 12948 // In C++, extern is often used to give implictly static const variables 12949 // external linkage, so don't warn in that case. If selectany is present, 12950 // this might be header code intended for C and C++ inclusion, so apply the 12951 // C++ rules. 12952 if (VDecl->getStorageClass() == SC_Extern && 12953 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 12954 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 12955 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 12956 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 12957 Diag(VDecl->getLocation(), diag::warn_extern_init); 12958 12959 // In Microsoft C++ mode, a const variable defined in namespace scope has 12960 // external linkage by default if the variable is declared with 12961 // __declspec(dllexport). 12962 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 12963 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() && 12964 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition()) 12965 VDecl->setStorageClass(SC_Extern); 12966 12967 // C99 6.7.8p4. All file scoped initializers need to be constant. 12968 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 12969 CheckForConstantInitializer(Init, DclT); 12970 } 12971 12972 QualType InitType = Init->getType(); 12973 if (!InitType.isNull() && 12974 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12975 InitType.hasNonTrivialToPrimitiveCopyCUnion())) 12976 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc()); 12977 12978 // We will represent direct-initialization similarly to copy-initialization: 12979 // int x(1); -as-> int x = 1; 12980 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 12981 // 12982 // Clients that want to distinguish between the two forms, can check for 12983 // direct initializer using VarDecl::getInitStyle(). 12984 // A major benefit is that clients that don't particularly care about which 12985 // exactly form was it (like the CodeGen) can handle both cases without 12986 // special case code. 12987 12988 // C++ 8.5p11: 12989 // The form of initialization (using parentheses or '=') is generally 12990 // insignificant, but does matter when the entity being initialized has a 12991 // class type. 12992 if (CXXDirectInit) { 12993 assert(DirectInit && "Call-style initializer must be direct init."); 12994 VDecl->setInitStyle(VarDecl::CallInit); 12995 } else if (DirectInit) { 12996 // This must be list-initialization. No other way is direct-initialization. 12997 VDecl->setInitStyle(VarDecl::ListInit); 12998 } 12999 13000 if (LangOpts.OpenMP && 13001 (LangOpts.OpenMPIsDevice || !LangOpts.OMPTargetTriples.empty()) && 13002 VDecl->isFileVarDecl()) 13003 DeclsToCheckForDeferredDiags.insert(VDecl); 13004 CheckCompleteVariableDeclaration(VDecl); 13005 } 13006 13007 /// ActOnInitializerError - Given that there was an error parsing an 13008 /// initializer for the given declaration, try to at least re-establish 13009 /// invariants such as whether a variable's type is either dependent or 13010 /// complete. 13011 void Sema::ActOnInitializerError(Decl *D) { 13012 // Our main concern here is re-establishing invariants like "a 13013 // variable's type is either dependent or complete". 13014 if (!D || D->isInvalidDecl()) return; 13015 13016 VarDecl *VD = dyn_cast<VarDecl>(D); 13017 if (!VD) return; 13018 13019 // Bindings are not usable if we can't make sense of the initializer. 13020 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 13021 for (auto *BD : DD->bindings()) 13022 BD->setInvalidDecl(); 13023 13024 // Auto types are meaningless if we can't make sense of the initializer. 13025 if (VD->getType()->isUndeducedType()) { 13026 D->setInvalidDecl(); 13027 return; 13028 } 13029 13030 QualType Ty = VD->getType(); 13031 if (Ty->isDependentType()) return; 13032 13033 // Require a complete type. 13034 if (RequireCompleteType(VD->getLocation(), 13035 Context.getBaseElementType(Ty), 13036 diag::err_typecheck_decl_incomplete_type)) { 13037 VD->setInvalidDecl(); 13038 return; 13039 } 13040 13041 // Require a non-abstract type. 13042 if (RequireNonAbstractType(VD->getLocation(), Ty, 13043 diag::err_abstract_type_in_decl, 13044 AbstractVariableType)) { 13045 VD->setInvalidDecl(); 13046 return; 13047 } 13048 13049 // Don't bother complaining about constructors or destructors, 13050 // though. 13051 } 13052 13053 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 13054 // If there is no declaration, there was an error parsing it. Just ignore it. 13055 if (!RealDecl) 13056 return; 13057 13058 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 13059 QualType Type = Var->getType(); 13060 13061 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 13062 if (isa<DecompositionDecl>(RealDecl)) { 13063 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 13064 Var->setInvalidDecl(); 13065 return; 13066 } 13067 13068 if (Type->isUndeducedType() && 13069 DeduceVariableDeclarationType(Var, false, nullptr)) 13070 return; 13071 13072 // C++11 [class.static.data]p3: A static data member can be declared with 13073 // the constexpr specifier; if so, its declaration shall specify 13074 // a brace-or-equal-initializer. 13075 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 13076 // the definition of a variable [...] or the declaration of a static data 13077 // member. 13078 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 13079 !Var->isThisDeclarationADemotedDefinition()) { 13080 if (Var->isStaticDataMember()) { 13081 // C++1z removes the relevant rule; the in-class declaration is always 13082 // a definition there. 13083 if (!getLangOpts().CPlusPlus17 && 13084 !Context.getTargetInfo().getCXXABI().isMicrosoft()) { 13085 Diag(Var->getLocation(), 13086 diag::err_constexpr_static_mem_var_requires_init) 13087 << Var; 13088 Var->setInvalidDecl(); 13089 return; 13090 } 13091 } else { 13092 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 13093 Var->setInvalidDecl(); 13094 return; 13095 } 13096 } 13097 13098 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 13099 // be initialized. 13100 if (!Var->isInvalidDecl() && 13101 Var->getType().getAddressSpace() == LangAS::opencl_constant && 13102 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 13103 bool HasConstExprDefaultConstructor = false; 13104 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) { 13105 for (auto *Ctor : RD->ctors()) { 13106 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 && 13107 Ctor->getMethodQualifiers().getAddressSpace() == 13108 LangAS::opencl_constant) { 13109 HasConstExprDefaultConstructor = true; 13110 } 13111 } 13112 } 13113 if (!HasConstExprDefaultConstructor) { 13114 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 13115 Var->setInvalidDecl(); 13116 return; 13117 } 13118 } 13119 13120 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) { 13121 if (Var->getStorageClass() == SC_Extern) { 13122 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl) 13123 << Var; 13124 Var->setInvalidDecl(); 13125 return; 13126 } 13127 if (RequireCompleteType(Var->getLocation(), Var->getType(), 13128 diag::err_typecheck_decl_incomplete_type)) { 13129 Var->setInvalidDecl(); 13130 return; 13131 } 13132 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) { 13133 if (!RD->hasTrivialDefaultConstructor()) { 13134 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor); 13135 Var->setInvalidDecl(); 13136 return; 13137 } 13138 } 13139 // The declaration is unitialized, no need for further checks. 13140 return; 13141 } 13142 13143 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition(); 13144 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly && 13145 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 13146 checkNonTrivialCUnion(Var->getType(), Var->getLocation(), 13147 NTCUC_DefaultInitializedObject, NTCUK_Init); 13148 13149 13150 switch (DefKind) { 13151 case VarDecl::Definition: 13152 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 13153 break; 13154 13155 // We have an out-of-line definition of a static data member 13156 // that has an in-class initializer, so we type-check this like 13157 // a declaration. 13158 // 13159 LLVM_FALLTHROUGH; 13160 13161 case VarDecl::DeclarationOnly: 13162 // It's only a declaration. 13163 13164 // Block scope. C99 6.7p7: If an identifier for an object is 13165 // declared with no linkage (C99 6.2.2p6), the type for the 13166 // object shall be complete. 13167 if (!Type->isDependentType() && Var->isLocalVarDecl() && 13168 !Var->hasLinkage() && !Var->isInvalidDecl() && 13169 RequireCompleteType(Var->getLocation(), Type, 13170 diag::err_typecheck_decl_incomplete_type)) 13171 Var->setInvalidDecl(); 13172 13173 // Make sure that the type is not abstract. 13174 if (!Type->isDependentType() && !Var->isInvalidDecl() && 13175 RequireNonAbstractType(Var->getLocation(), Type, 13176 diag::err_abstract_type_in_decl, 13177 AbstractVariableType)) 13178 Var->setInvalidDecl(); 13179 if (!Type->isDependentType() && !Var->isInvalidDecl() && 13180 Var->getStorageClass() == SC_PrivateExtern) { 13181 Diag(Var->getLocation(), diag::warn_private_extern); 13182 Diag(Var->getLocation(), diag::note_private_extern); 13183 } 13184 13185 if (Context.getTargetInfo().allowDebugInfoForExternalRef() && 13186 !Var->isInvalidDecl() && !getLangOpts().CPlusPlus) 13187 ExternalDeclarations.push_back(Var); 13188 13189 return; 13190 13191 case VarDecl::TentativeDefinition: 13192 // File scope. C99 6.9.2p2: A declaration of an identifier for an 13193 // object that has file scope without an initializer, and without a 13194 // storage-class specifier or with the storage-class specifier "static", 13195 // constitutes a tentative definition. Note: A tentative definition with 13196 // external linkage is valid (C99 6.2.2p5). 13197 if (!Var->isInvalidDecl()) { 13198 if (const IncompleteArrayType *ArrayT 13199 = Context.getAsIncompleteArrayType(Type)) { 13200 if (RequireCompleteSizedType( 13201 Var->getLocation(), ArrayT->getElementType(), 13202 diag::err_array_incomplete_or_sizeless_type)) 13203 Var->setInvalidDecl(); 13204 } else if (Var->getStorageClass() == SC_Static) { 13205 // C99 6.9.2p3: If the declaration of an identifier for an object is 13206 // a tentative definition and has internal linkage (C99 6.2.2p3), the 13207 // declared type shall not be an incomplete type. 13208 // NOTE: code such as the following 13209 // static struct s; 13210 // struct s { int a; }; 13211 // is accepted by gcc. Hence here we issue a warning instead of 13212 // an error and we do not invalidate the static declaration. 13213 // NOTE: to avoid multiple warnings, only check the first declaration. 13214 if (Var->isFirstDecl()) 13215 RequireCompleteType(Var->getLocation(), Type, 13216 diag::ext_typecheck_decl_incomplete_type); 13217 } 13218 } 13219 13220 // Record the tentative definition; we're done. 13221 if (!Var->isInvalidDecl()) 13222 TentativeDefinitions.push_back(Var); 13223 return; 13224 } 13225 13226 // Provide a specific diagnostic for uninitialized variable 13227 // definitions with incomplete array type. 13228 if (Type->isIncompleteArrayType()) { 13229 Diag(Var->getLocation(), 13230 diag::err_typecheck_incomplete_array_needs_initializer); 13231 Var->setInvalidDecl(); 13232 return; 13233 } 13234 13235 // Provide a specific diagnostic for uninitialized variable 13236 // definitions with reference type. 13237 if (Type->isReferenceType()) { 13238 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 13239 << Var << SourceRange(Var->getLocation(), Var->getLocation()); 13240 return; 13241 } 13242 13243 // Do not attempt to type-check the default initializer for a 13244 // variable with dependent type. 13245 if (Type->isDependentType()) 13246 return; 13247 13248 if (Var->isInvalidDecl()) 13249 return; 13250 13251 if (!Var->hasAttr<AliasAttr>()) { 13252 if (RequireCompleteType(Var->getLocation(), 13253 Context.getBaseElementType(Type), 13254 diag::err_typecheck_decl_incomplete_type)) { 13255 Var->setInvalidDecl(); 13256 return; 13257 } 13258 } else { 13259 return; 13260 } 13261 13262 // The variable can not have an abstract class type. 13263 if (RequireNonAbstractType(Var->getLocation(), Type, 13264 diag::err_abstract_type_in_decl, 13265 AbstractVariableType)) { 13266 Var->setInvalidDecl(); 13267 return; 13268 } 13269 13270 // Check for jumps past the implicit initializer. C++0x 13271 // clarifies that this applies to a "variable with automatic 13272 // storage duration", not a "local variable". 13273 // C++11 [stmt.dcl]p3 13274 // A program that jumps from a point where a variable with automatic 13275 // storage duration is not in scope to a point where it is in scope is 13276 // ill-formed unless the variable has scalar type, class type with a 13277 // trivial default constructor and a trivial destructor, a cv-qualified 13278 // version of one of these types, or an array of one of the preceding 13279 // types and is declared without an initializer. 13280 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 13281 if (const RecordType *Record 13282 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 13283 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 13284 // Mark the function (if we're in one) for further checking even if the 13285 // looser rules of C++11 do not require such checks, so that we can 13286 // diagnose incompatibilities with C++98. 13287 if (!CXXRecord->isPOD()) 13288 setFunctionHasBranchProtectedScope(); 13289 } 13290 } 13291 // In OpenCL, we can't initialize objects in the __local address space, 13292 // even implicitly, so don't synthesize an implicit initializer. 13293 if (getLangOpts().OpenCL && 13294 Var->getType().getAddressSpace() == LangAS::opencl_local) 13295 return; 13296 // C++03 [dcl.init]p9: 13297 // If no initializer is specified for an object, and the 13298 // object is of (possibly cv-qualified) non-POD class type (or 13299 // array thereof), the object shall be default-initialized; if 13300 // the object is of const-qualified type, the underlying class 13301 // type shall have a user-declared default 13302 // constructor. Otherwise, if no initializer is specified for 13303 // a non- static object, the object and its subobjects, if 13304 // any, have an indeterminate initial value); if the object 13305 // or any of its subobjects are of const-qualified type, the 13306 // program is ill-formed. 13307 // C++0x [dcl.init]p11: 13308 // If no initializer is specified for an object, the object is 13309 // default-initialized; [...]. 13310 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 13311 InitializationKind Kind 13312 = InitializationKind::CreateDefault(Var->getLocation()); 13313 13314 InitializationSequence InitSeq(*this, Entity, Kind, None); 13315 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 13316 13317 if (Init.get()) { 13318 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 13319 // This is important for template substitution. 13320 Var->setInitStyle(VarDecl::CallInit); 13321 } else if (Init.isInvalid()) { 13322 // If default-init fails, attach a recovery-expr initializer to track 13323 // that initialization was attempted and failed. 13324 auto RecoveryExpr = 13325 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {}); 13326 if (RecoveryExpr.get()) 13327 Var->setInit(RecoveryExpr.get()); 13328 } 13329 13330 CheckCompleteVariableDeclaration(Var); 13331 } 13332 } 13333 13334 void Sema::ActOnCXXForRangeDecl(Decl *D) { 13335 // If there is no declaration, there was an error parsing it. Ignore it. 13336 if (!D) 13337 return; 13338 13339 VarDecl *VD = dyn_cast<VarDecl>(D); 13340 if (!VD) { 13341 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 13342 D->setInvalidDecl(); 13343 return; 13344 } 13345 13346 VD->setCXXForRangeDecl(true); 13347 13348 // for-range-declaration cannot be given a storage class specifier. 13349 int Error = -1; 13350 switch (VD->getStorageClass()) { 13351 case SC_None: 13352 break; 13353 case SC_Extern: 13354 Error = 0; 13355 break; 13356 case SC_Static: 13357 Error = 1; 13358 break; 13359 case SC_PrivateExtern: 13360 Error = 2; 13361 break; 13362 case SC_Auto: 13363 Error = 3; 13364 break; 13365 case SC_Register: 13366 Error = 4; 13367 break; 13368 } 13369 13370 // for-range-declaration cannot be given a storage class specifier con't. 13371 switch (VD->getTSCSpec()) { 13372 case TSCS_thread_local: 13373 Error = 6; 13374 break; 13375 case TSCS___thread: 13376 case TSCS__Thread_local: 13377 case TSCS_unspecified: 13378 break; 13379 } 13380 13381 if (Error != -1) { 13382 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 13383 << VD << Error; 13384 D->setInvalidDecl(); 13385 } 13386 } 13387 13388 StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 13389 IdentifierInfo *Ident, 13390 ParsedAttributes &Attrs) { 13391 // C++1y [stmt.iter]p1: 13392 // A range-based for statement of the form 13393 // for ( for-range-identifier : for-range-initializer ) statement 13394 // is equivalent to 13395 // for ( auto&& for-range-identifier : for-range-initializer ) statement 13396 DeclSpec DS(Attrs.getPool().getFactory()); 13397 13398 const char *PrevSpec; 13399 unsigned DiagID; 13400 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 13401 getPrintingPolicy()); 13402 13403 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::ForInit); 13404 D.SetIdentifier(Ident, IdentLoc); 13405 D.takeAttributes(Attrs); 13406 13407 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false), 13408 IdentLoc); 13409 Decl *Var = ActOnDeclarator(S, D); 13410 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 13411 FinalizeDeclaration(Var); 13412 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 13413 Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd() 13414 : IdentLoc); 13415 } 13416 13417 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 13418 if (var->isInvalidDecl()) return; 13419 13420 MaybeAddCUDAConstantAttr(var); 13421 13422 if (getLangOpts().OpenCL) { 13423 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 13424 // initialiser 13425 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 13426 !var->hasInit()) { 13427 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 13428 << 1 /*Init*/; 13429 var->setInvalidDecl(); 13430 return; 13431 } 13432 } 13433 13434 // In Objective-C, don't allow jumps past the implicit initialization of a 13435 // local retaining variable. 13436 if (getLangOpts().ObjC && 13437 var->hasLocalStorage()) { 13438 switch (var->getType().getObjCLifetime()) { 13439 case Qualifiers::OCL_None: 13440 case Qualifiers::OCL_ExplicitNone: 13441 case Qualifiers::OCL_Autoreleasing: 13442 break; 13443 13444 case Qualifiers::OCL_Weak: 13445 case Qualifiers::OCL_Strong: 13446 setFunctionHasBranchProtectedScope(); 13447 break; 13448 } 13449 } 13450 13451 if (var->hasLocalStorage() && 13452 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 13453 setFunctionHasBranchProtectedScope(); 13454 13455 // Warn about externally-visible variables being defined without a 13456 // prior declaration. We only want to do this for global 13457 // declarations, but we also specifically need to avoid doing it for 13458 // class members because the linkage of an anonymous class can 13459 // change if it's later given a typedef name. 13460 if (var->isThisDeclarationADefinition() && 13461 var->getDeclContext()->getRedeclContext()->isFileContext() && 13462 var->isExternallyVisible() && var->hasLinkage() && 13463 !var->isInline() && !var->getDescribedVarTemplate() && 13464 !isa<VarTemplatePartialSpecializationDecl>(var) && 13465 !isTemplateInstantiation(var->getTemplateSpecializationKind()) && 13466 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 13467 var->getLocation())) { 13468 // Find a previous declaration that's not a definition. 13469 VarDecl *prev = var->getPreviousDecl(); 13470 while (prev && prev->isThisDeclarationADefinition()) 13471 prev = prev->getPreviousDecl(); 13472 13473 if (!prev) { 13474 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 13475 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 13476 << /* variable */ 0; 13477 } 13478 } 13479 13480 // Cache the result of checking for constant initialization. 13481 Optional<bool> CacheHasConstInit; 13482 const Expr *CacheCulprit = nullptr; 13483 auto checkConstInit = [&]() mutable { 13484 if (!CacheHasConstInit) 13485 CacheHasConstInit = var->getInit()->isConstantInitializer( 13486 Context, var->getType()->isReferenceType(), &CacheCulprit); 13487 return *CacheHasConstInit; 13488 }; 13489 13490 if (var->getTLSKind() == VarDecl::TLS_Static) { 13491 if (var->getType().isDestructedType()) { 13492 // GNU C++98 edits for __thread, [basic.start.term]p3: 13493 // The type of an object with thread storage duration shall not 13494 // have a non-trivial destructor. 13495 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 13496 if (getLangOpts().CPlusPlus11) 13497 Diag(var->getLocation(), diag::note_use_thread_local); 13498 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 13499 if (!checkConstInit()) { 13500 // GNU C++98 edits for __thread, [basic.start.init]p4: 13501 // An object of thread storage duration shall not require dynamic 13502 // initialization. 13503 // FIXME: Need strict checking here. 13504 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 13505 << CacheCulprit->getSourceRange(); 13506 if (getLangOpts().CPlusPlus11) 13507 Diag(var->getLocation(), diag::note_use_thread_local); 13508 } 13509 } 13510 } 13511 13512 13513 if (!var->getType()->isStructureType() && var->hasInit() && 13514 isa<InitListExpr>(var->getInit())) { 13515 const auto *ILE = cast<InitListExpr>(var->getInit()); 13516 unsigned NumInits = ILE->getNumInits(); 13517 if (NumInits > 2) 13518 for (unsigned I = 0; I < NumInits; ++I) { 13519 const auto *Init = ILE->getInit(I); 13520 if (!Init) 13521 break; 13522 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); 13523 if (!SL) 13524 break; 13525 13526 unsigned NumConcat = SL->getNumConcatenated(); 13527 // Diagnose missing comma in string array initialization. 13528 // Do not warn when all the elements in the initializer are concatenated 13529 // together. Do not warn for macros too. 13530 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) { 13531 bool OnlyOneMissingComma = true; 13532 for (unsigned J = I + 1; J < NumInits; ++J) { 13533 const auto *Init = ILE->getInit(J); 13534 if (!Init) 13535 break; 13536 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); 13537 if (!SLJ || SLJ->getNumConcatenated() > 1) { 13538 OnlyOneMissingComma = false; 13539 break; 13540 } 13541 } 13542 13543 if (OnlyOneMissingComma) { 13544 SmallVector<FixItHint, 1> Hints; 13545 for (unsigned i = 0; i < NumConcat - 1; ++i) 13546 Hints.push_back(FixItHint::CreateInsertion( 13547 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ",")); 13548 13549 Diag(SL->getStrTokenLoc(1), 13550 diag::warn_concatenated_literal_array_init) 13551 << Hints; 13552 Diag(SL->getBeginLoc(), 13553 diag::note_concatenated_string_literal_silence); 13554 } 13555 // In any case, stop now. 13556 break; 13557 } 13558 } 13559 } 13560 13561 13562 QualType type = var->getType(); 13563 13564 if (var->hasAttr<BlocksAttr>()) 13565 getCurFunction()->addByrefBlockVar(var); 13566 13567 Expr *Init = var->getInit(); 13568 bool GlobalStorage = var->hasGlobalStorage(); 13569 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 13570 QualType baseType = Context.getBaseElementType(type); 13571 bool HasConstInit = true; 13572 13573 // Check whether the initializer is sufficiently constant. 13574 if (getLangOpts().CPlusPlus && !type->isDependentType() && Init && 13575 !Init->isValueDependent() && 13576 (GlobalStorage || var->isConstexpr() || 13577 var->mightBeUsableInConstantExpressions(Context))) { 13578 // If this variable might have a constant initializer or might be usable in 13579 // constant expressions, check whether or not it actually is now. We can't 13580 // do this lazily, because the result might depend on things that change 13581 // later, such as which constexpr functions happen to be defined. 13582 SmallVector<PartialDiagnosticAt, 8> Notes; 13583 if (!getLangOpts().CPlusPlus11) { 13584 // Prior to C++11, in contexts where a constant initializer is required, 13585 // the set of valid constant initializers is described by syntactic rules 13586 // in [expr.const]p2-6. 13587 // FIXME: Stricter checking for these rules would be useful for constinit / 13588 // -Wglobal-constructors. 13589 HasConstInit = checkConstInit(); 13590 13591 // Compute and cache the constant value, and remember that we have a 13592 // constant initializer. 13593 if (HasConstInit) { 13594 (void)var->checkForConstantInitialization(Notes); 13595 Notes.clear(); 13596 } else if (CacheCulprit) { 13597 Notes.emplace_back(CacheCulprit->getExprLoc(), 13598 PDiag(diag::note_invalid_subexpr_in_const_expr)); 13599 Notes.back().second << CacheCulprit->getSourceRange(); 13600 } 13601 } else { 13602 // Evaluate the initializer to see if it's a constant initializer. 13603 HasConstInit = var->checkForConstantInitialization(Notes); 13604 } 13605 13606 if (HasConstInit) { 13607 // FIXME: Consider replacing the initializer with a ConstantExpr. 13608 } else if (var->isConstexpr()) { 13609 SourceLocation DiagLoc = var->getLocation(); 13610 // If the note doesn't add any useful information other than a source 13611 // location, fold it into the primary diagnostic. 13612 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 13613 diag::note_invalid_subexpr_in_const_expr) { 13614 DiagLoc = Notes[0].first; 13615 Notes.clear(); 13616 } 13617 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 13618 << var << Init->getSourceRange(); 13619 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 13620 Diag(Notes[I].first, Notes[I].second); 13621 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) { 13622 auto *Attr = var->getAttr<ConstInitAttr>(); 13623 Diag(var->getLocation(), diag::err_require_constant_init_failed) 13624 << Init->getSourceRange(); 13625 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here) 13626 << Attr->getRange() << Attr->isConstinit(); 13627 for (auto &it : Notes) 13628 Diag(it.first, it.second); 13629 } else if (IsGlobal && 13630 !getDiagnostics().isIgnored(diag::warn_global_constructor, 13631 var->getLocation())) { 13632 // Warn about globals which don't have a constant initializer. Don't 13633 // warn about globals with a non-trivial destructor because we already 13634 // warned about them. 13635 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 13636 if (!(RD && !RD->hasTrivialDestructor())) { 13637 // checkConstInit() here permits trivial default initialization even in 13638 // C++11 onwards, where such an initializer is not a constant initializer 13639 // but nonetheless doesn't require a global constructor. 13640 if (!checkConstInit()) 13641 Diag(var->getLocation(), diag::warn_global_constructor) 13642 << Init->getSourceRange(); 13643 } 13644 } 13645 } 13646 13647 // Apply section attributes and pragmas to global variables. 13648 if (GlobalStorage && var->isThisDeclarationADefinition() && 13649 !inTemplateInstantiation()) { 13650 PragmaStack<StringLiteral *> *Stack = nullptr; 13651 int SectionFlags = ASTContext::PSF_Read; 13652 if (var->getType().isConstQualified()) { 13653 if (HasConstInit) 13654 Stack = &ConstSegStack; 13655 else { 13656 Stack = &BSSSegStack; 13657 SectionFlags |= ASTContext::PSF_Write; 13658 } 13659 } else if (var->hasInit() && HasConstInit) { 13660 Stack = &DataSegStack; 13661 SectionFlags |= ASTContext::PSF_Write; 13662 } else { 13663 Stack = &BSSSegStack; 13664 SectionFlags |= ASTContext::PSF_Write; 13665 } 13666 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) { 13667 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec) 13668 SectionFlags |= ASTContext::PSF_Implicit; 13669 UnifySection(SA->getName(), SectionFlags, var); 13670 } else if (Stack->CurrentValue) { 13671 SectionFlags |= ASTContext::PSF_Implicit; 13672 auto SectionName = Stack->CurrentValue->getString(); 13673 var->addAttr(SectionAttr::CreateImplicit( 13674 Context, SectionName, Stack->CurrentPragmaLocation, 13675 AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate)); 13676 if (UnifySection(SectionName, SectionFlags, var)) 13677 var->dropAttr<SectionAttr>(); 13678 } 13679 13680 // Apply the init_seg attribute if this has an initializer. If the 13681 // initializer turns out to not be dynamic, we'll end up ignoring this 13682 // attribute. 13683 if (CurInitSeg && var->getInit()) 13684 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 13685 CurInitSegLoc, 13686 AttributeCommonInfo::AS_Pragma)); 13687 } 13688 13689 // All the following checks are C++ only. 13690 if (!getLangOpts().CPlusPlus) { 13691 // If this variable must be emitted, add it as an initializer for the 13692 // current module. 13693 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 13694 Context.addModuleInitializer(ModuleScopes.back().Module, var); 13695 return; 13696 } 13697 13698 // Require the destructor. 13699 if (!type->isDependentType()) 13700 if (const RecordType *recordType = baseType->getAs<RecordType>()) 13701 FinalizeVarWithDestructor(var, recordType); 13702 13703 // If this variable must be emitted, add it as an initializer for the current 13704 // module. 13705 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 13706 Context.addModuleInitializer(ModuleScopes.back().Module, var); 13707 13708 // Build the bindings if this is a structured binding declaration. 13709 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 13710 CheckCompleteDecompositionDeclaration(DD); 13711 } 13712 13713 /// Check if VD needs to be dllexport/dllimport due to being in a 13714 /// dllexport/import function. 13715 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) { 13716 assert(VD->isStaticLocal()); 13717 13718 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 13719 13720 // Find outermost function when VD is in lambda function. 13721 while (FD && !getDLLAttr(FD) && 13722 !FD->hasAttr<DLLExportStaticLocalAttr>() && 13723 !FD->hasAttr<DLLImportStaticLocalAttr>()) { 13724 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod()); 13725 } 13726 13727 if (!FD) 13728 return; 13729 13730 // Static locals inherit dll attributes from their function. 13731 if (Attr *A = getDLLAttr(FD)) { 13732 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 13733 NewAttr->setInherited(true); 13734 VD->addAttr(NewAttr); 13735 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) { 13736 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A); 13737 NewAttr->setInherited(true); 13738 VD->addAttr(NewAttr); 13739 13740 // Export this function to enforce exporting this static variable even 13741 // if it is not used in this compilation unit. 13742 if (!FD->hasAttr<DLLExportAttr>()) 13743 FD->addAttr(NewAttr); 13744 13745 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) { 13746 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A); 13747 NewAttr->setInherited(true); 13748 VD->addAttr(NewAttr); 13749 } 13750 } 13751 13752 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 13753 /// any semantic actions necessary after any initializer has been attached. 13754 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 13755 // Note that we are no longer parsing the initializer for this declaration. 13756 ParsingInitForAutoVars.erase(ThisDecl); 13757 13758 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 13759 if (!VD) 13760 return; 13761 13762 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active 13763 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && 13764 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { 13765 if (PragmaClangBSSSection.Valid) 13766 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit( 13767 Context, PragmaClangBSSSection.SectionName, 13768 PragmaClangBSSSection.PragmaLocation, 13769 AttributeCommonInfo::AS_Pragma)); 13770 if (PragmaClangDataSection.Valid) 13771 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit( 13772 Context, PragmaClangDataSection.SectionName, 13773 PragmaClangDataSection.PragmaLocation, 13774 AttributeCommonInfo::AS_Pragma)); 13775 if (PragmaClangRodataSection.Valid) 13776 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit( 13777 Context, PragmaClangRodataSection.SectionName, 13778 PragmaClangRodataSection.PragmaLocation, 13779 AttributeCommonInfo::AS_Pragma)); 13780 if (PragmaClangRelroSection.Valid) 13781 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit( 13782 Context, PragmaClangRelroSection.SectionName, 13783 PragmaClangRelroSection.PragmaLocation, 13784 AttributeCommonInfo::AS_Pragma)); 13785 } 13786 13787 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 13788 for (auto *BD : DD->bindings()) { 13789 FinalizeDeclaration(BD); 13790 } 13791 } 13792 13793 checkAttributesAfterMerging(*this, *VD); 13794 13795 // Perform TLS alignment check here after attributes attached to the variable 13796 // which may affect the alignment have been processed. Only perform the check 13797 // if the target has a maximum TLS alignment (zero means no constraints). 13798 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 13799 // Protect the check so that it's not performed on dependent types and 13800 // dependent alignments (we can't determine the alignment in that case). 13801 if (VD->getTLSKind() && !VD->hasDependentAlignment()) { 13802 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 13803 if (Context.getDeclAlign(VD) > MaxAlignChars) { 13804 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 13805 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 13806 << (unsigned)MaxAlignChars.getQuantity(); 13807 } 13808 } 13809 } 13810 13811 if (VD->isStaticLocal()) 13812 CheckStaticLocalForDllExport(VD); 13813 13814 // Perform check for initializers of device-side global variables. 13815 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 13816 // 7.5). We must also apply the same checks to all __shared__ 13817 // variables whether they are local or not. CUDA also allows 13818 // constant initializers for __constant__ and __device__ variables. 13819 if (getLangOpts().CUDA) 13820 checkAllowedCUDAInitializer(VD); 13821 13822 // Grab the dllimport or dllexport attribute off of the VarDecl. 13823 const InheritableAttr *DLLAttr = getDLLAttr(VD); 13824 13825 // Imported static data members cannot be defined out-of-line. 13826 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 13827 if (VD->isStaticDataMember() && VD->isOutOfLine() && 13828 VD->isThisDeclarationADefinition()) { 13829 // We allow definitions of dllimport class template static data members 13830 // with a warning. 13831 CXXRecordDecl *Context = 13832 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 13833 bool IsClassTemplateMember = 13834 isa<ClassTemplatePartialSpecializationDecl>(Context) || 13835 Context->getDescribedClassTemplate(); 13836 13837 Diag(VD->getLocation(), 13838 IsClassTemplateMember 13839 ? diag::warn_attribute_dllimport_static_field_definition 13840 : diag::err_attribute_dllimport_static_field_definition); 13841 Diag(IA->getLocation(), diag::note_attribute); 13842 if (!IsClassTemplateMember) 13843 VD->setInvalidDecl(); 13844 } 13845 } 13846 13847 // dllimport/dllexport variables cannot be thread local, their TLS index 13848 // isn't exported with the variable. 13849 if (DLLAttr && VD->getTLSKind()) { 13850 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 13851 if (F && getDLLAttr(F)) { 13852 assert(VD->isStaticLocal()); 13853 // But if this is a static local in a dlimport/dllexport function, the 13854 // function will never be inlined, which means the var would never be 13855 // imported, so having it marked import/export is safe. 13856 } else { 13857 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 13858 << DLLAttr; 13859 VD->setInvalidDecl(); 13860 } 13861 } 13862 13863 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 13864 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 13865 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition) 13866 << Attr; 13867 VD->dropAttr<UsedAttr>(); 13868 } 13869 } 13870 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) { 13871 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 13872 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition) 13873 << Attr; 13874 VD->dropAttr<RetainAttr>(); 13875 } 13876 } 13877 13878 const DeclContext *DC = VD->getDeclContext(); 13879 // If there's a #pragma GCC visibility in scope, and this isn't a class 13880 // member, set the visibility of this variable. 13881 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 13882 AddPushedVisibilityAttribute(VD); 13883 13884 // FIXME: Warn on unused var template partial specializations. 13885 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 13886 MarkUnusedFileScopedDecl(VD); 13887 13888 // Now we have parsed the initializer and can update the table of magic 13889 // tag values. 13890 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 13891 !VD->getType()->isIntegralOrEnumerationType()) 13892 return; 13893 13894 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 13895 const Expr *MagicValueExpr = VD->getInit(); 13896 if (!MagicValueExpr) { 13897 continue; 13898 } 13899 Optional<llvm::APSInt> MagicValueInt; 13900 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) { 13901 Diag(I->getRange().getBegin(), 13902 diag::err_type_tag_for_datatype_not_ice) 13903 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13904 continue; 13905 } 13906 if (MagicValueInt->getActiveBits() > 64) { 13907 Diag(I->getRange().getBegin(), 13908 diag::err_type_tag_for_datatype_too_large) 13909 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13910 continue; 13911 } 13912 uint64_t MagicValue = MagicValueInt->getZExtValue(); 13913 RegisterTypeTagForDatatype(I->getArgumentKind(), 13914 MagicValue, 13915 I->getMatchingCType(), 13916 I->getLayoutCompatible(), 13917 I->getMustBeNull()); 13918 } 13919 } 13920 13921 static bool hasDeducedAuto(DeclaratorDecl *DD) { 13922 auto *VD = dyn_cast<VarDecl>(DD); 13923 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 13924 } 13925 13926 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 13927 ArrayRef<Decl *> Group) { 13928 SmallVector<Decl*, 8> Decls; 13929 13930 if (DS.isTypeSpecOwned()) 13931 Decls.push_back(DS.getRepAsDecl()); 13932 13933 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 13934 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 13935 bool DiagnosedMultipleDecomps = false; 13936 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 13937 bool DiagnosedNonDeducedAuto = false; 13938 13939 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13940 if (Decl *D = Group[i]) { 13941 // For declarators, there are some additional syntactic-ish checks we need 13942 // to perform. 13943 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 13944 if (!FirstDeclaratorInGroup) 13945 FirstDeclaratorInGroup = DD; 13946 if (!FirstDecompDeclaratorInGroup) 13947 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 13948 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 13949 !hasDeducedAuto(DD)) 13950 FirstNonDeducedAutoInGroup = DD; 13951 13952 if (FirstDeclaratorInGroup != DD) { 13953 // A decomposition declaration cannot be combined with any other 13954 // declaration in the same group. 13955 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 13956 Diag(FirstDecompDeclaratorInGroup->getLocation(), 13957 diag::err_decomp_decl_not_alone) 13958 << FirstDeclaratorInGroup->getSourceRange() 13959 << DD->getSourceRange(); 13960 DiagnosedMultipleDecomps = true; 13961 } 13962 13963 // A declarator that uses 'auto' in any way other than to declare a 13964 // variable with a deduced type cannot be combined with any other 13965 // declarator in the same group. 13966 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 13967 Diag(FirstNonDeducedAutoInGroup->getLocation(), 13968 diag::err_auto_non_deduced_not_alone) 13969 << FirstNonDeducedAutoInGroup->getType() 13970 ->hasAutoForTrailingReturnType() 13971 << FirstDeclaratorInGroup->getSourceRange() 13972 << DD->getSourceRange(); 13973 DiagnosedNonDeducedAuto = true; 13974 } 13975 } 13976 } 13977 13978 Decls.push_back(D); 13979 } 13980 } 13981 13982 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 13983 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 13984 handleTagNumbering(Tag, S); 13985 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 13986 getLangOpts().CPlusPlus) 13987 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 13988 } 13989 } 13990 13991 return BuildDeclaratorGroup(Decls); 13992 } 13993 13994 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 13995 /// group, performing any necessary semantic checking. 13996 Sema::DeclGroupPtrTy 13997 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 13998 // C++14 [dcl.spec.auto]p7: (DR1347) 13999 // If the type that replaces the placeholder type is not the same in each 14000 // deduction, the program is ill-formed. 14001 if (Group.size() > 1) { 14002 QualType Deduced; 14003 VarDecl *DeducedDecl = nullptr; 14004 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 14005 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 14006 if (!D || D->isInvalidDecl()) 14007 break; 14008 DeducedType *DT = D->getType()->getContainedDeducedType(); 14009 if (!DT || DT->getDeducedType().isNull()) 14010 continue; 14011 if (Deduced.isNull()) { 14012 Deduced = DT->getDeducedType(); 14013 DeducedDecl = D; 14014 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 14015 auto *AT = dyn_cast<AutoType>(DT); 14016 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 14017 diag::err_auto_different_deductions) 14018 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced 14019 << DeducedDecl->getDeclName() << DT->getDeducedType() 14020 << D->getDeclName(); 14021 if (DeducedDecl->hasInit()) 14022 Dia << DeducedDecl->getInit()->getSourceRange(); 14023 if (D->getInit()) 14024 Dia << D->getInit()->getSourceRange(); 14025 D->setInvalidDecl(); 14026 break; 14027 } 14028 } 14029 } 14030 14031 ActOnDocumentableDecls(Group); 14032 14033 return DeclGroupPtrTy::make( 14034 DeclGroupRef::Create(Context, Group.data(), Group.size())); 14035 } 14036 14037 void Sema::ActOnDocumentableDecl(Decl *D) { 14038 ActOnDocumentableDecls(D); 14039 } 14040 14041 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 14042 // Don't parse the comment if Doxygen diagnostics are ignored. 14043 if (Group.empty() || !Group[0]) 14044 return; 14045 14046 if (Diags.isIgnored(diag::warn_doc_param_not_found, 14047 Group[0]->getLocation()) && 14048 Diags.isIgnored(diag::warn_unknown_comment_command_name, 14049 Group[0]->getLocation())) 14050 return; 14051 14052 if (Group.size() >= 2) { 14053 // This is a decl group. Normally it will contain only declarations 14054 // produced from declarator list. But in case we have any definitions or 14055 // additional declaration references: 14056 // 'typedef struct S {} S;' 14057 // 'typedef struct S *S;' 14058 // 'struct S *pS;' 14059 // FinalizeDeclaratorGroup adds these as separate declarations. 14060 Decl *MaybeTagDecl = Group[0]; 14061 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 14062 Group = Group.slice(1); 14063 } 14064 } 14065 14066 // FIMXE: We assume every Decl in the group is in the same file. 14067 // This is false when preprocessor constructs the group from decls in 14068 // different files (e. g. macros or #include). 14069 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor()); 14070 } 14071 14072 /// Common checks for a parameter-declaration that should apply to both function 14073 /// parameters and non-type template parameters. 14074 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) { 14075 // Check that there are no default arguments inside the type of this 14076 // parameter. 14077 if (getLangOpts().CPlusPlus) 14078 CheckExtraCXXDefaultArguments(D); 14079 14080 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 14081 if (D.getCXXScopeSpec().isSet()) { 14082 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 14083 << D.getCXXScopeSpec().getRange(); 14084 } 14085 14086 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a 14087 // simple identifier except [...irrelevant cases...]. 14088 switch (D.getName().getKind()) { 14089 case UnqualifiedIdKind::IK_Identifier: 14090 break; 14091 14092 case UnqualifiedIdKind::IK_OperatorFunctionId: 14093 case UnqualifiedIdKind::IK_ConversionFunctionId: 14094 case UnqualifiedIdKind::IK_LiteralOperatorId: 14095 case UnqualifiedIdKind::IK_ConstructorName: 14096 case UnqualifiedIdKind::IK_DestructorName: 14097 case UnqualifiedIdKind::IK_ImplicitSelfParam: 14098 case UnqualifiedIdKind::IK_DeductionGuideName: 14099 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 14100 << GetNameForDeclarator(D).getName(); 14101 break; 14102 14103 case UnqualifiedIdKind::IK_TemplateId: 14104 case UnqualifiedIdKind::IK_ConstructorTemplateId: 14105 // GetNameForDeclarator would not produce a useful name in this case. 14106 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id); 14107 break; 14108 } 14109 } 14110 14111 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 14112 /// to introduce parameters into function prototype scope. 14113 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 14114 const DeclSpec &DS = D.getDeclSpec(); 14115 14116 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 14117 14118 // C++03 [dcl.stc]p2 also permits 'auto'. 14119 StorageClass SC = SC_None; 14120 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 14121 SC = SC_Register; 14122 // In C++11, the 'register' storage class specifier is deprecated. 14123 // In C++17, it is not allowed, but we tolerate it as an extension. 14124 if (getLangOpts().CPlusPlus11) { 14125 Diag(DS.getStorageClassSpecLoc(), 14126 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 14127 : diag::warn_deprecated_register) 14128 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 14129 } 14130 } else if (getLangOpts().CPlusPlus && 14131 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 14132 SC = SC_Auto; 14133 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 14134 Diag(DS.getStorageClassSpecLoc(), 14135 diag::err_invalid_storage_class_in_func_decl); 14136 D.getMutableDeclSpec().ClearStorageClassSpecs(); 14137 } 14138 14139 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 14140 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 14141 << DeclSpec::getSpecifierName(TSCS); 14142 if (DS.isInlineSpecified()) 14143 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 14144 << getLangOpts().CPlusPlus17; 14145 if (DS.hasConstexprSpecifier()) 14146 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 14147 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); 14148 14149 DiagnoseFunctionSpecifiers(DS); 14150 14151 CheckFunctionOrTemplateParamDeclarator(S, D); 14152 14153 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 14154 QualType parmDeclType = TInfo->getType(); 14155 14156 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 14157 IdentifierInfo *II = D.getIdentifier(); 14158 if (II) { 14159 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 14160 ForVisibleRedeclaration); 14161 LookupName(R, S); 14162 if (R.isSingleResult()) { 14163 NamedDecl *PrevDecl = R.getFoundDecl(); 14164 if (PrevDecl->isTemplateParameter()) { 14165 // Maybe we will complain about the shadowed template parameter. 14166 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 14167 // Just pretend that we didn't see the previous declaration. 14168 PrevDecl = nullptr; 14169 } else if (S->isDeclScope(PrevDecl)) { 14170 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 14171 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 14172 14173 // Recover by removing the name 14174 II = nullptr; 14175 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 14176 D.setInvalidType(true); 14177 } 14178 } 14179 } 14180 14181 // Temporarily put parameter variables in the translation unit, not 14182 // the enclosing context. This prevents them from accidentally 14183 // looking like class members in C++. 14184 ParmVarDecl *New = 14185 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(), 14186 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC); 14187 14188 if (D.isInvalidType()) 14189 New->setInvalidDecl(); 14190 14191 assert(S->isFunctionPrototypeScope()); 14192 assert(S->getFunctionPrototypeDepth() >= 1); 14193 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 14194 S->getNextFunctionPrototypeIndex()); 14195 14196 // Add the parameter declaration into this scope. 14197 S->AddDecl(New); 14198 if (II) 14199 IdResolver.AddDecl(New); 14200 14201 ProcessDeclAttributes(S, New, D); 14202 14203 if (D.getDeclSpec().isModulePrivateSpecified()) 14204 Diag(New->getLocation(), diag::err_module_private_local) 14205 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 14206 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 14207 14208 if (New->hasAttr<BlocksAttr>()) { 14209 Diag(New->getLocation(), diag::err_block_on_nonlocal); 14210 } 14211 14212 if (getLangOpts().OpenCL) 14213 deduceOpenCLAddressSpace(New); 14214 14215 return New; 14216 } 14217 14218 /// Synthesizes a variable for a parameter arising from a 14219 /// typedef. 14220 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 14221 SourceLocation Loc, 14222 QualType T) { 14223 /* FIXME: setting StartLoc == Loc. 14224 Would it be worth to modify callers so as to provide proper source 14225 location for the unnamed parameters, embedding the parameter's type? */ 14226 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 14227 T, Context.getTrivialTypeSourceInfo(T, Loc), 14228 SC_None, nullptr); 14229 Param->setImplicit(); 14230 return Param; 14231 } 14232 14233 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 14234 // Don't diagnose unused-parameter errors in template instantiations; we 14235 // will already have done so in the template itself. 14236 if (inTemplateInstantiation()) 14237 return; 14238 14239 for (const ParmVarDecl *Parameter : Parameters) { 14240 if (!Parameter->isReferenced() && Parameter->getDeclName() && 14241 !Parameter->hasAttr<UnusedAttr>()) { 14242 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 14243 << Parameter->getDeclName(); 14244 } 14245 } 14246 } 14247 14248 void Sema::DiagnoseSizeOfParametersAndReturnValue( 14249 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 14250 if (LangOpts.NumLargeByValueCopy == 0) // No check. 14251 return; 14252 14253 // Warn if the return value is pass-by-value and larger than the specified 14254 // threshold. 14255 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 14256 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 14257 if (Size > LangOpts.NumLargeByValueCopy) 14258 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size; 14259 } 14260 14261 // Warn if any parameter is pass-by-value and larger than the specified 14262 // threshold. 14263 for (const ParmVarDecl *Parameter : Parameters) { 14264 QualType T = Parameter->getType(); 14265 if (T->isDependentType() || !T.isPODType(Context)) 14266 continue; 14267 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 14268 if (Size > LangOpts.NumLargeByValueCopy) 14269 Diag(Parameter->getLocation(), diag::warn_parameter_size) 14270 << Parameter << Size; 14271 } 14272 } 14273 14274 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 14275 SourceLocation NameLoc, IdentifierInfo *Name, 14276 QualType T, TypeSourceInfo *TSInfo, 14277 StorageClass SC) { 14278 // In ARC, infer a lifetime qualifier for appropriate parameter types. 14279 if (getLangOpts().ObjCAutoRefCount && 14280 T.getObjCLifetime() == Qualifiers::OCL_None && 14281 T->isObjCLifetimeType()) { 14282 14283 Qualifiers::ObjCLifetime lifetime; 14284 14285 // Special cases for arrays: 14286 // - if it's const, use __unsafe_unretained 14287 // - otherwise, it's an error 14288 if (T->isArrayType()) { 14289 if (!T.isConstQualified()) { 14290 if (DelayedDiagnostics.shouldDelayDiagnostics()) 14291 DelayedDiagnostics.add( 14292 sema::DelayedDiagnostic::makeForbiddenType( 14293 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 14294 else 14295 Diag(NameLoc, diag::err_arc_array_param_no_ownership) 14296 << TSInfo->getTypeLoc().getSourceRange(); 14297 } 14298 lifetime = Qualifiers::OCL_ExplicitNone; 14299 } else { 14300 lifetime = T->getObjCARCImplicitLifetime(); 14301 } 14302 T = Context.getLifetimeQualifiedType(T, lifetime); 14303 } 14304 14305 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 14306 Context.getAdjustedParameterType(T), 14307 TSInfo, SC, nullptr); 14308 14309 // Make a note if we created a new pack in the scope of a lambda, so that 14310 // we know that references to that pack must also be expanded within the 14311 // lambda scope. 14312 if (New->isParameterPack()) 14313 if (auto *LSI = getEnclosingLambda()) 14314 LSI->LocalPacks.push_back(New); 14315 14316 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() || 14317 New->getType().hasNonTrivialToPrimitiveCopyCUnion()) 14318 checkNonTrivialCUnion(New->getType(), New->getLocation(), 14319 NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy); 14320 14321 // Parameters can not be abstract class types. 14322 // For record types, this is done by the AbstractClassUsageDiagnoser once 14323 // the class has been completely parsed. 14324 if (!CurContext->isRecord() && 14325 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 14326 AbstractParamType)) 14327 New->setInvalidDecl(); 14328 14329 // Parameter declarators cannot be interface types. All ObjC objects are 14330 // passed by reference. 14331 if (T->isObjCObjectType()) { 14332 SourceLocation TypeEndLoc = 14333 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc()); 14334 Diag(NameLoc, 14335 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 14336 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 14337 T = Context.getObjCObjectPointerType(T); 14338 New->setType(T); 14339 } 14340 14341 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 14342 // duration shall not be qualified by an address-space qualifier." 14343 // Since all parameters have automatic store duration, they can not have 14344 // an address space. 14345 if (T.getAddressSpace() != LangAS::Default && 14346 // OpenCL allows function arguments declared to be an array of a type 14347 // to be qualified with an address space. 14348 !(getLangOpts().OpenCL && 14349 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) { 14350 Diag(NameLoc, diag::err_arg_with_address_space); 14351 New->setInvalidDecl(); 14352 } 14353 14354 // PPC MMA non-pointer types are not allowed as function argument types. 14355 if (Context.getTargetInfo().getTriple().isPPC64() && 14356 CheckPPCMMAType(New->getOriginalType(), New->getLocation())) { 14357 New->setInvalidDecl(); 14358 } 14359 14360 return New; 14361 } 14362 14363 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 14364 SourceLocation LocAfterDecls) { 14365 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 14366 14367 // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration 14368 // in the declaration list shall have at least one declarator, those 14369 // declarators shall only declare identifiers from the identifier list, and 14370 // every identifier in the identifier list shall be declared. 14371 // 14372 // C89 3.7.1p5 "If a declarator includes an identifier list, only the 14373 // identifiers it names shall be declared in the declaration list." 14374 // 14375 // This is why we only diagnose in C99 and later. Note, the other conditions 14376 // listed are checked elsewhere. 14377 if (!FTI.hasPrototype) { 14378 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 14379 --i; 14380 if (FTI.Params[i].Param == nullptr) { 14381 if (getLangOpts().C99) { 14382 SmallString<256> Code; 14383 llvm::raw_svector_ostream(Code) 14384 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 14385 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 14386 << FTI.Params[i].Ident 14387 << FixItHint::CreateInsertion(LocAfterDecls, Code); 14388 } 14389 14390 // Implicitly declare the argument as type 'int' for lack of a better 14391 // type. 14392 AttributeFactory attrs; 14393 DeclSpec DS(attrs); 14394 const char* PrevSpec; // unused 14395 unsigned DiagID; // unused 14396 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 14397 DiagID, Context.getPrintingPolicy()); 14398 // Use the identifier location for the type source range. 14399 DS.SetRangeStart(FTI.Params[i].IdentLoc); 14400 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 14401 Declarator ParamD(DS, ParsedAttributesView::none(), 14402 DeclaratorContext::KNRTypeList); 14403 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 14404 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 14405 } 14406 } 14407 } 14408 } 14409 14410 Decl * 14411 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 14412 MultiTemplateParamsArg TemplateParameterLists, 14413 SkipBodyInfo *SkipBody, FnBodyKind BodyKind) { 14414 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 14415 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 14416 Scope *ParentScope = FnBodyScope->getParent(); 14417 14418 // Check if we are in an `omp begin/end declare variant` scope. If we are, and 14419 // we define a non-templated function definition, we will create a declaration 14420 // instead (=BaseFD), and emit the definition with a mangled name afterwards. 14421 // The base function declaration will have the equivalent of an `omp declare 14422 // variant` annotation which specifies the mangled definition as a 14423 // specialization function under the OpenMP context defined as part of the 14424 // `omp begin declare variant`. 14425 SmallVector<FunctionDecl *, 4> Bases; 14426 if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope()) 14427 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( 14428 ParentScope, D, TemplateParameterLists, Bases); 14429 14430 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition); 14431 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 14432 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind); 14433 14434 if (!Bases.empty()) 14435 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases); 14436 14437 return Dcl; 14438 } 14439 14440 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 14441 Consumer.HandleInlineFunctionDefinition(D); 14442 } 14443 14444 static bool 14445 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 14446 const FunctionDecl *&PossiblePrototype) { 14447 // Don't warn about invalid declarations. 14448 if (FD->isInvalidDecl()) 14449 return false; 14450 14451 // Or declarations that aren't global. 14452 if (!FD->isGlobal()) 14453 return false; 14454 14455 // Don't warn about C++ member functions. 14456 if (isa<CXXMethodDecl>(FD)) 14457 return false; 14458 14459 // Don't warn about 'main'. 14460 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext())) 14461 if (IdentifierInfo *II = FD->getIdentifier()) 14462 if (II->isStr("main") || II->isStr("efi_main")) 14463 return false; 14464 14465 // Don't warn about inline functions. 14466 if (FD->isInlined()) 14467 return false; 14468 14469 // Don't warn about function templates. 14470 if (FD->getDescribedFunctionTemplate()) 14471 return false; 14472 14473 // Don't warn about function template specializations. 14474 if (FD->isFunctionTemplateSpecialization()) 14475 return false; 14476 14477 // Don't warn for OpenCL kernels. 14478 if (FD->hasAttr<OpenCLKernelAttr>()) 14479 return false; 14480 14481 // Don't warn on explicitly deleted functions. 14482 if (FD->isDeleted()) 14483 return false; 14484 14485 // Don't warn on implicitly local functions (such as having local-typed 14486 // parameters). 14487 if (!FD->isExternallyVisible()) 14488 return false; 14489 14490 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 14491 Prev; Prev = Prev->getPreviousDecl()) { 14492 // Ignore any declarations that occur in function or method 14493 // scope, because they aren't visible from the header. 14494 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 14495 continue; 14496 14497 PossiblePrototype = Prev; 14498 return Prev->getType()->isFunctionNoProtoType(); 14499 } 14500 14501 return true; 14502 } 14503 14504 void 14505 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 14506 const FunctionDecl *EffectiveDefinition, 14507 SkipBodyInfo *SkipBody) { 14508 const FunctionDecl *Definition = EffectiveDefinition; 14509 if (!Definition && 14510 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true)) 14511 return; 14512 14513 if (Definition->getFriendObjectKind() != Decl::FOK_None) { 14514 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) { 14515 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { 14516 // A merged copy of the same function, instantiated as a member of 14517 // the same class, is OK. 14518 if (declaresSameEntity(OrigFD, OrigDef) && 14519 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()), 14520 cast<Decl>(FD->getLexicalDeclContext()))) 14521 return; 14522 } 14523 } 14524 } 14525 14526 if (canRedefineFunction(Definition, getLangOpts())) 14527 return; 14528 14529 // Don't emit an error when this is redefinition of a typo-corrected 14530 // definition. 14531 if (TypoCorrectedFunctionDefinitions.count(Definition)) 14532 return; 14533 14534 // If we don't have a visible definition of the function, and it's inline or 14535 // a template, skip the new definition. 14536 if (SkipBody && !hasVisibleDefinition(Definition) && 14537 (Definition->getFormalLinkage() == InternalLinkage || 14538 Definition->isInlined() || 14539 Definition->getDescribedFunctionTemplate() || 14540 Definition->getNumTemplateParameterLists())) { 14541 SkipBody->ShouldSkip = true; 14542 SkipBody->Previous = const_cast<FunctionDecl*>(Definition); 14543 if (auto *TD = Definition->getDescribedFunctionTemplate()) 14544 makeMergedDefinitionVisible(TD); 14545 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 14546 return; 14547 } 14548 14549 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 14550 Definition->getStorageClass() == SC_Extern) 14551 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 14552 << FD << getLangOpts().CPlusPlus; 14553 else 14554 Diag(FD->getLocation(), diag::err_redefinition) << FD; 14555 14556 Diag(Definition->getLocation(), diag::note_previous_definition); 14557 FD->setInvalidDecl(); 14558 } 14559 14560 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 14561 Sema &S) { 14562 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 14563 14564 LambdaScopeInfo *LSI = S.PushLambdaScope(); 14565 LSI->CallOperator = CallOperator; 14566 LSI->Lambda = LambdaClass; 14567 LSI->ReturnType = CallOperator->getReturnType(); 14568 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 14569 14570 if (LCD == LCD_None) 14571 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 14572 else if (LCD == LCD_ByCopy) 14573 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 14574 else if (LCD == LCD_ByRef) 14575 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 14576 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 14577 14578 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 14579 LSI->Mutable = !CallOperator->isConst(); 14580 14581 // Add the captures to the LSI so they can be noted as already 14582 // captured within tryCaptureVar. 14583 auto I = LambdaClass->field_begin(); 14584 for (const auto &C : LambdaClass->captures()) { 14585 if (C.capturesVariable()) { 14586 VarDecl *VD = C.getCapturedVar(); 14587 if (VD->isInitCapture()) 14588 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 14589 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 14590 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 14591 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 14592 /*EllipsisLoc*/C.isPackExpansion() 14593 ? C.getEllipsisLoc() : SourceLocation(), 14594 I->getType(), /*Invalid*/false); 14595 14596 } else if (C.capturesThis()) { 14597 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(), 14598 C.getCaptureKind() == LCK_StarThis); 14599 } else { 14600 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(), 14601 I->getType()); 14602 } 14603 ++I; 14604 } 14605 } 14606 14607 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 14608 SkipBodyInfo *SkipBody, 14609 FnBodyKind BodyKind) { 14610 if (!D) { 14611 // Parsing the function declaration failed in some way. Push on a fake scope 14612 // anyway so we can try to parse the function body. 14613 PushFunctionScope(); 14614 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 14615 return D; 14616 } 14617 14618 FunctionDecl *FD = nullptr; 14619 14620 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 14621 FD = FunTmpl->getTemplatedDecl(); 14622 else 14623 FD = cast<FunctionDecl>(D); 14624 14625 // Do not push if it is a lambda because one is already pushed when building 14626 // the lambda in ActOnStartOfLambdaDefinition(). 14627 if (!isLambdaCallOperator(FD)) 14628 PushExpressionEvaluationContext( 14629 FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated 14630 : ExprEvalContexts.back().Context); 14631 14632 // Check for defining attributes before the check for redefinition. 14633 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 14634 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 14635 FD->dropAttr<AliasAttr>(); 14636 FD->setInvalidDecl(); 14637 } 14638 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 14639 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 14640 FD->dropAttr<IFuncAttr>(); 14641 FD->setInvalidDecl(); 14642 } 14643 14644 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { 14645 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 14646 Ctor->isDefaultConstructor() && 14647 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 14648 // If this is an MS ABI dllexport default constructor, instantiate any 14649 // default arguments. 14650 InstantiateDefaultCtorDefaultArgs(Ctor); 14651 } 14652 } 14653 14654 // See if this is a redefinition. If 'will have body' (or similar) is already 14655 // set, then these checks were already performed when it was set. 14656 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() && 14657 !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) { 14658 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 14659 14660 // If we're skipping the body, we're done. Don't enter the scope. 14661 if (SkipBody && SkipBody->ShouldSkip) 14662 return D; 14663 } 14664 14665 // Mark this function as "will have a body eventually". This lets users to 14666 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 14667 // this function. 14668 FD->setWillHaveBody(); 14669 14670 // If we are instantiating a generic lambda call operator, push 14671 // a LambdaScopeInfo onto the function stack. But use the information 14672 // that's already been calculated (ActOnLambdaExpr) to prime the current 14673 // LambdaScopeInfo. 14674 // When the template operator is being specialized, the LambdaScopeInfo, 14675 // has to be properly restored so that tryCaptureVariable doesn't try 14676 // and capture any new variables. In addition when calculating potential 14677 // captures during transformation of nested lambdas, it is necessary to 14678 // have the LSI properly restored. 14679 if (isGenericLambdaCallOperatorSpecialization(FD)) { 14680 assert(inTemplateInstantiation() && 14681 "There should be an active template instantiation on the stack " 14682 "when instantiating a generic lambda!"); 14683 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 14684 } else { 14685 // Enter a new function scope 14686 PushFunctionScope(); 14687 } 14688 14689 // Builtin functions cannot be defined. 14690 if (unsigned BuiltinID = FD->getBuiltinID()) { 14691 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 14692 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 14693 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 14694 FD->setInvalidDecl(); 14695 } 14696 } 14697 14698 // The return type of a function definition must be complete (C99 6.9.1p3), 14699 // unless the function is deleted (C++ specifc, C++ [dcl.fct.def.general]p2) 14700 QualType ResultType = FD->getReturnType(); 14701 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 14702 !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete && 14703 RequireCompleteType(FD->getLocation(), ResultType, 14704 diag::err_func_def_incomplete_result)) 14705 FD->setInvalidDecl(); 14706 14707 if (FnBodyScope) 14708 PushDeclContext(FnBodyScope, FD); 14709 14710 // Check the validity of our function parameters 14711 if (BodyKind != FnBodyKind::Delete) 14712 CheckParmsForFunctionDef(FD->parameters(), 14713 /*CheckParameterNames=*/true); 14714 14715 // Add non-parameter declarations already in the function to the current 14716 // scope. 14717 if (FnBodyScope) { 14718 for (Decl *NPD : FD->decls()) { 14719 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 14720 if (!NonParmDecl) 14721 continue; 14722 assert(!isa<ParmVarDecl>(NonParmDecl) && 14723 "parameters should not be in newly created FD yet"); 14724 14725 // If the decl has a name, make it accessible in the current scope. 14726 if (NonParmDecl->getDeclName()) 14727 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 14728 14729 // Similarly, dive into enums and fish their constants out, making them 14730 // accessible in this scope. 14731 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 14732 for (auto *EI : ED->enumerators()) 14733 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 14734 } 14735 } 14736 } 14737 14738 // Introduce our parameters into the function scope 14739 for (auto Param : FD->parameters()) { 14740 Param->setOwningFunction(FD); 14741 14742 // If this has an identifier, add it to the scope stack. 14743 if (Param->getIdentifier() && FnBodyScope) { 14744 CheckShadow(FnBodyScope, Param); 14745 14746 PushOnScopeChains(Param, FnBodyScope); 14747 } 14748 } 14749 14750 // Ensure that the function's exception specification is instantiated. 14751 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 14752 ResolveExceptionSpec(D->getLocation(), FPT); 14753 14754 // dllimport cannot be applied to non-inline function definitions. 14755 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 14756 !FD->isTemplateInstantiation()) { 14757 assert(!FD->hasAttr<DLLExportAttr>()); 14758 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 14759 FD->setInvalidDecl(); 14760 return D; 14761 } 14762 // We want to attach documentation to original Decl (which might be 14763 // a function template). 14764 ActOnDocumentableDecl(D); 14765 if (getCurLexicalContext()->isObjCContainer() && 14766 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 14767 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 14768 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 14769 14770 return D; 14771 } 14772 14773 /// Given the set of return statements within a function body, 14774 /// compute the variables that are subject to the named return value 14775 /// optimization. 14776 /// 14777 /// Each of the variables that is subject to the named return value 14778 /// optimization will be marked as NRVO variables in the AST, and any 14779 /// return statement that has a marked NRVO variable as its NRVO candidate can 14780 /// use the named return value optimization. 14781 /// 14782 /// This function applies a very simplistic algorithm for NRVO: if every return 14783 /// statement in the scope of a variable has the same NRVO candidate, that 14784 /// candidate is an NRVO variable. 14785 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 14786 ReturnStmt **Returns = Scope->Returns.data(); 14787 14788 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 14789 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 14790 if (!NRVOCandidate->isNRVOVariable()) 14791 Returns[I]->setNRVOCandidate(nullptr); 14792 } 14793 } 14794 } 14795 14796 bool Sema::canDelayFunctionBody(const Declarator &D) { 14797 // We can't delay parsing the body of a constexpr function template (yet). 14798 if (D.getDeclSpec().hasConstexprSpecifier()) 14799 return false; 14800 14801 // We can't delay parsing the body of a function template with a deduced 14802 // return type (yet). 14803 if (D.getDeclSpec().hasAutoTypeSpec()) { 14804 // If the placeholder introduces a non-deduced trailing return type, 14805 // we can still delay parsing it. 14806 if (D.getNumTypeObjects()) { 14807 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 14808 if (Outer.Kind == DeclaratorChunk::Function && 14809 Outer.Fun.hasTrailingReturnType()) { 14810 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 14811 return Ty.isNull() || !Ty->isUndeducedType(); 14812 } 14813 } 14814 return false; 14815 } 14816 14817 return true; 14818 } 14819 14820 bool Sema::canSkipFunctionBody(Decl *D) { 14821 // We cannot skip the body of a function (or function template) which is 14822 // constexpr, since we may need to evaluate its body in order to parse the 14823 // rest of the file. 14824 // We cannot skip the body of a function with an undeduced return type, 14825 // because any callers of that function need to know the type. 14826 if (const FunctionDecl *FD = D->getAsFunction()) { 14827 if (FD->isConstexpr()) 14828 return false; 14829 // We can't simply call Type::isUndeducedType here, because inside template 14830 // auto can be deduced to a dependent type, which is not considered 14831 // "undeduced". 14832 if (FD->getReturnType()->getContainedDeducedType()) 14833 return false; 14834 } 14835 return Consumer.shouldSkipFunctionBody(D); 14836 } 14837 14838 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 14839 if (!Decl) 14840 return nullptr; 14841 if (FunctionDecl *FD = Decl->getAsFunction()) 14842 FD->setHasSkippedBody(); 14843 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) 14844 MD->setHasSkippedBody(); 14845 return Decl; 14846 } 14847 14848 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 14849 return ActOnFinishFunctionBody(D, BodyArg, false); 14850 } 14851 14852 /// RAII object that pops an ExpressionEvaluationContext when exiting a function 14853 /// body. 14854 class ExitFunctionBodyRAII { 14855 public: 14856 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {} 14857 ~ExitFunctionBodyRAII() { 14858 if (!IsLambda) 14859 S.PopExpressionEvaluationContext(); 14860 } 14861 14862 private: 14863 Sema &S; 14864 bool IsLambda = false; 14865 }; 14866 14867 static void diagnoseImplicitlyRetainedSelf(Sema &S) { 14868 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo; 14869 14870 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) { 14871 if (EscapeInfo.count(BD)) 14872 return EscapeInfo[BD]; 14873 14874 bool R = false; 14875 const BlockDecl *CurBD = BD; 14876 14877 do { 14878 R = !CurBD->doesNotEscape(); 14879 if (R) 14880 break; 14881 CurBD = CurBD->getParent()->getInnermostBlockDecl(); 14882 } while (CurBD); 14883 14884 return EscapeInfo[BD] = R; 14885 }; 14886 14887 // If the location where 'self' is implicitly retained is inside a escaping 14888 // block, emit a diagnostic. 14889 for (const std::pair<SourceLocation, const BlockDecl *> &P : 14890 S.ImplicitlyRetainedSelfLocs) 14891 if (IsOrNestedInEscapingBlock(P.second)) 14892 S.Diag(P.first, diag::warn_implicitly_retains_self) 14893 << FixItHint::CreateInsertion(P.first, "self->"); 14894 } 14895 14896 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 14897 bool IsInstantiation) { 14898 FunctionScopeInfo *FSI = getCurFunction(); 14899 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 14900 14901 if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>()) 14902 FD->addAttr(StrictFPAttr::CreateImplicit(Context)); 14903 14904 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 14905 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 14906 14907 if (getLangOpts().Coroutines && FSI->isCoroutine()) 14908 CheckCompletedCoroutineBody(FD, Body); 14909 14910 { 14911 // Do not call PopExpressionEvaluationContext() if it is a lambda because 14912 // one is already popped when finishing the lambda in BuildLambdaExpr(). 14913 // This is meant to pop the context added in ActOnStartOfFunctionDef(). 14914 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD)); 14915 14916 if (FD) { 14917 FD->setBody(Body); 14918 FD->setWillHaveBody(false); 14919 14920 if (getLangOpts().CPlusPlus14) { 14921 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 14922 FD->getReturnType()->isUndeducedType()) { 14923 // For a function with a deduced result type to return void, 14924 // the result type as written must be 'auto' or 'decltype(auto)', 14925 // possibly cv-qualified or constrained, but not ref-qualified. 14926 if (!FD->getReturnType()->getAs<AutoType>()) { 14927 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 14928 << FD->getReturnType(); 14929 FD->setInvalidDecl(); 14930 } else { 14931 // Falling off the end of the function is the same as 'return;'. 14932 Expr *Dummy = nullptr; 14933 if (DeduceFunctionTypeFromReturnExpr( 14934 FD, dcl->getLocation(), Dummy, 14935 FD->getReturnType()->getAs<AutoType>())) 14936 FD->setInvalidDecl(); 14937 } 14938 } 14939 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 14940 // In C++11, we don't use 'auto' deduction rules for lambda call 14941 // operators because we don't support return type deduction. 14942 auto *LSI = getCurLambda(); 14943 if (LSI->HasImplicitReturnType) { 14944 deduceClosureReturnType(*LSI); 14945 14946 // C++11 [expr.prim.lambda]p4: 14947 // [...] if there are no return statements in the compound-statement 14948 // [the deduced type is] the type void 14949 QualType RetType = 14950 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 14951 14952 // Update the return type to the deduced type. 14953 const auto *Proto = FD->getType()->castAs<FunctionProtoType>(); 14954 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 14955 Proto->getExtProtoInfo())); 14956 } 14957 } 14958 14959 // If the function implicitly returns zero (like 'main') or is naked, 14960 // don't complain about missing return statements. 14961 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 14962 WP.disableCheckFallThrough(); 14963 14964 // MSVC permits the use of pure specifier (=0) on function definition, 14965 // defined at class scope, warn about this non-standard construct. 14966 if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine()) 14967 Diag(FD->getLocation(), diag::ext_pure_function_definition); 14968 14969 if (!FD->isInvalidDecl()) { 14970 // Don't diagnose unused parameters of defaulted, deleted or naked 14971 // functions. 14972 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() && 14973 !FD->hasAttr<NakedAttr>()) 14974 DiagnoseUnusedParameters(FD->parameters()); 14975 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 14976 FD->getReturnType(), FD); 14977 14978 // If this is a structor, we need a vtable. 14979 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 14980 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 14981 else if (CXXDestructorDecl *Destructor = 14982 dyn_cast<CXXDestructorDecl>(FD)) 14983 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 14984 14985 // Try to apply the named return value optimization. We have to check 14986 // if we can do this here because lambdas keep return statements around 14987 // to deduce an implicit return type. 14988 if (FD->getReturnType()->isRecordType() && 14989 (!getLangOpts().CPlusPlus || !FD->isDependentContext())) 14990 computeNRVO(Body, FSI); 14991 } 14992 14993 // GNU warning -Wmissing-prototypes: 14994 // Warn if a global function is defined without a previous 14995 // prototype declaration. This warning is issued even if the 14996 // definition itself provides a prototype. The aim is to detect 14997 // global functions that fail to be declared in header files. 14998 const FunctionDecl *PossiblePrototype = nullptr; 14999 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) { 15000 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 15001 15002 if (PossiblePrototype) { 15003 // We found a declaration that is not a prototype, 15004 // but that could be a zero-parameter prototype 15005 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) { 15006 TypeLoc TL = TI->getTypeLoc(); 15007 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 15008 Diag(PossiblePrototype->getLocation(), 15009 diag::note_declaration_not_a_prototype) 15010 << (FD->getNumParams() != 0) 15011 << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion( 15012 FTL.getRParenLoc(), "void") 15013 : FixItHint{}); 15014 } 15015 } else { 15016 // Returns true if the token beginning at this Loc is `const`. 15017 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM, 15018 const LangOptions &LangOpts) { 15019 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); 15020 if (LocInfo.first.isInvalid()) 15021 return false; 15022 15023 bool Invalid = false; 15024 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid); 15025 if (Invalid) 15026 return false; 15027 15028 if (LocInfo.second > Buffer.size()) 15029 return false; 15030 15031 const char *LexStart = Buffer.data() + LocInfo.second; 15032 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second); 15033 15034 return StartTok.consume_front("const") && 15035 (StartTok.empty() || isWhitespace(StartTok[0]) || 15036 StartTok.startswith("/*") || StartTok.startswith("//")); 15037 }; 15038 15039 auto findBeginLoc = [&]() { 15040 // If the return type has `const` qualifier, we want to insert 15041 // `static` before `const` (and not before the typename). 15042 if ((FD->getReturnType()->isAnyPointerType() && 15043 FD->getReturnType()->getPointeeType().isConstQualified()) || 15044 FD->getReturnType().isConstQualified()) { 15045 // But only do this if we can determine where the `const` is. 15046 15047 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(), 15048 getLangOpts())) 15049 15050 return FD->getBeginLoc(); 15051 } 15052 return FD->getTypeSpecStartLoc(); 15053 }; 15054 Diag(FD->getTypeSpecStartLoc(), 15055 diag::note_static_for_internal_linkage) 15056 << /* function */ 1 15057 << (FD->getStorageClass() == SC_None 15058 ? FixItHint::CreateInsertion(findBeginLoc(), "static ") 15059 : FixItHint{}); 15060 } 15061 } 15062 15063 // If the function being defined does not have a prototype, then we may 15064 // need to diagnose it as changing behavior in C2x because we now know 15065 // whether the function accepts arguments or not. This only handles the 15066 // case where the definition has no prototype but does have parameters 15067 // and either there is no previous potential prototype, or the previous 15068 // potential prototype also has no actual prototype. This handles cases 15069 // like: 15070 // void f(); void f(a) int a; {} 15071 // void g(a) int a; {} 15072 // See MergeFunctionDecl() for other cases of the behavior change 15073 // diagnostic. See GetFullTypeForDeclarator() for handling of a function 15074 // type without a prototype. 15075 if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 && 15076 (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() && 15077 !PossiblePrototype->isImplicit()))) { 15078 // The function definition has parameters, so this will change behavior 15079 // in C2x. If there is a possible prototype, it comes before the 15080 // function definition. 15081 // FIXME: The declaration may have already been diagnosed as being 15082 // deprecated in GetFullTypeForDeclarator() if it had no arguments, but 15083 // there's no way to test for the "changes behavior" condition in 15084 // SemaType.cpp when forming the declaration's function type. So, we do 15085 // this awkward dance instead. 15086 // 15087 // If we have a possible prototype and it declares a function with a 15088 // prototype, we don't want to diagnose it; if we have a possible 15089 // prototype and it has no prototype, it may have already been 15090 // diagnosed in SemaType.cpp as deprecated depending on whether 15091 // -Wstrict-prototypes is enabled. If we already warned about it being 15092 // deprecated, add a note that it also changes behavior. If we didn't 15093 // warn about it being deprecated (because the diagnostic is not 15094 // enabled), warn now that it is deprecated and changes behavior. 15095 15096 // This K&R C function definition definitely changes behavior in C2x, 15097 // so diagnose it. 15098 Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior) 15099 << /*definition*/ 1 << /* not supported in C2x */ 0; 15100 15101 // If we have a possible prototype for the function which is a user- 15102 // visible declaration, we already tested that it has no prototype. 15103 // This will change behavior in C2x. This gets a warning rather than a 15104 // note because it's the same behavior-changing problem as with the 15105 // definition. 15106 if (PossiblePrototype) 15107 Diag(PossiblePrototype->getLocation(), 15108 diag::warn_non_prototype_changes_behavior) 15109 << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1 15110 << /*definition*/ 1; 15111 } 15112 15113 // Warn on CPUDispatch with an actual body. 15114 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body) 15115 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body)) 15116 if (!CmpndBody->body_empty()) 15117 Diag(CmpndBody->body_front()->getBeginLoc(), 15118 diag::warn_dispatch_body_ignored); 15119 15120 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 15121 const CXXMethodDecl *KeyFunction; 15122 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 15123 MD->isVirtual() && 15124 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 15125 MD == KeyFunction->getCanonicalDecl()) { 15126 // Update the key-function state if necessary for this ABI. 15127 if (FD->isInlined() && 15128 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 15129 Context.setNonKeyFunction(MD); 15130 15131 // If the newly-chosen key function is already defined, then we 15132 // need to mark the vtable as used retroactively. 15133 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 15134 const FunctionDecl *Definition; 15135 if (KeyFunction && KeyFunction->isDefined(Definition)) 15136 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 15137 } else { 15138 // We just defined they key function; mark the vtable as used. 15139 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 15140 } 15141 } 15142 } 15143 15144 assert( 15145 (FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 15146 "Function parsing confused"); 15147 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 15148 assert(MD == getCurMethodDecl() && "Method parsing confused"); 15149 MD->setBody(Body); 15150 if (!MD->isInvalidDecl()) { 15151 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 15152 MD->getReturnType(), MD); 15153 15154 if (Body) 15155 computeNRVO(Body, FSI); 15156 } 15157 if (FSI->ObjCShouldCallSuper) { 15158 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call) 15159 << MD->getSelector().getAsString(); 15160 FSI->ObjCShouldCallSuper = false; 15161 } 15162 if (FSI->ObjCWarnForNoDesignatedInitChain) { 15163 const ObjCMethodDecl *InitMethod = nullptr; 15164 bool isDesignated = 15165 MD->isDesignatedInitializerForTheInterface(&InitMethod); 15166 assert(isDesignated && InitMethod); 15167 (void)isDesignated; 15168 15169 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 15170 auto IFace = MD->getClassInterface(); 15171 if (!IFace) 15172 return false; 15173 auto SuperD = IFace->getSuperClass(); 15174 if (!SuperD) 15175 return false; 15176 return SuperD->getIdentifier() == 15177 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 15178 }; 15179 // Don't issue this warning for unavailable inits or direct subclasses 15180 // of NSObject. 15181 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 15182 Diag(MD->getLocation(), 15183 diag::warn_objc_designated_init_missing_super_call); 15184 Diag(InitMethod->getLocation(), 15185 diag::note_objc_designated_init_marked_here); 15186 } 15187 FSI->ObjCWarnForNoDesignatedInitChain = false; 15188 } 15189 if (FSI->ObjCWarnForNoInitDelegation) { 15190 // Don't issue this warning for unavaialable inits. 15191 if (!MD->isUnavailable()) 15192 Diag(MD->getLocation(), 15193 diag::warn_objc_secondary_init_missing_init_call); 15194 FSI->ObjCWarnForNoInitDelegation = false; 15195 } 15196 15197 diagnoseImplicitlyRetainedSelf(*this); 15198 } else { 15199 // Parsing the function declaration failed in some way. Pop the fake scope 15200 // we pushed on. 15201 PopFunctionScopeInfo(ActivePolicy, dcl); 15202 return nullptr; 15203 } 15204 15205 if (Body && FSI->HasPotentialAvailabilityViolations) 15206 DiagnoseUnguardedAvailabilityViolations(dcl); 15207 15208 assert(!FSI->ObjCShouldCallSuper && 15209 "This should only be set for ObjC methods, which should have been " 15210 "handled in the block above."); 15211 15212 // Verify and clean out per-function state. 15213 if (Body && (!FD || !FD->isDefaulted())) { 15214 // C++ constructors that have function-try-blocks can't have return 15215 // statements in the handlers of that block. (C++ [except.handle]p14) 15216 // Verify this. 15217 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 15218 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 15219 15220 // Verify that gotos and switch cases don't jump into scopes illegally. 15221 if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled()) 15222 DiagnoseInvalidJumps(Body); 15223 15224 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 15225 if (!Destructor->getParent()->isDependentType()) 15226 CheckDestructor(Destructor); 15227 15228 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 15229 Destructor->getParent()); 15230 } 15231 15232 // If any errors have occurred, clear out any temporaries that may have 15233 // been leftover. This ensures that these temporaries won't be picked up 15234 // for deletion in some later function. 15235 if (hasUncompilableErrorOccurred() || 15236 getDiagnostics().getSuppressAllDiagnostics()) { 15237 DiscardCleanupsInEvaluationContext(); 15238 } 15239 if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) { 15240 // Since the body is valid, issue any analysis-based warnings that are 15241 // enabled. 15242 ActivePolicy = &WP; 15243 } 15244 15245 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 15246 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose)) 15247 FD->setInvalidDecl(); 15248 15249 if (FD && FD->hasAttr<NakedAttr>()) { 15250 for (const Stmt *S : Body->children()) { 15251 // Allow local register variables without initializer as they don't 15252 // require prologue. 15253 bool RegisterVariables = false; 15254 if (auto *DS = dyn_cast<DeclStmt>(S)) { 15255 for (const auto *Decl : DS->decls()) { 15256 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 15257 RegisterVariables = 15258 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 15259 if (!RegisterVariables) 15260 break; 15261 } 15262 } 15263 } 15264 if (RegisterVariables) 15265 continue; 15266 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 15267 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function); 15268 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 15269 FD->setInvalidDecl(); 15270 break; 15271 } 15272 } 15273 } 15274 15275 assert(ExprCleanupObjects.size() == 15276 ExprEvalContexts.back().NumCleanupObjects && 15277 "Leftover temporaries in function"); 15278 assert(!Cleanup.exprNeedsCleanups() && 15279 "Unaccounted cleanups in function"); 15280 assert(MaybeODRUseExprs.empty() && 15281 "Leftover expressions for odr-use checking"); 15282 } 15283 } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop 15284 // the declaration context below. Otherwise, we're unable to transform 15285 // 'this' expressions when transforming immediate context functions. 15286 15287 if (!IsInstantiation) 15288 PopDeclContext(); 15289 15290 PopFunctionScopeInfo(ActivePolicy, dcl); 15291 // If any errors have occurred, clear out any temporaries that may have 15292 // been leftover. This ensures that these temporaries won't be picked up for 15293 // deletion in some later function. 15294 if (hasUncompilableErrorOccurred()) { 15295 DiscardCleanupsInEvaluationContext(); 15296 } 15297 15298 if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsDevice || 15299 !LangOpts.OMPTargetTriples.empty())) || 15300 LangOpts.CUDA || LangOpts.SYCLIsDevice)) { 15301 auto ES = getEmissionStatus(FD); 15302 if (ES == Sema::FunctionEmissionStatus::Emitted || 15303 ES == Sema::FunctionEmissionStatus::Unknown) 15304 DeclsToCheckForDeferredDiags.insert(FD); 15305 } 15306 15307 if (FD && !FD->isDeleted()) 15308 checkTypeSupport(FD->getType(), FD->getLocation(), FD); 15309 15310 return dcl; 15311 } 15312 15313 /// When we finish delayed parsing of an attribute, we must attach it to the 15314 /// relevant Decl. 15315 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 15316 ParsedAttributes &Attrs) { 15317 // Always attach attributes to the underlying decl. 15318 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 15319 D = TD->getTemplatedDecl(); 15320 ProcessDeclAttributeList(S, D, Attrs); 15321 15322 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 15323 if (Method->isStatic()) 15324 checkThisInStaticMemberFunctionAttributes(Method); 15325 } 15326 15327 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 15328 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 15329 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 15330 IdentifierInfo &II, Scope *S) { 15331 // It is not valid to implicitly define a function in C2x. 15332 assert(LangOpts.implicitFunctionsAllowed() && 15333 "Implicit function declarations aren't allowed in this language mode"); 15334 15335 // Find the scope in which the identifier is injected and the corresponding 15336 // DeclContext. 15337 // FIXME: C89 does not say what happens if there is no enclosing block scope. 15338 // In that case, we inject the declaration into the translation unit scope 15339 // instead. 15340 Scope *BlockScope = S; 15341 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) 15342 BlockScope = BlockScope->getParent(); 15343 15344 Scope *ContextScope = BlockScope; 15345 while (!ContextScope->getEntity()) 15346 ContextScope = ContextScope->getParent(); 15347 ContextRAII SavedContext(*this, ContextScope->getEntity()); 15348 15349 // Before we produce a declaration for an implicitly defined 15350 // function, see whether there was a locally-scoped declaration of 15351 // this name as a function or variable. If so, use that 15352 // (non-visible) declaration, and complain about it. 15353 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); 15354 if (ExternCPrev) { 15355 // We still need to inject the function into the enclosing block scope so 15356 // that later (non-call) uses can see it. 15357 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); 15358 15359 // C89 footnote 38: 15360 // If in fact it is not defined as having type "function returning int", 15361 // the behavior is undefined. 15362 if (!isa<FunctionDecl>(ExternCPrev) || 15363 !Context.typesAreCompatible( 15364 cast<FunctionDecl>(ExternCPrev)->getType(), 15365 Context.getFunctionNoProtoType(Context.IntTy))) { 15366 Diag(Loc, diag::ext_use_out_of_scope_declaration) 15367 << ExternCPrev << !getLangOpts().C99; 15368 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 15369 return ExternCPrev; 15370 } 15371 } 15372 15373 // Extension in C99 (defaults to error). Legal in C89, but warn about it. 15374 unsigned diag_id; 15375 if (II.getName().startswith("__builtin_")) 15376 diag_id = diag::warn_builtin_unknown; 15377 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. 15378 else if (getLangOpts().C99) 15379 diag_id = diag::ext_implicit_function_decl_c99; 15380 else 15381 diag_id = diag::warn_implicit_function_decl; 15382 15383 TypoCorrection Corrected; 15384 // Because typo correction is expensive, only do it if the implicit 15385 // function declaration is going to be treated as an error. 15386 // 15387 // Perform the corection before issuing the main diagnostic, as some consumers 15388 // use typo-correction callbacks to enhance the main diagnostic. 15389 if (S && !ExternCPrev && 15390 (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) { 15391 DeclFilterCCC<FunctionDecl> CCC{}; 15392 Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName, 15393 S, nullptr, CCC, CTK_NonError); 15394 } 15395 15396 Diag(Loc, diag_id) << &II; 15397 if (Corrected) { 15398 // If the correction is going to suggest an implicitly defined function, 15399 // skip the correction as not being a particularly good idea. 15400 bool Diagnose = true; 15401 if (const auto *D = Corrected.getCorrectionDecl()) 15402 Diagnose = !D->isImplicit(); 15403 if (Diagnose) 15404 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 15405 /*ErrorRecovery*/ false); 15406 } 15407 15408 // If we found a prior declaration of this function, don't bother building 15409 // another one. We've already pushed that one into scope, so there's nothing 15410 // more to do. 15411 if (ExternCPrev) 15412 return ExternCPrev; 15413 15414 // Set a Declarator for the implicit definition: int foo(); 15415 const char *Dummy; 15416 AttributeFactory attrFactory; 15417 DeclSpec DS(attrFactory); 15418 unsigned DiagID; 15419 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 15420 Context.getPrintingPolicy()); 15421 (void)Error; // Silence warning. 15422 assert(!Error && "Error setting up implicit decl!"); 15423 SourceLocation NoLoc; 15424 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::Block); 15425 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 15426 /*IsAmbiguous=*/false, 15427 /*LParenLoc=*/NoLoc, 15428 /*Params=*/nullptr, 15429 /*NumParams=*/0, 15430 /*EllipsisLoc=*/NoLoc, 15431 /*RParenLoc=*/NoLoc, 15432 /*RefQualifierIsLvalueRef=*/true, 15433 /*RefQualifierLoc=*/NoLoc, 15434 /*MutableLoc=*/NoLoc, EST_None, 15435 /*ESpecRange=*/SourceRange(), 15436 /*Exceptions=*/nullptr, 15437 /*ExceptionRanges=*/nullptr, 15438 /*NumExceptions=*/0, 15439 /*NoexceptExpr=*/nullptr, 15440 /*ExceptionSpecTokens=*/nullptr, 15441 /*DeclsInPrototype=*/None, Loc, 15442 Loc, D), 15443 std::move(DS.getAttributes()), SourceLocation()); 15444 D.SetIdentifier(&II, Loc); 15445 15446 // Insert this function into the enclosing block scope. 15447 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); 15448 FD->setImplicit(); 15449 15450 AddKnownFunctionAttributes(FD); 15451 15452 return FD; 15453 } 15454 15455 /// If this function is a C++ replaceable global allocation function 15456 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]), 15457 /// adds any function attributes that we know a priori based on the standard. 15458 /// 15459 /// We need to check for duplicate attributes both here and where user-written 15460 /// attributes are applied to declarations. 15461 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction( 15462 FunctionDecl *FD) { 15463 if (FD->isInvalidDecl()) 15464 return; 15465 15466 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New && 15467 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New) 15468 return; 15469 15470 Optional<unsigned> AlignmentParam; 15471 bool IsNothrow = false; 15472 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow)) 15473 return; 15474 15475 // C++2a [basic.stc.dynamic.allocation]p4: 15476 // An allocation function that has a non-throwing exception specification 15477 // indicates failure by returning a null pointer value. Any other allocation 15478 // function never returns a null pointer value and indicates failure only by 15479 // throwing an exception [...] 15480 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>()) 15481 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation())); 15482 15483 // C++2a [basic.stc.dynamic.allocation]p2: 15484 // An allocation function attempts to allocate the requested amount of 15485 // storage. [...] If the request succeeds, the value returned by a 15486 // replaceable allocation function is a [...] pointer value p0 different 15487 // from any previously returned value p1 [...] 15488 // 15489 // However, this particular information is being added in codegen, 15490 // because there is an opt-out switch for it (-fno-assume-sane-operator-new) 15491 15492 // C++2a [basic.stc.dynamic.allocation]p2: 15493 // An allocation function attempts to allocate the requested amount of 15494 // storage. If it is successful, it returns the address of the start of a 15495 // block of storage whose length in bytes is at least as large as the 15496 // requested size. 15497 if (!FD->hasAttr<AllocSizeAttr>()) { 15498 FD->addAttr(AllocSizeAttr::CreateImplicit( 15499 Context, /*ElemSizeParam=*/ParamIdx(1, FD), 15500 /*NumElemsParam=*/ParamIdx(), FD->getLocation())); 15501 } 15502 15503 // C++2a [basic.stc.dynamic.allocation]p3: 15504 // For an allocation function [...], the pointer returned on a successful 15505 // call shall represent the address of storage that is aligned as follows: 15506 // (3.1) If the allocation function takes an argument of type 15507 // std::align_val_t, the storage will have the alignment 15508 // specified by the value of this argument. 15509 if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) { 15510 FD->addAttr(AllocAlignAttr::CreateImplicit( 15511 Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation())); 15512 } 15513 15514 // FIXME: 15515 // C++2a [basic.stc.dynamic.allocation]p3: 15516 // For an allocation function [...], the pointer returned on a successful 15517 // call shall represent the address of storage that is aligned as follows: 15518 // (3.2) Otherwise, if the allocation function is named operator new[], 15519 // the storage is aligned for any object that does not have 15520 // new-extended alignment ([basic.align]) and is no larger than the 15521 // requested size. 15522 // (3.3) Otherwise, the storage is aligned for any object that does not 15523 // have new-extended alignment and is of the requested size. 15524 } 15525 15526 /// Adds any function attributes that we know a priori based on 15527 /// the declaration of this function. 15528 /// 15529 /// These attributes can apply both to implicitly-declared builtins 15530 /// (like __builtin___printf_chk) or to library-declared functions 15531 /// like NSLog or printf. 15532 /// 15533 /// We need to check for duplicate attributes both here and where user-written 15534 /// attributes are applied to declarations. 15535 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 15536 if (FD->isInvalidDecl()) 15537 return; 15538 15539 // If this is a built-in function, map its builtin attributes to 15540 // actual attributes. 15541 if (unsigned BuiltinID = FD->getBuiltinID()) { 15542 // Handle printf-formatting attributes. 15543 unsigned FormatIdx; 15544 bool HasVAListArg; 15545 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 15546 if (!FD->hasAttr<FormatAttr>()) { 15547 const char *fmt = "printf"; 15548 unsigned int NumParams = FD->getNumParams(); 15549 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 15550 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 15551 fmt = "NSString"; 15552 FD->addAttr(FormatAttr::CreateImplicit(Context, 15553 &Context.Idents.get(fmt), 15554 FormatIdx+1, 15555 HasVAListArg ? 0 : FormatIdx+2, 15556 FD->getLocation())); 15557 } 15558 } 15559 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 15560 HasVAListArg)) { 15561 if (!FD->hasAttr<FormatAttr>()) 15562 FD->addAttr(FormatAttr::CreateImplicit(Context, 15563 &Context.Idents.get("scanf"), 15564 FormatIdx+1, 15565 HasVAListArg ? 0 : FormatIdx+2, 15566 FD->getLocation())); 15567 } 15568 15569 // Handle automatically recognized callbacks. 15570 SmallVector<int, 4> Encoding; 15571 if (!FD->hasAttr<CallbackAttr>() && 15572 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding)) 15573 FD->addAttr(CallbackAttr::CreateImplicit( 15574 Context, Encoding.data(), Encoding.size(), FD->getLocation())); 15575 15576 // Mark const if we don't care about errno and that is the only thing 15577 // preventing the function from being const. This allows IRgen to use LLVM 15578 // intrinsics for such functions. 15579 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() && 15580 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) 15581 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 15582 15583 // We make "fma" on GNU or Windows const because we know it does not set 15584 // errno in those environments even though it could set errno based on the 15585 // C standard. 15586 const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); 15587 if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) && 15588 !FD->hasAttr<ConstAttr>()) { 15589 switch (BuiltinID) { 15590 case Builtin::BI__builtin_fma: 15591 case Builtin::BI__builtin_fmaf: 15592 case Builtin::BI__builtin_fmal: 15593 case Builtin::BIfma: 15594 case Builtin::BIfmaf: 15595 case Builtin::BIfmal: 15596 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 15597 break; 15598 default: 15599 break; 15600 } 15601 } 15602 15603 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 15604 !FD->hasAttr<ReturnsTwiceAttr>()) 15605 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 15606 FD->getLocation())); 15607 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 15608 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 15609 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 15610 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 15611 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 15612 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 15613 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 15614 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 15615 // Add the appropriate attribute, depending on the CUDA compilation mode 15616 // and which target the builtin belongs to. For example, during host 15617 // compilation, aux builtins are __device__, while the rest are __host__. 15618 if (getLangOpts().CUDAIsDevice != 15619 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 15620 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 15621 else 15622 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 15623 } 15624 15625 // Add known guaranteed alignment for allocation functions. 15626 switch (BuiltinID) { 15627 case Builtin::BImemalign: 15628 case Builtin::BIaligned_alloc: 15629 if (!FD->hasAttr<AllocAlignAttr>()) 15630 FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD), 15631 FD->getLocation())); 15632 break; 15633 default: 15634 break; 15635 } 15636 15637 // Add allocsize attribute for allocation functions. 15638 switch (BuiltinID) { 15639 case Builtin::BIcalloc: 15640 FD->addAttr(AllocSizeAttr::CreateImplicit( 15641 Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation())); 15642 break; 15643 case Builtin::BImemalign: 15644 case Builtin::BIaligned_alloc: 15645 case Builtin::BIrealloc: 15646 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD), 15647 ParamIdx(), FD->getLocation())); 15648 break; 15649 case Builtin::BImalloc: 15650 FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD), 15651 ParamIdx(), FD->getLocation())); 15652 break; 15653 default: 15654 break; 15655 } 15656 } 15657 15658 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD); 15659 15660 // If C++ exceptions are enabled but we are told extern "C" functions cannot 15661 // throw, add an implicit nothrow attribute to any extern "C" function we come 15662 // across. 15663 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 15664 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 15665 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 15666 if (!FPT || FPT->getExceptionSpecType() == EST_None) 15667 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 15668 } 15669 15670 IdentifierInfo *Name = FD->getIdentifier(); 15671 if (!Name) 15672 return; 15673 if ((!getLangOpts().CPlusPlus && 15674 FD->getDeclContext()->isTranslationUnit()) || 15675 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 15676 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 15677 LinkageSpecDecl::lang_c)) { 15678 // Okay: this could be a libc/libm/Objective-C function we know 15679 // about. 15680 } else 15681 return; 15682 15683 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 15684 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 15685 // target-specific builtins, perhaps? 15686 if (!FD->hasAttr<FormatAttr>()) 15687 FD->addAttr(FormatAttr::CreateImplicit(Context, 15688 &Context.Idents.get("printf"), 2, 15689 Name->isStr("vasprintf") ? 0 : 3, 15690 FD->getLocation())); 15691 } 15692 15693 if (Name->isStr("__CFStringMakeConstantString")) { 15694 // We already have a __builtin___CFStringMakeConstantString, 15695 // but builds that use -fno-constant-cfstrings don't go through that. 15696 if (!FD->hasAttr<FormatArgAttr>()) 15697 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), 15698 FD->getLocation())); 15699 } 15700 } 15701 15702 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 15703 TypeSourceInfo *TInfo) { 15704 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 15705 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 15706 15707 if (!TInfo) { 15708 assert(D.isInvalidType() && "no declarator info for valid type"); 15709 TInfo = Context.getTrivialTypeSourceInfo(T); 15710 } 15711 15712 // Scope manipulation handled by caller. 15713 TypedefDecl *NewTD = 15714 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(), 15715 D.getIdentifierLoc(), D.getIdentifier(), TInfo); 15716 15717 // Bail out immediately if we have an invalid declaration. 15718 if (D.isInvalidType()) { 15719 NewTD->setInvalidDecl(); 15720 return NewTD; 15721 } 15722 15723 if (D.getDeclSpec().isModulePrivateSpecified()) { 15724 if (CurContext->isFunctionOrMethod()) 15725 Diag(NewTD->getLocation(), diag::err_module_private_local) 15726 << 2 << NewTD 15727 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 15728 << FixItHint::CreateRemoval( 15729 D.getDeclSpec().getModulePrivateSpecLoc()); 15730 else 15731 NewTD->setModulePrivate(); 15732 } 15733 15734 // C++ [dcl.typedef]p8: 15735 // If the typedef declaration defines an unnamed class (or 15736 // enum), the first typedef-name declared by the declaration 15737 // to be that class type (or enum type) is used to denote the 15738 // class type (or enum type) for linkage purposes only. 15739 // We need to check whether the type was declared in the declaration. 15740 switch (D.getDeclSpec().getTypeSpecType()) { 15741 case TST_enum: 15742 case TST_struct: 15743 case TST_interface: 15744 case TST_union: 15745 case TST_class: { 15746 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 15747 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 15748 break; 15749 } 15750 15751 default: 15752 break; 15753 } 15754 15755 return NewTD; 15756 } 15757 15758 /// Check that this is a valid underlying type for an enum declaration. 15759 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 15760 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 15761 QualType T = TI->getType(); 15762 15763 if (T->isDependentType()) 15764 return false; 15765 15766 // This doesn't use 'isIntegralType' despite the error message mentioning 15767 // integral type because isIntegralType would also allow enum types in C. 15768 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 15769 if (BT->isInteger()) 15770 return false; 15771 15772 if (T->isBitIntType()) 15773 return false; 15774 15775 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 15776 } 15777 15778 /// Check whether this is a valid redeclaration of a previous enumeration. 15779 /// \return true if the redeclaration was invalid. 15780 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 15781 QualType EnumUnderlyingTy, bool IsFixed, 15782 const EnumDecl *Prev) { 15783 if (IsScoped != Prev->isScoped()) { 15784 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 15785 << Prev->isScoped(); 15786 Diag(Prev->getLocation(), diag::note_previous_declaration); 15787 return true; 15788 } 15789 15790 if (IsFixed && Prev->isFixed()) { 15791 if (!EnumUnderlyingTy->isDependentType() && 15792 !Prev->getIntegerType()->isDependentType() && 15793 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 15794 Prev->getIntegerType())) { 15795 // TODO: Highlight the underlying type of the redeclaration. 15796 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 15797 << EnumUnderlyingTy << Prev->getIntegerType(); 15798 Diag(Prev->getLocation(), diag::note_previous_declaration) 15799 << Prev->getIntegerTypeRange(); 15800 return true; 15801 } 15802 } else if (IsFixed != Prev->isFixed()) { 15803 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 15804 << Prev->isFixed(); 15805 Diag(Prev->getLocation(), diag::note_previous_declaration); 15806 return true; 15807 } 15808 15809 return false; 15810 } 15811 15812 /// Get diagnostic %select index for tag kind for 15813 /// redeclaration diagnostic message. 15814 /// WARNING: Indexes apply to particular diagnostics only! 15815 /// 15816 /// \returns diagnostic %select index. 15817 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 15818 switch (Tag) { 15819 case TTK_Struct: return 0; 15820 case TTK_Interface: return 1; 15821 case TTK_Class: return 2; 15822 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 15823 } 15824 } 15825 15826 /// Determine if tag kind is a class-key compatible with 15827 /// class for redeclaration (class, struct, or __interface). 15828 /// 15829 /// \returns true iff the tag kind is compatible. 15830 static bool isClassCompatTagKind(TagTypeKind Tag) 15831 { 15832 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 15833 } 15834 15835 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 15836 TagTypeKind TTK) { 15837 if (isa<TypedefDecl>(PrevDecl)) 15838 return NTK_Typedef; 15839 else if (isa<TypeAliasDecl>(PrevDecl)) 15840 return NTK_TypeAlias; 15841 else if (isa<ClassTemplateDecl>(PrevDecl)) 15842 return NTK_Template; 15843 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 15844 return NTK_TypeAliasTemplate; 15845 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 15846 return NTK_TemplateTemplateArgument; 15847 switch (TTK) { 15848 case TTK_Struct: 15849 case TTK_Interface: 15850 case TTK_Class: 15851 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 15852 case TTK_Union: 15853 return NTK_NonUnion; 15854 case TTK_Enum: 15855 return NTK_NonEnum; 15856 } 15857 llvm_unreachable("invalid TTK"); 15858 } 15859 15860 /// Determine whether a tag with a given kind is acceptable 15861 /// as a redeclaration of the given tag declaration. 15862 /// 15863 /// \returns true if the new tag kind is acceptable, false otherwise. 15864 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 15865 TagTypeKind NewTag, bool isDefinition, 15866 SourceLocation NewTagLoc, 15867 const IdentifierInfo *Name) { 15868 // C++ [dcl.type.elab]p3: 15869 // The class-key or enum keyword present in the 15870 // elaborated-type-specifier shall agree in kind with the 15871 // declaration to which the name in the elaborated-type-specifier 15872 // refers. This rule also applies to the form of 15873 // elaborated-type-specifier that declares a class-name or 15874 // friend class since it can be construed as referring to the 15875 // definition of the class. Thus, in any 15876 // elaborated-type-specifier, the enum keyword shall be used to 15877 // refer to an enumeration (7.2), the union class-key shall be 15878 // used to refer to a union (clause 9), and either the class or 15879 // struct class-key shall be used to refer to a class (clause 9) 15880 // declared using the class or struct class-key. 15881 TagTypeKind OldTag = Previous->getTagKind(); 15882 if (OldTag != NewTag && 15883 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag))) 15884 return false; 15885 15886 // Tags are compatible, but we might still want to warn on mismatched tags. 15887 // Non-class tags can't be mismatched at this point. 15888 if (!isClassCompatTagKind(NewTag)) 15889 return true; 15890 15891 // Declarations for which -Wmismatched-tags is disabled are entirely ignored 15892 // by our warning analysis. We don't want to warn about mismatches with (eg) 15893 // declarations in system headers that are designed to be specialized, but if 15894 // a user asks us to warn, we should warn if their code contains mismatched 15895 // declarations. 15896 auto IsIgnoredLoc = [&](SourceLocation Loc) { 15897 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch, 15898 Loc); 15899 }; 15900 if (IsIgnoredLoc(NewTagLoc)) 15901 return true; 15902 15903 auto IsIgnored = [&](const TagDecl *Tag) { 15904 return IsIgnoredLoc(Tag->getLocation()); 15905 }; 15906 while (IsIgnored(Previous)) { 15907 Previous = Previous->getPreviousDecl(); 15908 if (!Previous) 15909 return true; 15910 OldTag = Previous->getTagKind(); 15911 } 15912 15913 bool isTemplate = false; 15914 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 15915 isTemplate = Record->getDescribedClassTemplate(); 15916 15917 if (inTemplateInstantiation()) { 15918 if (OldTag != NewTag) { 15919 // In a template instantiation, do not offer fix-its for tag mismatches 15920 // since they usually mess up the template instead of fixing the problem. 15921 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15922 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15923 << getRedeclDiagFromTagKind(OldTag); 15924 // FIXME: Note previous location? 15925 } 15926 return true; 15927 } 15928 15929 if (isDefinition) { 15930 // On definitions, check all previous tags and issue a fix-it for each 15931 // one that doesn't match the current tag. 15932 if (Previous->getDefinition()) { 15933 // Don't suggest fix-its for redefinitions. 15934 return true; 15935 } 15936 15937 bool previousMismatch = false; 15938 for (const TagDecl *I : Previous->redecls()) { 15939 if (I->getTagKind() != NewTag) { 15940 // Ignore previous declarations for which the warning was disabled. 15941 if (IsIgnored(I)) 15942 continue; 15943 15944 if (!previousMismatch) { 15945 previousMismatch = true; 15946 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 15947 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15948 << getRedeclDiagFromTagKind(I->getTagKind()); 15949 } 15950 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 15951 << getRedeclDiagFromTagKind(NewTag) 15952 << FixItHint::CreateReplacement(I->getInnerLocStart(), 15953 TypeWithKeyword::getTagTypeKindName(NewTag)); 15954 } 15955 } 15956 return true; 15957 } 15958 15959 // Identify the prevailing tag kind: this is the kind of the definition (if 15960 // there is a non-ignored definition), or otherwise the kind of the prior 15961 // (non-ignored) declaration. 15962 const TagDecl *PrevDef = Previous->getDefinition(); 15963 if (PrevDef && IsIgnored(PrevDef)) 15964 PrevDef = nullptr; 15965 const TagDecl *Redecl = PrevDef ? PrevDef : Previous; 15966 if (Redecl->getTagKind() != NewTag) { 15967 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15968 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15969 << getRedeclDiagFromTagKind(OldTag); 15970 Diag(Redecl->getLocation(), diag::note_previous_use); 15971 15972 // If there is a previous definition, suggest a fix-it. 15973 if (PrevDef) { 15974 Diag(NewTagLoc, diag::note_struct_class_suggestion) 15975 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 15976 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 15977 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 15978 } 15979 } 15980 15981 return true; 15982 } 15983 15984 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 15985 /// from an outer enclosing namespace or file scope inside a friend declaration. 15986 /// This should provide the commented out code in the following snippet: 15987 /// namespace N { 15988 /// struct X; 15989 /// namespace M { 15990 /// struct Y { friend struct /*N::*/ X; }; 15991 /// } 15992 /// } 15993 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 15994 SourceLocation NameLoc) { 15995 // While the decl is in a namespace, do repeated lookup of that name and see 15996 // if we get the same namespace back. If we do not, continue until 15997 // translation unit scope, at which point we have a fully qualified NNS. 15998 SmallVector<IdentifierInfo *, 4> Namespaces; 15999 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 16000 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 16001 // This tag should be declared in a namespace, which can only be enclosed by 16002 // other namespaces. Bail if there's an anonymous namespace in the chain. 16003 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 16004 if (!Namespace || Namespace->isAnonymousNamespace()) 16005 return FixItHint(); 16006 IdentifierInfo *II = Namespace->getIdentifier(); 16007 Namespaces.push_back(II); 16008 NamedDecl *Lookup = SemaRef.LookupSingleName( 16009 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 16010 if (Lookup == Namespace) 16011 break; 16012 } 16013 16014 // Once we have all the namespaces, reverse them to go outermost first, and 16015 // build an NNS. 16016 SmallString<64> Insertion; 16017 llvm::raw_svector_ostream OS(Insertion); 16018 if (DC->isTranslationUnit()) 16019 OS << "::"; 16020 std::reverse(Namespaces.begin(), Namespaces.end()); 16021 for (auto *II : Namespaces) 16022 OS << II->getName() << "::"; 16023 return FixItHint::CreateInsertion(NameLoc, Insertion); 16024 } 16025 16026 /// Determine whether a tag originally declared in context \p OldDC can 16027 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup 16028 /// found a declaration in \p OldDC as a previous decl, perhaps through a 16029 /// using-declaration). 16030 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 16031 DeclContext *NewDC) { 16032 OldDC = OldDC->getRedeclContext(); 16033 NewDC = NewDC->getRedeclContext(); 16034 16035 if (OldDC->Equals(NewDC)) 16036 return true; 16037 16038 // In MSVC mode, we allow a redeclaration if the contexts are related (either 16039 // encloses the other). 16040 if (S.getLangOpts().MSVCCompat && 16041 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 16042 return true; 16043 16044 return false; 16045 } 16046 16047 /// This is invoked when we see 'struct foo' or 'struct {'. In the 16048 /// former case, Name will be non-null. In the later case, Name will be null. 16049 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 16050 /// reference/declaration/definition of a tag. 16051 /// 16052 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 16053 /// trailing-type-specifier) other than one in an alias-declaration. 16054 /// 16055 /// \param SkipBody If non-null, will be set to indicate if the caller should 16056 /// skip the definition of this tag and treat it as if it were a declaration. 16057 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 16058 SourceLocation KWLoc, CXXScopeSpec &SS, 16059 IdentifierInfo *Name, SourceLocation NameLoc, 16060 const ParsedAttributesView &Attrs, AccessSpecifier AS, 16061 SourceLocation ModulePrivateLoc, 16062 MultiTemplateParamsArg TemplateParameterLists, 16063 bool &OwnedDecl, bool &IsDependent, 16064 SourceLocation ScopedEnumKWLoc, 16065 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, 16066 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 16067 SkipBodyInfo *SkipBody) { 16068 // If this is not a definition, it must have a name. 16069 IdentifierInfo *OrigName = Name; 16070 assert((Name != nullptr || TUK == TUK_Definition) && 16071 "Nameless record must be a definition!"); 16072 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 16073 16074 OwnedDecl = false; 16075 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 16076 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 16077 16078 // FIXME: Check member specializations more carefully. 16079 bool isMemberSpecialization = false; 16080 bool Invalid = false; 16081 16082 // We only need to do this matching if we have template parameters 16083 // or a scope specifier, which also conveniently avoids this work 16084 // for non-C++ cases. 16085 if (TemplateParameterLists.size() > 0 || 16086 (SS.isNotEmpty() && TUK != TUK_Reference)) { 16087 if (TemplateParameterList *TemplateParams = 16088 MatchTemplateParametersToScopeSpecifier( 16089 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 16090 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 16091 if (Kind == TTK_Enum) { 16092 Diag(KWLoc, diag::err_enum_template); 16093 return nullptr; 16094 } 16095 16096 if (TemplateParams->size() > 0) { 16097 // This is a declaration or definition of a class template (which may 16098 // be a member of another template). 16099 16100 if (Invalid) 16101 return nullptr; 16102 16103 OwnedDecl = false; 16104 DeclResult Result = CheckClassTemplate( 16105 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams, 16106 AS, ModulePrivateLoc, 16107 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1, 16108 TemplateParameterLists.data(), SkipBody); 16109 return Result.get(); 16110 } else { 16111 // The "template<>" header is extraneous. 16112 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 16113 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 16114 isMemberSpecialization = true; 16115 } 16116 } 16117 16118 if (!TemplateParameterLists.empty() && isMemberSpecialization && 16119 CheckTemplateDeclScope(S, TemplateParameterLists.back())) 16120 return nullptr; 16121 } 16122 16123 // Figure out the underlying type if this a enum declaration. We need to do 16124 // this early, because it's needed to detect if this is an incompatible 16125 // redeclaration. 16126 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 16127 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; 16128 16129 if (Kind == TTK_Enum) { 16130 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { 16131 // No underlying type explicitly specified, or we failed to parse the 16132 // type, default to int. 16133 EnumUnderlying = Context.IntTy.getTypePtr(); 16134 } else if (UnderlyingType.get()) { 16135 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 16136 // integral type; any cv-qualification is ignored. 16137 TypeSourceInfo *TI = nullptr; 16138 GetTypeFromParser(UnderlyingType.get(), &TI); 16139 EnumUnderlying = TI; 16140 16141 if (CheckEnumUnderlyingType(TI)) 16142 // Recover by falling back to int. 16143 EnumUnderlying = Context.IntTy.getTypePtr(); 16144 16145 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 16146 UPPC_FixedUnderlyingType)) 16147 EnumUnderlying = Context.IntTy.getTypePtr(); 16148 16149 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) { 16150 // For MSVC ABI compatibility, unfixed enums must use an underlying type 16151 // of 'int'. However, if this is an unfixed forward declaration, don't set 16152 // the underlying type unless the user enables -fms-compatibility. This 16153 // makes unfixed forward declared enums incomplete and is more conforming. 16154 if (TUK == TUK_Definition || getLangOpts().MSVCCompat) 16155 EnumUnderlying = Context.IntTy.getTypePtr(); 16156 } 16157 } 16158 16159 DeclContext *SearchDC = CurContext; 16160 DeclContext *DC = CurContext; 16161 bool isStdBadAlloc = false; 16162 bool isStdAlignValT = false; 16163 16164 RedeclarationKind Redecl = forRedeclarationInCurContext(); 16165 if (TUK == TUK_Friend || TUK == TUK_Reference) 16166 Redecl = NotForRedeclaration; 16167 16168 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C 16169 /// implemented asks for structural equivalence checking, the returned decl 16170 /// here is passed back to the parser, allowing the tag body to be parsed. 16171 auto createTagFromNewDecl = [&]() -> TagDecl * { 16172 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage"); 16173 // If there is an identifier, use the location of the identifier as the 16174 // location of the decl, otherwise use the location of the struct/union 16175 // keyword. 16176 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 16177 TagDecl *New = nullptr; 16178 16179 if (Kind == TTK_Enum) { 16180 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, 16181 ScopedEnum, ScopedEnumUsesClassTag, IsFixed); 16182 // If this is an undefined enum, bail. 16183 if (TUK != TUK_Definition && !Invalid) 16184 return nullptr; 16185 if (EnumUnderlying) { 16186 EnumDecl *ED = cast<EnumDecl>(New); 16187 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) 16188 ED->setIntegerTypeSourceInfo(TI); 16189 else 16190 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); 16191 ED->setPromotionType(ED->getIntegerType()); 16192 } 16193 } else { // struct/union 16194 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 16195 nullptr); 16196 } 16197 16198 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 16199 // Add alignment attributes if necessary; these attributes are checked 16200 // when the ASTContext lays out the structure. 16201 // 16202 // It is important for implementing the correct semantics that this 16203 // happen here (in ActOnTag). The #pragma pack stack is 16204 // maintained as a result of parser callbacks which can occur at 16205 // many points during the parsing of a struct declaration (because 16206 // the #pragma tokens are effectively skipped over during the 16207 // parsing of the struct). 16208 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 16209 AddAlignmentAttributesForRecord(RD); 16210 AddMsStructLayoutForRecord(RD); 16211 } 16212 } 16213 New->setLexicalDeclContext(CurContext); 16214 return New; 16215 }; 16216 16217 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 16218 if (Name && SS.isNotEmpty()) { 16219 // We have a nested-name tag ('struct foo::bar'). 16220 16221 // Check for invalid 'foo::'. 16222 if (SS.isInvalid()) { 16223 Name = nullptr; 16224 goto CreateNewDecl; 16225 } 16226 16227 // If this is a friend or a reference to a class in a dependent 16228 // context, don't try to make a decl for it. 16229 if (TUK == TUK_Friend || TUK == TUK_Reference) { 16230 DC = computeDeclContext(SS, false); 16231 if (!DC) { 16232 IsDependent = true; 16233 return nullptr; 16234 } 16235 } else { 16236 DC = computeDeclContext(SS, true); 16237 if (!DC) { 16238 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 16239 << SS.getRange(); 16240 return nullptr; 16241 } 16242 } 16243 16244 if (RequireCompleteDeclContext(SS, DC)) 16245 return nullptr; 16246 16247 SearchDC = DC; 16248 // Look-up name inside 'foo::'. 16249 LookupQualifiedName(Previous, DC); 16250 16251 if (Previous.isAmbiguous()) 16252 return nullptr; 16253 16254 if (Previous.empty()) { 16255 // Name lookup did not find anything. However, if the 16256 // nested-name-specifier refers to the current instantiation, 16257 // and that current instantiation has any dependent base 16258 // classes, we might find something at instantiation time: treat 16259 // this as a dependent elaborated-type-specifier. 16260 // But this only makes any sense for reference-like lookups. 16261 if (Previous.wasNotFoundInCurrentInstantiation() && 16262 (TUK == TUK_Reference || TUK == TUK_Friend)) { 16263 IsDependent = true; 16264 return nullptr; 16265 } 16266 16267 // A tag 'foo::bar' must already exist. 16268 Diag(NameLoc, diag::err_not_tag_in_scope) 16269 << Kind << Name << DC << SS.getRange(); 16270 Name = nullptr; 16271 Invalid = true; 16272 goto CreateNewDecl; 16273 } 16274 } else if (Name) { 16275 // C++14 [class.mem]p14: 16276 // If T is the name of a class, then each of the following shall have a 16277 // name different from T: 16278 // -- every member of class T that is itself a type 16279 if (TUK != TUK_Reference && TUK != TUK_Friend && 16280 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 16281 return nullptr; 16282 16283 // If this is a named struct, check to see if there was a previous forward 16284 // declaration or definition. 16285 // FIXME: We're looking into outer scopes here, even when we 16286 // shouldn't be. Doing so can result in ambiguities that we 16287 // shouldn't be diagnosing. 16288 LookupName(Previous, S); 16289 16290 // When declaring or defining a tag, ignore ambiguities introduced 16291 // by types using'ed into this scope. 16292 if (Previous.isAmbiguous() && 16293 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 16294 LookupResult::Filter F = Previous.makeFilter(); 16295 while (F.hasNext()) { 16296 NamedDecl *ND = F.next(); 16297 if (!ND->getDeclContext()->getRedeclContext()->Equals( 16298 SearchDC->getRedeclContext())) 16299 F.erase(); 16300 } 16301 F.done(); 16302 } 16303 16304 // C++11 [namespace.memdef]p3: 16305 // If the name in a friend declaration is neither qualified nor 16306 // a template-id and the declaration is a function or an 16307 // elaborated-type-specifier, the lookup to determine whether 16308 // the entity has been previously declared shall not consider 16309 // any scopes outside the innermost enclosing namespace. 16310 // 16311 // MSVC doesn't implement the above rule for types, so a friend tag 16312 // declaration may be a redeclaration of a type declared in an enclosing 16313 // scope. They do implement this rule for friend functions. 16314 // 16315 // Does it matter that this should be by scope instead of by 16316 // semantic context? 16317 if (!Previous.empty() && TUK == TUK_Friend) { 16318 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 16319 LookupResult::Filter F = Previous.makeFilter(); 16320 bool FriendSawTagOutsideEnclosingNamespace = false; 16321 while (F.hasNext()) { 16322 NamedDecl *ND = F.next(); 16323 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 16324 if (DC->isFileContext() && 16325 !EnclosingNS->Encloses(ND->getDeclContext())) { 16326 if (getLangOpts().MSVCCompat) 16327 FriendSawTagOutsideEnclosingNamespace = true; 16328 else 16329 F.erase(); 16330 } 16331 } 16332 F.done(); 16333 16334 // Diagnose this MSVC extension in the easy case where lookup would have 16335 // unambiguously found something outside the enclosing namespace. 16336 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 16337 NamedDecl *ND = Previous.getFoundDecl(); 16338 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 16339 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 16340 } 16341 } 16342 16343 // Note: there used to be some attempt at recovery here. 16344 if (Previous.isAmbiguous()) 16345 return nullptr; 16346 16347 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 16348 // FIXME: This makes sure that we ignore the contexts associated 16349 // with C structs, unions, and enums when looking for a matching 16350 // tag declaration or definition. See the similar lookup tweak 16351 // in Sema::LookupName; is there a better way to deal with this? 16352 while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(SearchDC)) 16353 SearchDC = SearchDC->getParent(); 16354 } else if (getLangOpts().CPlusPlus) { 16355 // Inside ObjCContainer want to keep it as a lexical decl context but go 16356 // past it (most often to TranslationUnit) to find the semantic decl 16357 // context. 16358 while (isa<ObjCContainerDecl>(SearchDC)) 16359 SearchDC = SearchDC->getParent(); 16360 } 16361 } else if (getLangOpts().CPlusPlus) { 16362 // Don't use ObjCContainerDecl as the semantic decl context for anonymous 16363 // TagDecl the same way as we skip it for named TagDecl. 16364 while (isa<ObjCContainerDecl>(SearchDC)) 16365 SearchDC = SearchDC->getParent(); 16366 } 16367 16368 if (Previous.isSingleResult() && 16369 Previous.getFoundDecl()->isTemplateParameter()) { 16370 // Maybe we will complain about the shadowed template parameter. 16371 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 16372 // Just pretend that we didn't see the previous declaration. 16373 Previous.clear(); 16374 } 16375 16376 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 16377 DC->Equals(getStdNamespace())) { 16378 if (Name->isStr("bad_alloc")) { 16379 // This is a declaration of or a reference to "std::bad_alloc". 16380 isStdBadAlloc = true; 16381 16382 // If std::bad_alloc has been implicitly declared (but made invisible to 16383 // name lookup), fill in this implicit declaration as the previous 16384 // declaration, so that the declarations get chained appropriately. 16385 if (Previous.empty() && StdBadAlloc) 16386 Previous.addDecl(getStdBadAlloc()); 16387 } else if (Name->isStr("align_val_t")) { 16388 isStdAlignValT = true; 16389 if (Previous.empty() && StdAlignValT) 16390 Previous.addDecl(getStdAlignValT()); 16391 } 16392 } 16393 16394 // If we didn't find a previous declaration, and this is a reference 16395 // (or friend reference), move to the correct scope. In C++, we 16396 // also need to do a redeclaration lookup there, just in case 16397 // there's a shadow friend decl. 16398 if (Name && Previous.empty() && 16399 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { 16400 if (Invalid) goto CreateNewDecl; 16401 assert(SS.isEmpty()); 16402 16403 if (TUK == TUK_Reference || IsTemplateParamOrArg) { 16404 // C++ [basic.scope.pdecl]p5: 16405 // -- for an elaborated-type-specifier of the form 16406 // 16407 // class-key identifier 16408 // 16409 // if the elaborated-type-specifier is used in the 16410 // decl-specifier-seq or parameter-declaration-clause of a 16411 // function defined in namespace scope, the identifier is 16412 // declared as a class-name in the namespace that contains 16413 // the declaration; otherwise, except as a friend 16414 // declaration, the identifier is declared in the smallest 16415 // non-class, non-function-prototype scope that contains the 16416 // declaration. 16417 // 16418 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 16419 // C structs and unions. 16420 // 16421 // It is an error in C++ to declare (rather than define) an enum 16422 // type, including via an elaborated type specifier. We'll 16423 // diagnose that later; for now, declare the enum in the same 16424 // scope as we would have picked for any other tag type. 16425 // 16426 // GNU C also supports this behavior as part of its incomplete 16427 // enum types extension, while GNU C++ does not. 16428 // 16429 // Find the context where we'll be declaring the tag. 16430 // FIXME: We would like to maintain the current DeclContext as the 16431 // lexical context, 16432 SearchDC = getTagInjectionContext(SearchDC); 16433 16434 // Find the scope where we'll be declaring the tag. 16435 S = getTagInjectionScope(S, getLangOpts()); 16436 } else { 16437 assert(TUK == TUK_Friend); 16438 // C++ [namespace.memdef]p3: 16439 // If a friend declaration in a non-local class first declares a 16440 // class or function, the friend class or function is a member of 16441 // the innermost enclosing namespace. 16442 SearchDC = SearchDC->getEnclosingNamespaceContext(); 16443 } 16444 16445 // In C++, we need to do a redeclaration lookup to properly 16446 // diagnose some problems. 16447 // FIXME: redeclaration lookup is also used (with and without C++) to find a 16448 // hidden declaration so that we don't get ambiguity errors when using a 16449 // type declared by an elaborated-type-specifier. In C that is not correct 16450 // and we should instead merge compatible types found by lookup. 16451 if (getLangOpts().CPlusPlus) { 16452 // FIXME: This can perform qualified lookups into function contexts, 16453 // which are meaningless. 16454 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 16455 LookupQualifiedName(Previous, SearchDC); 16456 } else { 16457 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 16458 LookupName(Previous, S); 16459 } 16460 } 16461 16462 // If we have a known previous declaration to use, then use it. 16463 if (Previous.empty() && SkipBody && SkipBody->Previous) 16464 Previous.addDecl(SkipBody->Previous); 16465 16466 if (!Previous.empty()) { 16467 NamedDecl *PrevDecl = Previous.getFoundDecl(); 16468 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 16469 16470 // It's okay to have a tag decl in the same scope as a typedef 16471 // which hides a tag decl in the same scope. Finding this 16472 // with a redeclaration lookup can only actually happen in C++. 16473 // 16474 // This is also okay for elaborated-type-specifiers, which is 16475 // technically forbidden by the current standard but which is 16476 // okay according to the likely resolution of an open issue; 16477 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 16478 if (getLangOpts().CPlusPlus) { 16479 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 16480 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 16481 TagDecl *Tag = TT->getDecl(); 16482 if (Tag->getDeclName() == Name && 16483 Tag->getDeclContext()->getRedeclContext() 16484 ->Equals(TD->getDeclContext()->getRedeclContext())) { 16485 PrevDecl = Tag; 16486 Previous.clear(); 16487 Previous.addDecl(Tag); 16488 Previous.resolveKind(); 16489 } 16490 } 16491 } 16492 } 16493 16494 // If this is a redeclaration of a using shadow declaration, it must 16495 // declare a tag in the same context. In MSVC mode, we allow a 16496 // redefinition if either context is within the other. 16497 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 16498 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 16499 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 16500 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 16501 !(OldTag && isAcceptableTagRedeclContext( 16502 *this, OldTag->getDeclContext(), SearchDC))) { 16503 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 16504 Diag(Shadow->getTargetDecl()->getLocation(), 16505 diag::note_using_decl_target); 16506 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) 16507 << 0; 16508 // Recover by ignoring the old declaration. 16509 Previous.clear(); 16510 goto CreateNewDecl; 16511 } 16512 } 16513 16514 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 16515 // If this is a use of a previous tag, or if the tag is already declared 16516 // in the same scope (so that the definition/declaration completes or 16517 // rementions the tag), reuse the decl. 16518 if (TUK == TUK_Reference || TUK == TUK_Friend || 16519 isDeclInScope(DirectPrevDecl, SearchDC, S, 16520 SS.isNotEmpty() || isMemberSpecialization)) { 16521 // Make sure that this wasn't declared as an enum and now used as a 16522 // struct or something similar. 16523 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 16524 TUK == TUK_Definition, KWLoc, 16525 Name)) { 16526 bool SafeToContinue 16527 = (PrevTagDecl->getTagKind() != TTK_Enum && 16528 Kind != TTK_Enum); 16529 if (SafeToContinue) 16530 Diag(KWLoc, diag::err_use_with_wrong_tag) 16531 << Name 16532 << FixItHint::CreateReplacement(SourceRange(KWLoc), 16533 PrevTagDecl->getKindName()); 16534 else 16535 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 16536 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 16537 16538 if (SafeToContinue) 16539 Kind = PrevTagDecl->getTagKind(); 16540 else { 16541 // Recover by making this an anonymous redefinition. 16542 Name = nullptr; 16543 Previous.clear(); 16544 Invalid = true; 16545 } 16546 } 16547 16548 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 16549 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 16550 if (TUK == TUK_Reference || TUK == TUK_Friend) 16551 return PrevTagDecl; 16552 16553 QualType EnumUnderlyingTy; 16554 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 16555 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 16556 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 16557 EnumUnderlyingTy = QualType(T, 0); 16558 16559 // All conflicts with previous declarations are recovered by 16560 // returning the previous declaration, unless this is a definition, 16561 // in which case we want the caller to bail out. 16562 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 16563 ScopedEnum, EnumUnderlyingTy, 16564 IsFixed, PrevEnum)) 16565 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 16566 } 16567 16568 // C++11 [class.mem]p1: 16569 // A member shall not be declared twice in the member-specification, 16570 // except that a nested class or member class template can be declared 16571 // and then later defined. 16572 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 16573 S->isDeclScope(PrevDecl)) { 16574 Diag(NameLoc, diag::ext_member_redeclared); 16575 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 16576 } 16577 16578 if (!Invalid) { 16579 // If this is a use, just return the declaration we found, unless 16580 // we have attributes. 16581 if (TUK == TUK_Reference || TUK == TUK_Friend) { 16582 if (!Attrs.empty()) { 16583 // FIXME: Diagnose these attributes. For now, we create a new 16584 // declaration to hold them. 16585 } else if (TUK == TUK_Reference && 16586 (PrevTagDecl->getFriendObjectKind() == 16587 Decl::FOK_Undeclared || 16588 PrevDecl->getOwningModule() != getCurrentModule()) && 16589 SS.isEmpty()) { 16590 // This declaration is a reference to an existing entity, but 16591 // has different visibility from that entity: it either makes 16592 // a friend visible or it makes a type visible in a new module. 16593 // In either case, create a new declaration. We only do this if 16594 // the declaration would have meant the same thing if no prior 16595 // declaration were found, that is, if it was found in the same 16596 // scope where we would have injected a declaration. 16597 if (!getTagInjectionContext(CurContext)->getRedeclContext() 16598 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 16599 return PrevTagDecl; 16600 // This is in the injected scope, create a new declaration in 16601 // that scope. 16602 S = getTagInjectionScope(S, getLangOpts()); 16603 } else { 16604 return PrevTagDecl; 16605 } 16606 } 16607 16608 // Diagnose attempts to redefine a tag. 16609 if (TUK == TUK_Definition) { 16610 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 16611 // If we're defining a specialization and the previous definition 16612 // is from an implicit instantiation, don't emit an error 16613 // here; we'll catch this in the general case below. 16614 bool IsExplicitSpecializationAfterInstantiation = false; 16615 if (isMemberSpecialization) { 16616 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 16617 IsExplicitSpecializationAfterInstantiation = 16618 RD->getTemplateSpecializationKind() != 16619 TSK_ExplicitSpecialization; 16620 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 16621 IsExplicitSpecializationAfterInstantiation = 16622 ED->getTemplateSpecializationKind() != 16623 TSK_ExplicitSpecialization; 16624 } 16625 16626 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do 16627 // not keep more that one definition around (merge them). However, 16628 // ensure the decl passes the structural compatibility check in 16629 // C11 6.2.7/1 (or 6.1.2.6/1 in C89). 16630 NamedDecl *Hidden = nullptr; 16631 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 16632 // There is a definition of this tag, but it is not visible. We 16633 // explicitly make use of C++'s one definition rule here, and 16634 // assume that this definition is identical to the hidden one 16635 // we already have. Make the existing definition visible and 16636 // use it in place of this one. 16637 if (!getLangOpts().CPlusPlus) { 16638 // Postpone making the old definition visible until after we 16639 // complete parsing the new one and do the structural 16640 // comparison. 16641 SkipBody->CheckSameAsPrevious = true; 16642 SkipBody->New = createTagFromNewDecl(); 16643 SkipBody->Previous = Def; 16644 return Def; 16645 } else { 16646 SkipBody->ShouldSkip = true; 16647 SkipBody->Previous = Def; 16648 makeMergedDefinitionVisible(Hidden); 16649 // Carry on and handle it like a normal definition. We'll 16650 // skip starting the definitiion later. 16651 } 16652 } else if (!IsExplicitSpecializationAfterInstantiation) { 16653 // A redeclaration in function prototype scope in C isn't 16654 // visible elsewhere, so merely issue a warning. 16655 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 16656 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 16657 else 16658 Diag(NameLoc, diag::err_redefinition) << Name; 16659 notePreviousDefinition(Def, 16660 NameLoc.isValid() ? NameLoc : KWLoc); 16661 // If this is a redefinition, recover by making this 16662 // struct be anonymous, which will make any later 16663 // references get the previous definition. 16664 Name = nullptr; 16665 Previous.clear(); 16666 Invalid = true; 16667 } 16668 } else { 16669 // If the type is currently being defined, complain 16670 // about a nested redefinition. 16671 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 16672 if (TD->isBeingDefined()) { 16673 Diag(NameLoc, diag::err_nested_redefinition) << Name; 16674 Diag(PrevTagDecl->getLocation(), 16675 diag::note_previous_definition); 16676 Name = nullptr; 16677 Previous.clear(); 16678 Invalid = true; 16679 } 16680 } 16681 16682 // Okay, this is definition of a previously declared or referenced 16683 // tag. We're going to create a new Decl for it. 16684 } 16685 16686 // Okay, we're going to make a redeclaration. If this is some kind 16687 // of reference, make sure we build the redeclaration in the same DC 16688 // as the original, and ignore the current access specifier. 16689 if (TUK == TUK_Friend || TUK == TUK_Reference) { 16690 SearchDC = PrevTagDecl->getDeclContext(); 16691 AS = AS_none; 16692 } 16693 } 16694 // If we get here we have (another) forward declaration or we 16695 // have a definition. Just create a new decl. 16696 16697 } else { 16698 // If we get here, this is a definition of a new tag type in a nested 16699 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 16700 // new decl/type. We set PrevDecl to NULL so that the entities 16701 // have distinct types. 16702 Previous.clear(); 16703 } 16704 // If we get here, we're going to create a new Decl. If PrevDecl 16705 // is non-NULL, it's a definition of the tag declared by 16706 // PrevDecl. If it's NULL, we have a new definition. 16707 16708 // Otherwise, PrevDecl is not a tag, but was found with tag 16709 // lookup. This is only actually possible in C++, where a few 16710 // things like templates still live in the tag namespace. 16711 } else { 16712 // Use a better diagnostic if an elaborated-type-specifier 16713 // found the wrong kind of type on the first 16714 // (non-redeclaration) lookup. 16715 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 16716 !Previous.isForRedeclaration()) { 16717 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 16718 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 16719 << Kind; 16720 Diag(PrevDecl->getLocation(), diag::note_declared_at); 16721 Invalid = true; 16722 16723 // Otherwise, only diagnose if the declaration is in scope. 16724 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 16725 SS.isNotEmpty() || isMemberSpecialization)) { 16726 // do nothing 16727 16728 // Diagnose implicit declarations introduced by elaborated types. 16729 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 16730 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 16731 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 16732 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 16733 Invalid = true; 16734 16735 // Otherwise it's a declaration. Call out a particularly common 16736 // case here. 16737 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 16738 unsigned Kind = 0; 16739 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 16740 Diag(NameLoc, diag::err_tag_definition_of_typedef) 16741 << Name << Kind << TND->getUnderlyingType(); 16742 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 16743 Invalid = true; 16744 16745 // Otherwise, diagnose. 16746 } else { 16747 // The tag name clashes with something else in the target scope, 16748 // issue an error and recover by making this tag be anonymous. 16749 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 16750 notePreviousDefinition(PrevDecl, NameLoc); 16751 Name = nullptr; 16752 Invalid = true; 16753 } 16754 16755 // The existing declaration isn't relevant to us; we're in a 16756 // new scope, so clear out the previous declaration. 16757 Previous.clear(); 16758 } 16759 } 16760 16761 CreateNewDecl: 16762 16763 TagDecl *PrevDecl = nullptr; 16764 if (Previous.isSingleResult()) 16765 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 16766 16767 // If there is an identifier, use the location of the identifier as the 16768 // location of the decl, otherwise use the location of the struct/union 16769 // keyword. 16770 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 16771 16772 // Otherwise, create a new declaration. If there is a previous 16773 // declaration of the same entity, the two will be linked via 16774 // PrevDecl. 16775 TagDecl *New; 16776 16777 if (Kind == TTK_Enum) { 16778 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 16779 // enum X { A, B, C } D; D should chain to X. 16780 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 16781 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 16782 ScopedEnumUsesClassTag, IsFixed); 16783 16784 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 16785 StdAlignValT = cast<EnumDecl>(New); 16786 16787 // If this is an undefined enum, warn. 16788 if (TUK != TUK_Definition && !Invalid) { 16789 TagDecl *Def; 16790 if (IsFixed && cast<EnumDecl>(New)->isFixed()) { 16791 // C++0x: 7.2p2: opaque-enum-declaration. 16792 // Conflicts are diagnosed above. Do nothing. 16793 } 16794 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 16795 Diag(Loc, diag::ext_forward_ref_enum_def) 16796 << New; 16797 Diag(Def->getLocation(), diag::note_previous_definition); 16798 } else { 16799 unsigned DiagID = diag::ext_forward_ref_enum; 16800 if (getLangOpts().MSVCCompat) 16801 DiagID = diag::ext_ms_forward_ref_enum; 16802 else if (getLangOpts().CPlusPlus) 16803 DiagID = diag::err_forward_ref_enum; 16804 Diag(Loc, DiagID); 16805 } 16806 } 16807 16808 if (EnumUnderlying) { 16809 EnumDecl *ED = cast<EnumDecl>(New); 16810 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 16811 ED->setIntegerTypeSourceInfo(TI); 16812 else 16813 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 16814 ED->setPromotionType(ED->getIntegerType()); 16815 assert(ED->isComplete() && "enum with type should be complete"); 16816 } 16817 } else { 16818 // struct/union/class 16819 16820 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 16821 // struct X { int A; } D; D should chain to X. 16822 if (getLangOpts().CPlusPlus) { 16823 // FIXME: Look for a way to use RecordDecl for simple structs. 16824 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 16825 cast_or_null<CXXRecordDecl>(PrevDecl)); 16826 16827 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 16828 StdBadAlloc = cast<CXXRecordDecl>(New); 16829 } else 16830 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 16831 cast_or_null<RecordDecl>(PrevDecl)); 16832 } 16833 16834 // C++11 [dcl.type]p3: 16835 // A type-specifier-seq shall not define a class or enumeration [...]. 16836 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && 16837 TUK == TUK_Definition) { 16838 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 16839 << Context.getTagDeclType(New); 16840 Invalid = true; 16841 } 16842 16843 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && 16844 DC->getDeclKind() == Decl::Enum) { 16845 Diag(New->getLocation(), diag::err_type_defined_in_enum) 16846 << Context.getTagDeclType(New); 16847 Invalid = true; 16848 } 16849 16850 // Maybe add qualifier info. 16851 if (SS.isNotEmpty()) { 16852 if (SS.isSet()) { 16853 // If this is either a declaration or a definition, check the 16854 // nested-name-specifier against the current context. 16855 if ((TUK == TUK_Definition || TUK == TUK_Declaration) && 16856 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, 16857 isMemberSpecialization)) 16858 Invalid = true; 16859 16860 New->setQualifierInfo(SS.getWithLocInContext(Context)); 16861 if (TemplateParameterLists.size() > 0) { 16862 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 16863 } 16864 } 16865 else 16866 Invalid = true; 16867 } 16868 16869 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 16870 // Add alignment attributes if necessary; these attributes are checked when 16871 // the ASTContext lays out the structure. 16872 // 16873 // It is important for implementing the correct semantics that this 16874 // happen here (in ActOnTag). The #pragma pack stack is 16875 // maintained as a result of parser callbacks which can occur at 16876 // many points during the parsing of a struct declaration (because 16877 // the #pragma tokens are effectively skipped over during the 16878 // parsing of the struct). 16879 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 16880 AddAlignmentAttributesForRecord(RD); 16881 AddMsStructLayoutForRecord(RD); 16882 } 16883 } 16884 16885 if (ModulePrivateLoc.isValid()) { 16886 if (isMemberSpecialization) 16887 Diag(New->getLocation(), diag::err_module_private_specialization) 16888 << 2 16889 << FixItHint::CreateRemoval(ModulePrivateLoc); 16890 // __module_private__ does not apply to local classes. However, we only 16891 // diagnose this as an error when the declaration specifiers are 16892 // freestanding. Here, we just ignore the __module_private__. 16893 else if (!SearchDC->isFunctionOrMethod()) 16894 New->setModulePrivate(); 16895 } 16896 16897 // If this is a specialization of a member class (of a class template), 16898 // check the specialization. 16899 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 16900 Invalid = true; 16901 16902 // If we're declaring or defining a tag in function prototype scope in C, 16903 // note that this type can only be used within the function and add it to 16904 // the list of decls to inject into the function definition scope. 16905 if ((Name || Kind == TTK_Enum) && 16906 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 16907 if (getLangOpts().CPlusPlus) { 16908 // C++ [dcl.fct]p6: 16909 // Types shall not be defined in return or parameter types. 16910 if (TUK == TUK_Definition && !IsTypeSpecifier) { 16911 Diag(Loc, diag::err_type_defined_in_param_type) 16912 << Name; 16913 Invalid = true; 16914 } 16915 } else if (!PrevDecl) { 16916 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 16917 } 16918 } 16919 16920 if (Invalid) 16921 New->setInvalidDecl(); 16922 16923 // Set the lexical context. If the tag has a C++ scope specifier, the 16924 // lexical context will be different from the semantic context. 16925 New->setLexicalDeclContext(CurContext); 16926 16927 // Mark this as a friend decl if applicable. 16928 // In Microsoft mode, a friend declaration also acts as a forward 16929 // declaration so we always pass true to setObjectOfFriendDecl to make 16930 // the tag name visible. 16931 if (TUK == TUK_Friend) 16932 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 16933 16934 // Set the access specifier. 16935 if (!Invalid && SearchDC->isRecord()) 16936 SetMemberAccessSpecifier(New, PrevDecl, AS); 16937 16938 if (PrevDecl) 16939 CheckRedeclarationInModule(New, PrevDecl); 16940 16941 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) 16942 New->startDefinition(); 16943 16944 ProcessDeclAttributeList(S, New, Attrs); 16945 AddPragmaAttributes(S, New); 16946 16947 // If this has an identifier, add it to the scope stack. 16948 if (TUK == TUK_Friend) { 16949 // We might be replacing an existing declaration in the lookup tables; 16950 // if so, borrow its access specifier. 16951 if (PrevDecl) 16952 New->setAccess(PrevDecl->getAccess()); 16953 16954 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 16955 DC->makeDeclVisibleInContext(New); 16956 if (Name) // can be null along some error paths 16957 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 16958 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 16959 } else if (Name) { 16960 S = getNonFieldDeclScope(S); 16961 PushOnScopeChains(New, S, true); 16962 } else { 16963 CurContext->addDecl(New); 16964 } 16965 16966 // If this is the C FILE type, notify the AST context. 16967 if (IdentifierInfo *II = New->getIdentifier()) 16968 if (!New->isInvalidDecl() && 16969 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 16970 II->isStr("FILE")) 16971 Context.setFILEDecl(New); 16972 16973 if (PrevDecl) 16974 mergeDeclAttributes(New, PrevDecl); 16975 16976 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) 16977 inferGslOwnerPointerAttribute(CXXRD); 16978 16979 // If there's a #pragma GCC visibility in scope, set the visibility of this 16980 // record. 16981 AddPushedVisibilityAttribute(New); 16982 16983 if (isMemberSpecialization && !New->isInvalidDecl()) 16984 CompleteMemberSpecialization(New, Previous); 16985 16986 OwnedDecl = true; 16987 // In C++, don't return an invalid declaration. We can't recover well from 16988 // the cases where we make the type anonymous. 16989 if (Invalid && getLangOpts().CPlusPlus) { 16990 if (New->isBeingDefined()) 16991 if (auto RD = dyn_cast<RecordDecl>(New)) 16992 RD->completeDefinition(); 16993 return nullptr; 16994 } else if (SkipBody && SkipBody->ShouldSkip) { 16995 return SkipBody->Previous; 16996 } else { 16997 return New; 16998 } 16999 } 17000 17001 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 17002 AdjustDeclIfTemplate(TagD); 17003 TagDecl *Tag = cast<TagDecl>(TagD); 17004 17005 // Enter the tag context. 17006 PushDeclContext(S, Tag); 17007 17008 ActOnDocumentableDecl(TagD); 17009 17010 // If there's a #pragma GCC visibility in scope, set the visibility of this 17011 // record. 17012 AddPushedVisibilityAttribute(Tag); 17013 } 17014 17015 bool Sema::ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody) { 17016 if (!hasStructuralCompatLayout(Prev, SkipBody.New)) 17017 return false; 17018 17019 // Make the previous decl visible. 17020 makeMergedDefinitionVisible(SkipBody.Previous); 17021 return true; 17022 } 17023 17024 void Sema::ActOnObjCContainerStartDefinition(ObjCContainerDecl *IDecl) { 17025 assert(IDecl->getLexicalParent() == CurContext && 17026 "The next DeclContext should be lexically contained in the current one."); 17027 CurContext = IDecl; 17028 } 17029 17030 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 17031 SourceLocation FinalLoc, 17032 bool IsFinalSpelledSealed, 17033 bool IsAbstract, 17034 SourceLocation LBraceLoc) { 17035 AdjustDeclIfTemplate(TagD); 17036 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 17037 17038 FieldCollector->StartClass(); 17039 17040 if (!Record->getIdentifier()) 17041 return; 17042 17043 if (IsAbstract) 17044 Record->markAbstract(); 17045 17046 if (FinalLoc.isValid()) { 17047 Record->addAttr(FinalAttr::Create( 17048 Context, FinalLoc, AttributeCommonInfo::AS_Keyword, 17049 static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed))); 17050 } 17051 // C++ [class]p2: 17052 // [...] The class-name is also inserted into the scope of the 17053 // class itself; this is known as the injected-class-name. For 17054 // purposes of access checking, the injected-class-name is treated 17055 // as if it were a public member name. 17056 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create( 17057 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(), 17058 Record->getLocation(), Record->getIdentifier(), 17059 /*PrevDecl=*/nullptr, 17060 /*DelayTypeCreation=*/true); 17061 Context.getTypeDeclType(InjectedClassName, Record); 17062 InjectedClassName->setImplicit(); 17063 InjectedClassName->setAccess(AS_public); 17064 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 17065 InjectedClassName->setDescribedClassTemplate(Template); 17066 PushOnScopeChains(InjectedClassName, S); 17067 assert(InjectedClassName->isInjectedClassName() && 17068 "Broken injected-class-name"); 17069 } 17070 17071 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 17072 SourceRange BraceRange) { 17073 AdjustDeclIfTemplate(TagD); 17074 TagDecl *Tag = cast<TagDecl>(TagD); 17075 Tag->setBraceRange(BraceRange); 17076 17077 // Make sure we "complete" the definition even it is invalid. 17078 if (Tag->isBeingDefined()) { 17079 assert(Tag->isInvalidDecl() && "We should already have completed it"); 17080 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 17081 RD->completeDefinition(); 17082 } 17083 17084 if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) { 17085 FieldCollector->FinishClass(); 17086 if (RD->hasAttr<SYCLSpecialClassAttr>()) { 17087 auto *Def = RD->getDefinition(); 17088 assert(Def && "The record is expected to have a completed definition"); 17089 unsigned NumInitMethods = 0; 17090 for (auto *Method : Def->methods()) { 17091 if (!Method->getIdentifier()) 17092 continue; 17093 if (Method->getName() == "__init") 17094 NumInitMethods++; 17095 } 17096 if (NumInitMethods > 1 || !Def->hasInitMethod()) 17097 Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method); 17098 } 17099 } 17100 17101 // Exit this scope of this tag's definition. 17102 PopDeclContext(); 17103 17104 if (getCurLexicalContext()->isObjCContainer() && 17105 Tag->getDeclContext()->isFileContext()) 17106 Tag->setTopLevelDeclInObjCContainer(); 17107 17108 // Notify the consumer that we've defined a tag. 17109 if (!Tag->isInvalidDecl()) 17110 Consumer.HandleTagDeclDefinition(Tag); 17111 17112 // Clangs implementation of #pragma align(packed) differs in bitfield layout 17113 // from XLs and instead matches the XL #pragma pack(1) behavior. 17114 if (Context.getTargetInfo().getTriple().isOSAIX() && 17115 AlignPackStack.hasValue()) { 17116 AlignPackInfo APInfo = AlignPackStack.CurrentValue; 17117 // Only diagnose #pragma align(packed). 17118 if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed) 17119 return; 17120 const RecordDecl *RD = dyn_cast<RecordDecl>(Tag); 17121 if (!RD) 17122 return; 17123 // Only warn if there is at least 1 bitfield member. 17124 if (llvm::any_of(RD->fields(), 17125 [](const FieldDecl *FD) { return FD->isBitField(); })) 17126 Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible); 17127 } 17128 } 17129 17130 void Sema::ActOnObjCContainerFinishDefinition() { 17131 // Exit this scope of this interface definition. 17132 PopDeclContext(); 17133 } 17134 17135 void Sema::ActOnObjCTemporaryExitContainerContext(ObjCContainerDecl *ObjCCtx) { 17136 assert(ObjCCtx == CurContext && "Mismatch of container contexts"); 17137 OriginalLexicalContext = ObjCCtx; 17138 ActOnObjCContainerFinishDefinition(); 17139 } 17140 17141 void Sema::ActOnObjCReenterContainerContext(ObjCContainerDecl *ObjCCtx) { 17142 ActOnObjCContainerStartDefinition(ObjCCtx); 17143 OriginalLexicalContext = nullptr; 17144 } 17145 17146 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 17147 AdjustDeclIfTemplate(TagD); 17148 TagDecl *Tag = cast<TagDecl>(TagD); 17149 Tag->setInvalidDecl(); 17150 17151 // Make sure we "complete" the definition even it is invalid. 17152 if (Tag->isBeingDefined()) { 17153 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 17154 RD->completeDefinition(); 17155 } 17156 17157 // We're undoing ActOnTagStartDefinition here, not 17158 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 17159 // the FieldCollector. 17160 17161 PopDeclContext(); 17162 } 17163 17164 // Note that FieldName may be null for anonymous bitfields. 17165 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 17166 IdentifierInfo *FieldName, QualType FieldTy, 17167 bool IsMsStruct, Expr *BitWidth) { 17168 assert(BitWidth); 17169 if (BitWidth->containsErrors()) 17170 return ExprError(); 17171 17172 // C99 6.7.2.1p4 - verify the field type. 17173 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 17174 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 17175 // Handle incomplete and sizeless types with a specific error. 17176 if (RequireCompleteSizedType(FieldLoc, FieldTy, 17177 diag::err_field_incomplete_or_sizeless)) 17178 return ExprError(); 17179 if (FieldName) 17180 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 17181 << FieldName << FieldTy << BitWidth->getSourceRange(); 17182 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 17183 << FieldTy << BitWidth->getSourceRange(); 17184 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 17185 UPPC_BitFieldWidth)) 17186 return ExprError(); 17187 17188 // If the bit-width is type- or value-dependent, don't try to check 17189 // it now. 17190 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 17191 return BitWidth; 17192 17193 llvm::APSInt Value; 17194 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold); 17195 if (ICE.isInvalid()) 17196 return ICE; 17197 BitWidth = ICE.get(); 17198 17199 // Zero-width bitfield is ok for anonymous field. 17200 if (Value == 0 && FieldName) 17201 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 17202 17203 if (Value.isSigned() && Value.isNegative()) { 17204 if (FieldName) 17205 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 17206 << FieldName << toString(Value, 10); 17207 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 17208 << toString(Value, 10); 17209 } 17210 17211 // The size of the bit-field must not exceed our maximum permitted object 17212 // size. 17213 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) { 17214 return Diag(FieldLoc, diag::err_bitfield_too_wide) 17215 << !FieldName << FieldName << toString(Value, 10); 17216 } 17217 17218 if (!FieldTy->isDependentType()) { 17219 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 17220 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 17221 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 17222 17223 // Over-wide bitfields are an error in C or when using the MSVC bitfield 17224 // ABI. 17225 bool CStdConstraintViolation = 17226 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 17227 bool MSBitfieldViolation = 17228 Value.ugt(TypeStorageSize) && 17229 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 17230 if (CStdConstraintViolation || MSBitfieldViolation) { 17231 unsigned DiagWidth = 17232 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 17233 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 17234 << (bool)FieldName << FieldName << toString(Value, 10) 17235 << !CStdConstraintViolation << DiagWidth; 17236 } 17237 17238 // Warn on types where the user might conceivably expect to get all 17239 // specified bits as value bits: that's all integral types other than 17240 // 'bool'. 17241 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) { 17242 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 17243 << FieldName << toString(Value, 10) 17244 << (unsigned)TypeWidth; 17245 } 17246 } 17247 17248 return BitWidth; 17249 } 17250 17251 /// ActOnField - Each field of a C struct/union is passed into this in order 17252 /// to create a FieldDecl object for it. 17253 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 17254 Declarator &D, Expr *BitfieldWidth) { 17255 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 17256 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 17257 /*InitStyle=*/ICIS_NoInit, AS_public); 17258 return Res; 17259 } 17260 17261 /// HandleField - Analyze a field of a C struct or a C++ data member. 17262 /// 17263 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 17264 SourceLocation DeclStart, 17265 Declarator &D, Expr *BitWidth, 17266 InClassInitStyle InitStyle, 17267 AccessSpecifier AS) { 17268 if (D.isDecompositionDeclarator()) { 17269 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 17270 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 17271 << Decomp.getSourceRange(); 17272 return nullptr; 17273 } 17274 17275 IdentifierInfo *II = D.getIdentifier(); 17276 SourceLocation Loc = DeclStart; 17277 if (II) Loc = D.getIdentifierLoc(); 17278 17279 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 17280 QualType T = TInfo->getType(); 17281 if (getLangOpts().CPlusPlus) { 17282 CheckExtraCXXDefaultArguments(D); 17283 17284 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 17285 UPPC_DataMemberType)) { 17286 D.setInvalidType(); 17287 T = Context.IntTy; 17288 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 17289 } 17290 } 17291 17292 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 17293 17294 if (D.getDeclSpec().isInlineSpecified()) 17295 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 17296 << getLangOpts().CPlusPlus17; 17297 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 17298 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 17299 diag::err_invalid_thread) 17300 << DeclSpec::getSpecifierName(TSCS); 17301 17302 // Check to see if this name was declared as a member previously 17303 NamedDecl *PrevDecl = nullptr; 17304 LookupResult Previous(*this, II, Loc, LookupMemberName, 17305 ForVisibleRedeclaration); 17306 LookupName(Previous, S); 17307 switch (Previous.getResultKind()) { 17308 case LookupResult::Found: 17309 case LookupResult::FoundUnresolvedValue: 17310 PrevDecl = Previous.getAsSingle<NamedDecl>(); 17311 break; 17312 17313 case LookupResult::FoundOverloaded: 17314 PrevDecl = Previous.getRepresentativeDecl(); 17315 break; 17316 17317 case LookupResult::NotFound: 17318 case LookupResult::NotFoundInCurrentInstantiation: 17319 case LookupResult::Ambiguous: 17320 break; 17321 } 17322 Previous.suppressDiagnostics(); 17323 17324 if (PrevDecl && PrevDecl->isTemplateParameter()) { 17325 // Maybe we will complain about the shadowed template parameter. 17326 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 17327 // Just pretend that we didn't see the previous declaration. 17328 PrevDecl = nullptr; 17329 } 17330 17331 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 17332 PrevDecl = nullptr; 17333 17334 bool Mutable 17335 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 17336 SourceLocation TSSL = D.getBeginLoc(); 17337 FieldDecl *NewFD 17338 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 17339 TSSL, AS, PrevDecl, &D); 17340 17341 if (NewFD->isInvalidDecl()) 17342 Record->setInvalidDecl(); 17343 17344 if (D.getDeclSpec().isModulePrivateSpecified()) 17345 NewFD->setModulePrivate(); 17346 17347 if (NewFD->isInvalidDecl() && PrevDecl) { 17348 // Don't introduce NewFD into scope; there's already something 17349 // with the same name in the same scope. 17350 } else if (II) { 17351 PushOnScopeChains(NewFD, S); 17352 } else 17353 Record->addDecl(NewFD); 17354 17355 return NewFD; 17356 } 17357 17358 /// Build a new FieldDecl and check its well-formedness. 17359 /// 17360 /// This routine builds a new FieldDecl given the fields name, type, 17361 /// record, etc. \p PrevDecl should refer to any previous declaration 17362 /// with the same name and in the same scope as the field to be 17363 /// created. 17364 /// 17365 /// \returns a new FieldDecl. 17366 /// 17367 /// \todo The Declarator argument is a hack. It will be removed once 17368 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 17369 TypeSourceInfo *TInfo, 17370 RecordDecl *Record, SourceLocation Loc, 17371 bool Mutable, Expr *BitWidth, 17372 InClassInitStyle InitStyle, 17373 SourceLocation TSSL, 17374 AccessSpecifier AS, NamedDecl *PrevDecl, 17375 Declarator *D) { 17376 IdentifierInfo *II = Name.getAsIdentifierInfo(); 17377 bool InvalidDecl = false; 17378 if (D) InvalidDecl = D->isInvalidType(); 17379 17380 // If we receive a broken type, recover by assuming 'int' and 17381 // marking this declaration as invalid. 17382 if (T.isNull() || T->containsErrors()) { 17383 InvalidDecl = true; 17384 T = Context.IntTy; 17385 } 17386 17387 QualType EltTy = Context.getBaseElementType(T); 17388 if (!EltTy->isDependentType() && !EltTy->containsErrors()) { 17389 if (RequireCompleteSizedType(Loc, EltTy, 17390 diag::err_field_incomplete_or_sizeless)) { 17391 // Fields of incomplete type force their record to be invalid. 17392 Record->setInvalidDecl(); 17393 InvalidDecl = true; 17394 } else { 17395 NamedDecl *Def; 17396 EltTy->isIncompleteType(&Def); 17397 if (Def && Def->isInvalidDecl()) { 17398 Record->setInvalidDecl(); 17399 InvalidDecl = true; 17400 } 17401 } 17402 } 17403 17404 // TR 18037 does not allow fields to be declared with address space 17405 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() || 17406 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { 17407 Diag(Loc, diag::err_field_with_address_space); 17408 Record->setInvalidDecl(); 17409 InvalidDecl = true; 17410 } 17411 17412 if (LangOpts.OpenCL) { 17413 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 17414 // used as structure or union field: image, sampler, event or block types. 17415 if (T->isEventT() || T->isImageType() || T->isSamplerT() || 17416 T->isBlockPointerType()) { 17417 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 17418 Record->setInvalidDecl(); 17419 InvalidDecl = true; 17420 } 17421 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension 17422 // is enabled. 17423 if (BitWidth && !getOpenCLOptions().isAvailableOption( 17424 "__cl_clang_bitfields", LangOpts)) { 17425 Diag(Loc, diag::err_opencl_bitfields); 17426 InvalidDecl = true; 17427 } 17428 } 17429 17430 // Anonymous bit-fields cannot be cv-qualified (CWG 2229). 17431 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && 17432 T.hasQualifiers()) { 17433 InvalidDecl = true; 17434 Diag(Loc, diag::err_anon_bitfield_qualifiers); 17435 } 17436 17437 // C99 6.7.2.1p8: A member of a structure or union may have any type other 17438 // than a variably modified type. 17439 if (!InvalidDecl && T->isVariablyModifiedType()) { 17440 if (!tryToFixVariablyModifiedVarType( 17441 TInfo, T, Loc, diag::err_typecheck_field_variable_size)) 17442 InvalidDecl = true; 17443 } 17444 17445 // Fields can not have abstract class types 17446 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 17447 diag::err_abstract_type_in_decl, 17448 AbstractFieldType)) 17449 InvalidDecl = true; 17450 17451 if (InvalidDecl) 17452 BitWidth = nullptr; 17453 // If this is declared as a bit-field, check the bit-field. 17454 if (BitWidth) { 17455 BitWidth = 17456 VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth).get(); 17457 if (!BitWidth) { 17458 InvalidDecl = true; 17459 BitWidth = nullptr; 17460 } 17461 } 17462 17463 // Check that 'mutable' is consistent with the type of the declaration. 17464 if (!InvalidDecl && Mutable) { 17465 unsigned DiagID = 0; 17466 if (T->isReferenceType()) 17467 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 17468 : diag::err_mutable_reference; 17469 else if (T.isConstQualified()) 17470 DiagID = diag::err_mutable_const; 17471 17472 if (DiagID) { 17473 SourceLocation ErrLoc = Loc; 17474 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 17475 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 17476 Diag(ErrLoc, DiagID); 17477 if (DiagID != diag::ext_mutable_reference) { 17478 Mutable = false; 17479 InvalidDecl = true; 17480 } 17481 } 17482 } 17483 17484 // C++11 [class.union]p8 (DR1460): 17485 // At most one variant member of a union may have a 17486 // brace-or-equal-initializer. 17487 if (InitStyle != ICIS_NoInit) 17488 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 17489 17490 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 17491 BitWidth, Mutable, InitStyle); 17492 if (InvalidDecl) 17493 NewFD->setInvalidDecl(); 17494 17495 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 17496 Diag(Loc, diag::err_duplicate_member) << II; 17497 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 17498 NewFD->setInvalidDecl(); 17499 } 17500 17501 if (!InvalidDecl && getLangOpts().CPlusPlus) { 17502 if (Record->isUnion()) { 17503 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 17504 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 17505 if (RDecl->getDefinition()) { 17506 // C++ [class.union]p1: An object of a class with a non-trivial 17507 // constructor, a non-trivial copy constructor, a non-trivial 17508 // destructor, or a non-trivial copy assignment operator 17509 // cannot be a member of a union, nor can an array of such 17510 // objects. 17511 if (CheckNontrivialField(NewFD)) 17512 NewFD->setInvalidDecl(); 17513 } 17514 } 17515 17516 // C++ [class.union]p1: If a union contains a member of reference type, 17517 // the program is ill-formed, except when compiling with MSVC extensions 17518 // enabled. 17519 if (EltTy->isReferenceType()) { 17520 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 17521 diag::ext_union_member_of_reference_type : 17522 diag::err_union_member_of_reference_type) 17523 << NewFD->getDeclName() << EltTy; 17524 if (!getLangOpts().MicrosoftExt) 17525 NewFD->setInvalidDecl(); 17526 } 17527 } 17528 } 17529 17530 // FIXME: We need to pass in the attributes given an AST 17531 // representation, not a parser representation. 17532 if (D) { 17533 // FIXME: The current scope is almost... but not entirely... correct here. 17534 ProcessDeclAttributes(getCurScope(), NewFD, *D); 17535 17536 if (NewFD->hasAttrs()) 17537 CheckAlignasUnderalignment(NewFD); 17538 } 17539 17540 // In auto-retain/release, infer strong retension for fields of 17541 // retainable type. 17542 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 17543 NewFD->setInvalidDecl(); 17544 17545 if (T.isObjCGCWeak()) 17546 Diag(Loc, diag::warn_attribute_weak_on_field); 17547 17548 // PPC MMA non-pointer types are not allowed as field types. 17549 if (Context.getTargetInfo().getTriple().isPPC64() && 17550 CheckPPCMMAType(T, NewFD->getLocation())) 17551 NewFD->setInvalidDecl(); 17552 17553 NewFD->setAccess(AS); 17554 return NewFD; 17555 } 17556 17557 bool Sema::CheckNontrivialField(FieldDecl *FD) { 17558 assert(FD); 17559 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 17560 17561 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 17562 return false; 17563 17564 QualType EltTy = Context.getBaseElementType(FD->getType()); 17565 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 17566 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 17567 if (RDecl->getDefinition()) { 17568 // We check for copy constructors before constructors 17569 // because otherwise we'll never get complaints about 17570 // copy constructors. 17571 17572 CXXSpecialMember member = CXXInvalid; 17573 // We're required to check for any non-trivial constructors. Since the 17574 // implicit default constructor is suppressed if there are any 17575 // user-declared constructors, we just need to check that there is a 17576 // trivial default constructor and a trivial copy constructor. (We don't 17577 // worry about move constructors here, since this is a C++98 check.) 17578 if (RDecl->hasNonTrivialCopyConstructor()) 17579 member = CXXCopyConstructor; 17580 else if (!RDecl->hasTrivialDefaultConstructor()) 17581 member = CXXDefaultConstructor; 17582 else if (RDecl->hasNonTrivialCopyAssignment()) 17583 member = CXXCopyAssignment; 17584 else if (RDecl->hasNonTrivialDestructor()) 17585 member = CXXDestructor; 17586 17587 if (member != CXXInvalid) { 17588 if (!getLangOpts().CPlusPlus11 && 17589 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 17590 // Objective-C++ ARC: it is an error to have a non-trivial field of 17591 // a union. However, system headers in Objective-C programs 17592 // occasionally have Objective-C lifetime objects within unions, 17593 // and rather than cause the program to fail, we make those 17594 // members unavailable. 17595 SourceLocation Loc = FD->getLocation(); 17596 if (getSourceManager().isInSystemHeader(Loc)) { 17597 if (!FD->hasAttr<UnavailableAttr>()) 17598 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 17599 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 17600 return false; 17601 } 17602 } 17603 17604 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 17605 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 17606 diag::err_illegal_union_or_anon_struct_member) 17607 << FD->getParent()->isUnion() << FD->getDeclName() << member; 17608 DiagnoseNontrivial(RDecl, member); 17609 return !getLangOpts().CPlusPlus11; 17610 } 17611 } 17612 } 17613 17614 return false; 17615 } 17616 17617 /// TranslateIvarVisibility - Translate visibility from a token ID to an 17618 /// AST enum value. 17619 static ObjCIvarDecl::AccessControl 17620 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 17621 switch (ivarVisibility) { 17622 default: llvm_unreachable("Unknown visitibility kind"); 17623 case tok::objc_private: return ObjCIvarDecl::Private; 17624 case tok::objc_public: return ObjCIvarDecl::Public; 17625 case tok::objc_protected: return ObjCIvarDecl::Protected; 17626 case tok::objc_package: return ObjCIvarDecl::Package; 17627 } 17628 } 17629 17630 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 17631 /// in order to create an IvarDecl object for it. 17632 Decl *Sema::ActOnIvar(Scope *S, 17633 SourceLocation DeclStart, 17634 Declarator &D, Expr *BitfieldWidth, 17635 tok::ObjCKeywordKind Visibility) { 17636 17637 IdentifierInfo *II = D.getIdentifier(); 17638 Expr *BitWidth = (Expr*)BitfieldWidth; 17639 SourceLocation Loc = DeclStart; 17640 if (II) Loc = D.getIdentifierLoc(); 17641 17642 // FIXME: Unnamed fields can be handled in various different ways, for 17643 // example, unnamed unions inject all members into the struct namespace! 17644 17645 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 17646 QualType T = TInfo->getType(); 17647 17648 if (BitWidth) { 17649 // 6.7.2.1p3, 6.7.2.1p4 17650 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 17651 if (!BitWidth) 17652 D.setInvalidType(); 17653 } else { 17654 // Not a bitfield. 17655 17656 // validate II. 17657 17658 } 17659 if (T->isReferenceType()) { 17660 Diag(Loc, diag::err_ivar_reference_type); 17661 D.setInvalidType(); 17662 } 17663 // C99 6.7.2.1p8: A member of a structure or union may have any type other 17664 // than a variably modified type. 17665 else if (T->isVariablyModifiedType()) { 17666 if (!tryToFixVariablyModifiedVarType( 17667 TInfo, T, Loc, diag::err_typecheck_ivar_variable_size)) 17668 D.setInvalidType(); 17669 } 17670 17671 // Get the visibility (access control) for this ivar. 17672 ObjCIvarDecl::AccessControl ac = 17673 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 17674 : ObjCIvarDecl::None; 17675 // Must set ivar's DeclContext to its enclosing interface. 17676 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 17677 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 17678 return nullptr; 17679 ObjCContainerDecl *EnclosingContext; 17680 if (ObjCImplementationDecl *IMPDecl = 17681 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 17682 if (LangOpts.ObjCRuntime.isFragile()) { 17683 // Case of ivar declared in an implementation. Context is that of its class. 17684 EnclosingContext = IMPDecl->getClassInterface(); 17685 assert(EnclosingContext && "Implementation has no class interface!"); 17686 } 17687 else 17688 EnclosingContext = EnclosingDecl; 17689 } else { 17690 if (ObjCCategoryDecl *CDecl = 17691 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 17692 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 17693 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 17694 return nullptr; 17695 } 17696 } 17697 EnclosingContext = EnclosingDecl; 17698 } 17699 17700 // Construct the decl. 17701 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 17702 DeclStart, Loc, II, T, 17703 TInfo, ac, (Expr *)BitfieldWidth); 17704 17705 if (II) { 17706 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 17707 ForVisibleRedeclaration); 17708 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 17709 && !isa<TagDecl>(PrevDecl)) { 17710 Diag(Loc, diag::err_duplicate_member) << II; 17711 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 17712 NewID->setInvalidDecl(); 17713 } 17714 } 17715 17716 // Process attributes attached to the ivar. 17717 ProcessDeclAttributes(S, NewID, D); 17718 17719 if (D.isInvalidType()) 17720 NewID->setInvalidDecl(); 17721 17722 // In ARC, infer 'retaining' for ivars of retainable type. 17723 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 17724 NewID->setInvalidDecl(); 17725 17726 if (D.getDeclSpec().isModulePrivateSpecified()) 17727 NewID->setModulePrivate(); 17728 17729 if (II) { 17730 // FIXME: When interfaces are DeclContexts, we'll need to add 17731 // these to the interface. 17732 S->AddDecl(NewID); 17733 IdResolver.AddDecl(NewID); 17734 } 17735 17736 if (LangOpts.ObjCRuntime.isNonFragile() && 17737 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 17738 Diag(Loc, diag::warn_ivars_in_interface); 17739 17740 return NewID; 17741 } 17742 17743 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 17744 /// class and class extensions. For every class \@interface and class 17745 /// extension \@interface, if the last ivar is a bitfield of any type, 17746 /// then add an implicit `char :0` ivar to the end of that interface. 17747 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 17748 SmallVectorImpl<Decl *> &AllIvarDecls) { 17749 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 17750 return; 17751 17752 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 17753 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 17754 17755 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) 17756 return; 17757 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 17758 if (!ID) { 17759 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 17760 if (!CD->IsClassExtension()) 17761 return; 17762 } 17763 // No need to add this to end of @implementation. 17764 else 17765 return; 17766 } 17767 // All conditions are met. Add a new bitfield to the tail end of ivars. 17768 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 17769 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 17770 17771 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 17772 DeclLoc, DeclLoc, nullptr, 17773 Context.CharTy, 17774 Context.getTrivialTypeSourceInfo(Context.CharTy, 17775 DeclLoc), 17776 ObjCIvarDecl::Private, BW, 17777 true); 17778 AllIvarDecls.push_back(Ivar); 17779 } 17780 17781 namespace { 17782 /// [class.dtor]p4: 17783 /// At the end of the definition of a class, overload resolution is 17784 /// performed among the prospective destructors declared in that class with 17785 /// an empty argument list to select the destructor for the class, also 17786 /// known as the selected destructor. 17787 /// 17788 /// We do the overload resolution here, then mark the selected constructor in the AST. 17789 /// Later CXXRecordDecl::getDestructor() will return the selected constructor. 17790 void ComputeSelectedDestructor(Sema &S, CXXRecordDecl *Record) { 17791 if (!Record->hasUserDeclaredDestructor()) { 17792 return; 17793 } 17794 17795 SourceLocation Loc = Record->getLocation(); 17796 OverloadCandidateSet OCS(Loc, OverloadCandidateSet::CSK_Normal); 17797 17798 for (auto *Decl : Record->decls()) { 17799 if (auto *DD = dyn_cast<CXXDestructorDecl>(Decl)) { 17800 if (DD->isInvalidDecl()) 17801 continue; 17802 S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {}, 17803 OCS); 17804 assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected."); 17805 } 17806 } 17807 17808 if (OCS.empty()) { 17809 return; 17810 } 17811 OverloadCandidateSet::iterator Best; 17812 unsigned Msg = 0; 17813 OverloadCandidateDisplayKind DisplayKind; 17814 17815 switch (OCS.BestViableFunction(S, Loc, Best)) { 17816 case OR_Success: 17817 case OR_Deleted: 17818 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(Best->Function)); 17819 break; 17820 17821 case OR_Ambiguous: 17822 Msg = diag::err_ambiguous_destructor; 17823 DisplayKind = OCD_AmbiguousCandidates; 17824 break; 17825 17826 case OR_No_Viable_Function: 17827 Msg = diag::err_no_viable_destructor; 17828 DisplayKind = OCD_AllCandidates; 17829 break; 17830 } 17831 17832 if (Msg) { 17833 // OpenCL have got their own thing going with destructors. It's slightly broken, 17834 // but we allow it. 17835 if (!S.LangOpts.OpenCL) { 17836 PartialDiagnostic Diag = S.PDiag(Msg) << Record; 17837 OCS.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, DisplayKind, {}); 17838 Record->setInvalidDecl(); 17839 } 17840 // It's a bit hacky: At this point we've raised an error but we want the 17841 // rest of the compiler to continue somehow working. However almost 17842 // everything we'll try to do with the class will depend on there being a 17843 // destructor. So let's pretend the first one is selected and hope for the 17844 // best. 17845 Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(OCS.begin()->Function)); 17846 } 17847 } 17848 } // namespace 17849 17850 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 17851 ArrayRef<Decl *> Fields, SourceLocation LBrac, 17852 SourceLocation RBrac, 17853 const ParsedAttributesView &Attrs) { 17854 assert(EnclosingDecl && "missing record or interface decl"); 17855 17856 // If this is an Objective-C @implementation or category and we have 17857 // new fields here we should reset the layout of the interface since 17858 // it will now change. 17859 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 17860 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 17861 switch (DC->getKind()) { 17862 default: break; 17863 case Decl::ObjCCategory: 17864 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 17865 break; 17866 case Decl::ObjCImplementation: 17867 Context. 17868 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 17869 break; 17870 } 17871 } 17872 17873 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 17874 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl); 17875 17876 if (CXXRecord && !CXXRecord->isDependentType()) 17877 ComputeSelectedDestructor(*this, CXXRecord); 17878 17879 // Start counting up the number of named members; make sure to include 17880 // members of anonymous structs and unions in the total. 17881 unsigned NumNamedMembers = 0; 17882 if (Record) { 17883 for (const auto *I : Record->decls()) { 17884 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 17885 if (IFD->getDeclName()) 17886 ++NumNamedMembers; 17887 } 17888 } 17889 17890 // Verify that all the fields are okay. 17891 SmallVector<FieldDecl*, 32> RecFields; 17892 17893 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 17894 i != end; ++i) { 17895 FieldDecl *FD = cast<FieldDecl>(*i); 17896 17897 // Get the type for the field. 17898 const Type *FDTy = FD->getType().getTypePtr(); 17899 17900 if (!FD->isAnonymousStructOrUnion()) { 17901 // Remember all fields written by the user. 17902 RecFields.push_back(FD); 17903 } 17904 17905 // If the field is already invalid for some reason, don't emit more 17906 // diagnostics about it. 17907 if (FD->isInvalidDecl()) { 17908 EnclosingDecl->setInvalidDecl(); 17909 continue; 17910 } 17911 17912 // C99 6.7.2.1p2: 17913 // A structure or union shall not contain a member with 17914 // incomplete or function type (hence, a structure shall not 17915 // contain an instance of itself, but may contain a pointer to 17916 // an instance of itself), except that the last member of a 17917 // structure with more than one named member may have incomplete 17918 // array type; such a structure (and any union containing, 17919 // possibly recursively, a member that is such a structure) 17920 // shall not be a member of a structure or an element of an 17921 // array. 17922 bool IsLastField = (i + 1 == Fields.end()); 17923 if (FDTy->isFunctionType()) { 17924 // Field declared as a function. 17925 Diag(FD->getLocation(), diag::err_field_declared_as_function) 17926 << FD->getDeclName(); 17927 FD->setInvalidDecl(); 17928 EnclosingDecl->setInvalidDecl(); 17929 continue; 17930 } else if (FDTy->isIncompleteArrayType() && 17931 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { 17932 if (Record) { 17933 // Flexible array member. 17934 // Microsoft and g++ is more permissive regarding flexible array. 17935 // It will accept flexible array in union and also 17936 // as the sole element of a struct/class. 17937 unsigned DiagID = 0; 17938 if (!Record->isUnion() && !IsLastField) { 17939 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) 17940 << FD->getDeclName() << FD->getType() << Record->getTagKind(); 17941 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); 17942 FD->setInvalidDecl(); 17943 EnclosingDecl->setInvalidDecl(); 17944 continue; 17945 } else if (Record->isUnion()) 17946 DiagID = getLangOpts().MicrosoftExt 17947 ? diag::ext_flexible_array_union_ms 17948 : getLangOpts().CPlusPlus 17949 ? diag::ext_flexible_array_union_gnu 17950 : diag::err_flexible_array_union; 17951 else if (NumNamedMembers < 1) 17952 DiagID = getLangOpts().MicrosoftExt 17953 ? diag::ext_flexible_array_empty_aggregate_ms 17954 : getLangOpts().CPlusPlus 17955 ? diag::ext_flexible_array_empty_aggregate_gnu 17956 : diag::err_flexible_array_empty_aggregate; 17957 17958 if (DiagID) 17959 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 17960 << Record->getTagKind(); 17961 // While the layout of types that contain virtual bases is not specified 17962 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 17963 // virtual bases after the derived members. This would make a flexible 17964 // array member declared at the end of an object not adjacent to the end 17965 // of the type. 17966 if (CXXRecord && CXXRecord->getNumVBases() != 0) 17967 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 17968 << FD->getDeclName() << Record->getTagKind(); 17969 if (!getLangOpts().C99) 17970 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 17971 << FD->getDeclName() << Record->getTagKind(); 17972 17973 // If the element type has a non-trivial destructor, we would not 17974 // implicitly destroy the elements, so disallow it for now. 17975 // 17976 // FIXME: GCC allows this. We should probably either implicitly delete 17977 // the destructor of the containing class, or just allow this. 17978 QualType BaseElem = Context.getBaseElementType(FD->getType()); 17979 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 17980 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 17981 << FD->getDeclName() << FD->getType(); 17982 FD->setInvalidDecl(); 17983 EnclosingDecl->setInvalidDecl(); 17984 continue; 17985 } 17986 // Okay, we have a legal flexible array member at the end of the struct. 17987 Record->setHasFlexibleArrayMember(true); 17988 } else { 17989 // In ObjCContainerDecl ivars with incomplete array type are accepted, 17990 // unless they are followed by another ivar. That check is done 17991 // elsewhere, after synthesized ivars are known. 17992 } 17993 } else if (!FDTy->isDependentType() && 17994 RequireCompleteSizedType( 17995 FD->getLocation(), FD->getType(), 17996 diag::err_field_incomplete_or_sizeless)) { 17997 // Incomplete type 17998 FD->setInvalidDecl(); 17999 EnclosingDecl->setInvalidDecl(); 18000 continue; 18001 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 18002 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 18003 // A type which contains a flexible array member is considered to be a 18004 // flexible array member. 18005 Record->setHasFlexibleArrayMember(true); 18006 if (!Record->isUnion()) { 18007 // If this is a struct/class and this is not the last element, reject 18008 // it. Note that GCC supports variable sized arrays in the middle of 18009 // structures. 18010 if (!IsLastField) 18011 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 18012 << FD->getDeclName() << FD->getType(); 18013 else { 18014 // We support flexible arrays at the end of structs in 18015 // other structs as an extension. 18016 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 18017 << FD->getDeclName(); 18018 } 18019 } 18020 } 18021 if (isa<ObjCContainerDecl>(EnclosingDecl) && 18022 RequireNonAbstractType(FD->getLocation(), FD->getType(), 18023 diag::err_abstract_type_in_decl, 18024 AbstractIvarType)) { 18025 // Ivars can not have abstract class types 18026 FD->setInvalidDecl(); 18027 } 18028 if (Record && FDTTy->getDecl()->hasObjectMember()) 18029 Record->setHasObjectMember(true); 18030 if (Record && FDTTy->getDecl()->hasVolatileMember()) 18031 Record->setHasVolatileMember(true); 18032 } else if (FDTy->isObjCObjectType()) { 18033 /// A field cannot be an Objective-c object 18034 Diag(FD->getLocation(), diag::err_statically_allocated_object) 18035 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 18036 QualType T = Context.getObjCObjectPointerType(FD->getType()); 18037 FD->setType(T); 18038 } else if (Record && Record->isUnion() && 18039 FD->getType().hasNonTrivialObjCLifetime() && 18040 getSourceManager().isInSystemHeader(FD->getLocation()) && 18041 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() && 18042 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong || 18043 !Context.hasDirectOwnershipQualifier(FD->getType()))) { 18044 // For backward compatibility, fields of C unions declared in system 18045 // headers that have non-trivial ObjC ownership qualifications are marked 18046 // as unavailable unless the qualifier is explicit and __strong. This can 18047 // break ABI compatibility between programs compiled with ARC and MRR, but 18048 // is a better option than rejecting programs using those unions under 18049 // ARC. 18050 FD->addAttr(UnavailableAttr::CreateImplicit( 18051 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, 18052 FD->getLocation())); 18053 } else if (getLangOpts().ObjC && 18054 getLangOpts().getGC() != LangOptions::NonGC && Record && 18055 !Record->hasObjectMember()) { 18056 if (FD->getType()->isObjCObjectPointerType() || 18057 FD->getType().isObjCGCStrong()) 18058 Record->setHasObjectMember(true); 18059 else if (Context.getAsArrayType(FD->getType())) { 18060 QualType BaseType = Context.getBaseElementType(FD->getType()); 18061 if (BaseType->isRecordType() && 18062 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember()) 18063 Record->setHasObjectMember(true); 18064 else if (BaseType->isObjCObjectPointerType() || 18065 BaseType.isObjCGCStrong()) 18066 Record->setHasObjectMember(true); 18067 } 18068 } 18069 18070 if (Record && !getLangOpts().CPlusPlus && 18071 !shouldIgnoreForRecordTriviality(FD)) { 18072 QualType FT = FD->getType(); 18073 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) { 18074 Record->setNonTrivialToPrimitiveDefaultInitialize(true); 18075 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 18076 Record->isUnion()) 18077 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true); 18078 } 18079 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); 18080 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) { 18081 Record->setNonTrivialToPrimitiveCopy(true); 18082 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion()) 18083 Record->setHasNonTrivialToPrimitiveCopyCUnion(true); 18084 } 18085 if (FT.isDestructedType()) { 18086 Record->setNonTrivialToPrimitiveDestroy(true); 18087 Record->setParamDestroyedInCallee(true); 18088 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion()) 18089 Record->setHasNonTrivialToPrimitiveDestructCUnion(true); 18090 } 18091 18092 if (const auto *RT = FT->getAs<RecordType>()) { 18093 if (RT->getDecl()->getArgPassingRestrictions() == 18094 RecordDecl::APK_CanNeverPassInRegs) 18095 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 18096 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) 18097 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 18098 } 18099 18100 if (Record && FD->getType().isVolatileQualified()) 18101 Record->setHasVolatileMember(true); 18102 // Keep track of the number of named members. 18103 if (FD->getIdentifier()) 18104 ++NumNamedMembers; 18105 } 18106 18107 // Okay, we successfully defined 'Record'. 18108 if (Record) { 18109 bool Completed = false; 18110 if (CXXRecord) { 18111 if (!CXXRecord->isInvalidDecl()) { 18112 // Set access bits correctly on the directly-declared conversions. 18113 for (CXXRecordDecl::conversion_iterator 18114 I = CXXRecord->conversion_begin(), 18115 E = CXXRecord->conversion_end(); I != E; ++I) 18116 I.setAccess((*I)->getAccess()); 18117 } 18118 18119 // Add any implicitly-declared members to this class. 18120 AddImplicitlyDeclaredMembersToClass(CXXRecord); 18121 18122 if (!CXXRecord->isDependentType()) { 18123 if (!CXXRecord->isInvalidDecl()) { 18124 // If we have virtual base classes, we may end up finding multiple 18125 // final overriders for a given virtual function. Check for this 18126 // problem now. 18127 if (CXXRecord->getNumVBases()) { 18128 CXXFinalOverriderMap FinalOverriders; 18129 CXXRecord->getFinalOverriders(FinalOverriders); 18130 18131 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 18132 MEnd = FinalOverriders.end(); 18133 M != MEnd; ++M) { 18134 for (OverridingMethods::iterator SO = M->second.begin(), 18135 SOEnd = M->second.end(); 18136 SO != SOEnd; ++SO) { 18137 assert(SO->second.size() > 0 && 18138 "Virtual function without overriding functions?"); 18139 if (SO->second.size() == 1) 18140 continue; 18141 18142 // C++ [class.virtual]p2: 18143 // In a derived class, if a virtual member function of a base 18144 // class subobject has more than one final overrider the 18145 // program is ill-formed. 18146 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 18147 << (const NamedDecl *)M->first << Record; 18148 Diag(M->first->getLocation(), 18149 diag::note_overridden_virtual_function); 18150 for (OverridingMethods::overriding_iterator 18151 OM = SO->second.begin(), 18152 OMEnd = SO->second.end(); 18153 OM != OMEnd; ++OM) 18154 Diag(OM->Method->getLocation(), diag::note_final_overrider) 18155 << (const NamedDecl *)M->first << OM->Method->getParent(); 18156 18157 Record->setInvalidDecl(); 18158 } 18159 } 18160 CXXRecord->completeDefinition(&FinalOverriders); 18161 Completed = true; 18162 } 18163 } 18164 } 18165 } 18166 18167 if (!Completed) 18168 Record->completeDefinition(); 18169 18170 // Handle attributes before checking the layout. 18171 ProcessDeclAttributeList(S, Record, Attrs); 18172 18173 // Check to see if a FieldDecl is a pointer to a function. 18174 auto IsFunctionPointer = [&](const Decl *D) { 18175 const FieldDecl *FD = dyn_cast<FieldDecl>(D); 18176 if (!FD) 18177 return false; 18178 QualType FieldType = FD->getType().getDesugaredType(Context); 18179 if (isa<PointerType>(FieldType)) { 18180 QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType(); 18181 return PointeeType.getDesugaredType(Context)->isFunctionType(); 18182 } 18183 return false; 18184 }; 18185 18186 // Maybe randomize the record's decls. We automatically randomize a record 18187 // of function pointers, unless it has the "no_randomize_layout" attribute. 18188 if (!getLangOpts().CPlusPlus && 18189 (Record->hasAttr<RandomizeLayoutAttr>() || 18190 (!Record->hasAttr<NoRandomizeLayoutAttr>() && 18191 llvm::all_of(Record->decls(), IsFunctionPointer))) && 18192 !Record->isUnion() && !getLangOpts().RandstructSeed.empty() && 18193 !Record->isRandomized()) { 18194 SmallVector<Decl *, 32> NewDeclOrdering; 18195 if (randstruct::randomizeStructureLayout(Context, Record, 18196 NewDeclOrdering)) 18197 Record->reorderDecls(NewDeclOrdering); 18198 } 18199 18200 // We may have deferred checking for a deleted destructor. Check now. 18201 if (CXXRecord) { 18202 auto *Dtor = CXXRecord->getDestructor(); 18203 if (Dtor && Dtor->isImplicit() && 18204 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { 18205 CXXRecord->setImplicitDestructorIsDeleted(); 18206 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 18207 } 18208 } 18209 18210 if (Record->hasAttrs()) { 18211 CheckAlignasUnderalignment(Record); 18212 18213 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 18214 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 18215 IA->getRange(), IA->getBestCase(), 18216 IA->getInheritanceModel()); 18217 } 18218 18219 // Check if the structure/union declaration is a type that can have zero 18220 // size in C. For C this is a language extension, for C++ it may cause 18221 // compatibility problems. 18222 bool CheckForZeroSize; 18223 if (!getLangOpts().CPlusPlus) { 18224 CheckForZeroSize = true; 18225 } else { 18226 // For C++ filter out types that cannot be referenced in C code. 18227 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 18228 CheckForZeroSize = 18229 CXXRecord->getLexicalDeclContext()->isExternCContext() && 18230 !CXXRecord->isDependentType() && !inTemplateInstantiation() && 18231 CXXRecord->isCLike(); 18232 } 18233 if (CheckForZeroSize) { 18234 bool ZeroSize = true; 18235 bool IsEmpty = true; 18236 unsigned NonBitFields = 0; 18237 for (RecordDecl::field_iterator I = Record->field_begin(), 18238 E = Record->field_end(); 18239 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 18240 IsEmpty = false; 18241 if (I->isUnnamedBitfield()) { 18242 if (!I->isZeroLengthBitField(Context)) 18243 ZeroSize = false; 18244 } else { 18245 ++NonBitFields; 18246 QualType FieldType = I->getType(); 18247 if (FieldType->isIncompleteType() || 18248 !Context.getTypeSizeInChars(FieldType).isZero()) 18249 ZeroSize = false; 18250 } 18251 } 18252 18253 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 18254 // allowed in C++, but warn if its declaration is inside 18255 // extern "C" block. 18256 if (ZeroSize) { 18257 Diag(RecLoc, getLangOpts().CPlusPlus ? 18258 diag::warn_zero_size_struct_union_in_extern_c : 18259 diag::warn_zero_size_struct_union_compat) 18260 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 18261 } 18262 18263 // Structs without named members are extension in C (C99 6.7.2.1p7), 18264 // but are accepted by GCC. 18265 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 18266 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 18267 diag::ext_no_named_members_in_struct_union) 18268 << Record->isUnion(); 18269 } 18270 } 18271 } else { 18272 ObjCIvarDecl **ClsFields = 18273 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 18274 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 18275 ID->setEndOfDefinitionLoc(RBrac); 18276 // Add ivar's to class's DeclContext. 18277 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 18278 ClsFields[i]->setLexicalDeclContext(ID); 18279 ID->addDecl(ClsFields[i]); 18280 } 18281 // Must enforce the rule that ivars in the base classes may not be 18282 // duplicates. 18283 if (ID->getSuperClass()) 18284 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 18285 } else if (ObjCImplementationDecl *IMPDecl = 18286 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 18287 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 18288 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 18289 // Ivar declared in @implementation never belongs to the implementation. 18290 // Only it is in implementation's lexical context. 18291 ClsFields[I]->setLexicalDeclContext(IMPDecl); 18292 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 18293 IMPDecl->setIvarLBraceLoc(LBrac); 18294 IMPDecl->setIvarRBraceLoc(RBrac); 18295 } else if (ObjCCategoryDecl *CDecl = 18296 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 18297 // case of ivars in class extension; all other cases have been 18298 // reported as errors elsewhere. 18299 // FIXME. Class extension does not have a LocEnd field. 18300 // CDecl->setLocEnd(RBrac); 18301 // Add ivar's to class extension's DeclContext. 18302 // Diagnose redeclaration of private ivars. 18303 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 18304 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 18305 if (IDecl) { 18306 if (const ObjCIvarDecl *ClsIvar = 18307 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 18308 Diag(ClsFields[i]->getLocation(), 18309 diag::err_duplicate_ivar_declaration); 18310 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 18311 continue; 18312 } 18313 for (const auto *Ext : IDecl->known_extensions()) { 18314 if (const ObjCIvarDecl *ClsExtIvar 18315 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 18316 Diag(ClsFields[i]->getLocation(), 18317 diag::err_duplicate_ivar_declaration); 18318 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 18319 continue; 18320 } 18321 } 18322 } 18323 ClsFields[i]->setLexicalDeclContext(CDecl); 18324 CDecl->addDecl(ClsFields[i]); 18325 } 18326 CDecl->setIvarLBraceLoc(LBrac); 18327 CDecl->setIvarRBraceLoc(RBrac); 18328 } 18329 } 18330 } 18331 18332 /// Determine whether the given integral value is representable within 18333 /// the given type T. 18334 static bool isRepresentableIntegerValue(ASTContext &Context, 18335 llvm::APSInt &Value, 18336 QualType T) { 18337 assert((T->isIntegralType(Context) || T->isEnumeralType()) && 18338 "Integral type required!"); 18339 unsigned BitWidth = Context.getIntWidth(T); 18340 18341 if (Value.isUnsigned() || Value.isNonNegative()) { 18342 if (T->isSignedIntegerOrEnumerationType()) 18343 --BitWidth; 18344 return Value.getActiveBits() <= BitWidth; 18345 } 18346 return Value.getMinSignedBits() <= BitWidth; 18347 } 18348 18349 // Given an integral type, return the next larger integral type 18350 // (or a NULL type of no such type exists). 18351 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 18352 // FIXME: Int128/UInt128 support, which also needs to be introduced into 18353 // enum checking below. 18354 assert((T->isIntegralType(Context) || 18355 T->isEnumeralType()) && "Integral type required!"); 18356 const unsigned NumTypes = 4; 18357 QualType SignedIntegralTypes[NumTypes] = { 18358 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 18359 }; 18360 QualType UnsignedIntegralTypes[NumTypes] = { 18361 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 18362 Context.UnsignedLongLongTy 18363 }; 18364 18365 unsigned BitWidth = Context.getTypeSize(T); 18366 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 18367 : UnsignedIntegralTypes; 18368 for (unsigned I = 0; I != NumTypes; ++I) 18369 if (Context.getTypeSize(Types[I]) > BitWidth) 18370 return Types[I]; 18371 18372 return QualType(); 18373 } 18374 18375 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 18376 EnumConstantDecl *LastEnumConst, 18377 SourceLocation IdLoc, 18378 IdentifierInfo *Id, 18379 Expr *Val) { 18380 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 18381 llvm::APSInt EnumVal(IntWidth); 18382 QualType EltTy; 18383 18384 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 18385 Val = nullptr; 18386 18387 if (Val) 18388 Val = DefaultLvalueConversion(Val).get(); 18389 18390 if (Val) { 18391 if (Enum->isDependentType() || Val->isTypeDependent() || 18392 Val->containsErrors()) 18393 EltTy = Context.DependentTy; 18394 else { 18395 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed 18396 // underlying type, but do allow it in all other contexts. 18397 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) { 18398 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 18399 // constant-expression in the enumerator-definition shall be a converted 18400 // constant expression of the underlying type. 18401 EltTy = Enum->getIntegerType(); 18402 ExprResult Converted = 18403 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 18404 CCEK_Enumerator); 18405 if (Converted.isInvalid()) 18406 Val = nullptr; 18407 else 18408 Val = Converted.get(); 18409 } else if (!Val->isValueDependent() && 18410 !(Val = 18411 VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold) 18412 .get())) { 18413 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 18414 } else { 18415 if (Enum->isComplete()) { 18416 EltTy = Enum->getIntegerType(); 18417 18418 // In Obj-C and Microsoft mode, require the enumeration value to be 18419 // representable in the underlying type of the enumeration. In C++11, 18420 // we perform a non-narrowing conversion as part of converted constant 18421 // expression checking. 18422 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 18423 if (Context.getTargetInfo() 18424 .getTriple() 18425 .isWindowsMSVCEnvironment()) { 18426 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 18427 } else { 18428 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 18429 } 18430 } 18431 18432 // Cast to the underlying type. 18433 Val = ImpCastExprToType(Val, EltTy, 18434 EltTy->isBooleanType() ? CK_IntegralToBoolean 18435 : CK_IntegralCast) 18436 .get(); 18437 } else if (getLangOpts().CPlusPlus) { 18438 // C++11 [dcl.enum]p5: 18439 // If the underlying type is not fixed, the type of each enumerator 18440 // is the type of its initializing value: 18441 // - If an initializer is specified for an enumerator, the 18442 // initializing value has the same type as the expression. 18443 EltTy = Val->getType(); 18444 } else { 18445 // C99 6.7.2.2p2: 18446 // The expression that defines the value of an enumeration constant 18447 // shall be an integer constant expression that has a value 18448 // representable as an int. 18449 18450 // Complain if the value is not representable in an int. 18451 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 18452 Diag(IdLoc, diag::ext_enum_value_not_int) 18453 << toString(EnumVal, 10) << Val->getSourceRange() 18454 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 18455 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 18456 // Force the type of the expression to 'int'. 18457 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 18458 } 18459 EltTy = Val->getType(); 18460 } 18461 } 18462 } 18463 } 18464 18465 if (!Val) { 18466 if (Enum->isDependentType()) 18467 EltTy = Context.DependentTy; 18468 else if (!LastEnumConst) { 18469 // C++0x [dcl.enum]p5: 18470 // If the underlying type is not fixed, the type of each enumerator 18471 // is the type of its initializing value: 18472 // - If no initializer is specified for the first enumerator, the 18473 // initializing value has an unspecified integral type. 18474 // 18475 // GCC uses 'int' for its unspecified integral type, as does 18476 // C99 6.7.2.2p3. 18477 if (Enum->isFixed()) { 18478 EltTy = Enum->getIntegerType(); 18479 } 18480 else { 18481 EltTy = Context.IntTy; 18482 } 18483 } else { 18484 // Assign the last value + 1. 18485 EnumVal = LastEnumConst->getInitVal(); 18486 ++EnumVal; 18487 EltTy = LastEnumConst->getType(); 18488 18489 // Check for overflow on increment. 18490 if (EnumVal < LastEnumConst->getInitVal()) { 18491 // C++0x [dcl.enum]p5: 18492 // If the underlying type is not fixed, the type of each enumerator 18493 // is the type of its initializing value: 18494 // 18495 // - Otherwise the type of the initializing value is the same as 18496 // the type of the initializing value of the preceding enumerator 18497 // unless the incremented value is not representable in that type, 18498 // in which case the type is an unspecified integral type 18499 // sufficient to contain the incremented value. If no such type 18500 // exists, the program is ill-formed. 18501 QualType T = getNextLargerIntegralType(Context, EltTy); 18502 if (T.isNull() || Enum->isFixed()) { 18503 // There is no integral type larger enough to represent this 18504 // value. Complain, then allow the value to wrap around. 18505 EnumVal = LastEnumConst->getInitVal(); 18506 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 18507 ++EnumVal; 18508 if (Enum->isFixed()) 18509 // When the underlying type is fixed, this is ill-formed. 18510 Diag(IdLoc, diag::err_enumerator_wrapped) 18511 << toString(EnumVal, 10) 18512 << EltTy; 18513 else 18514 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 18515 << toString(EnumVal, 10); 18516 } else { 18517 EltTy = T; 18518 } 18519 18520 // Retrieve the last enumerator's value, extent that type to the 18521 // type that is supposed to be large enough to represent the incremented 18522 // value, then increment. 18523 EnumVal = LastEnumConst->getInitVal(); 18524 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 18525 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 18526 ++EnumVal; 18527 18528 // If we're not in C++, diagnose the overflow of enumerator values, 18529 // which in C99 means that the enumerator value is not representable in 18530 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 18531 // permits enumerator values that are representable in some larger 18532 // integral type. 18533 if (!getLangOpts().CPlusPlus && !T.isNull()) 18534 Diag(IdLoc, diag::warn_enum_value_overflow); 18535 } else if (!getLangOpts().CPlusPlus && 18536 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 18537 // Enforce C99 6.7.2.2p2 even when we compute the next value. 18538 Diag(IdLoc, diag::ext_enum_value_not_int) 18539 << toString(EnumVal, 10) << 1; 18540 } 18541 } 18542 } 18543 18544 if (!EltTy->isDependentType()) { 18545 // Make the enumerator value match the signedness and size of the 18546 // enumerator's type. 18547 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 18548 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 18549 } 18550 18551 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 18552 Val, EnumVal); 18553 } 18554 18555 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 18556 SourceLocation IILoc) { 18557 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 18558 !getLangOpts().CPlusPlus) 18559 return SkipBodyInfo(); 18560 18561 // We have an anonymous enum definition. Look up the first enumerator to 18562 // determine if we should merge the definition with an existing one and 18563 // skip the body. 18564 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 18565 forRedeclarationInCurContext()); 18566 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 18567 if (!PrevECD) 18568 return SkipBodyInfo(); 18569 18570 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 18571 NamedDecl *Hidden; 18572 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 18573 SkipBodyInfo Skip; 18574 Skip.Previous = Hidden; 18575 return Skip; 18576 } 18577 18578 return SkipBodyInfo(); 18579 } 18580 18581 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 18582 SourceLocation IdLoc, IdentifierInfo *Id, 18583 const ParsedAttributesView &Attrs, 18584 SourceLocation EqualLoc, Expr *Val) { 18585 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 18586 EnumConstantDecl *LastEnumConst = 18587 cast_or_null<EnumConstantDecl>(lastEnumConst); 18588 18589 // The scope passed in may not be a decl scope. Zip up the scope tree until 18590 // we find one that is. 18591 S = getNonFieldDeclScope(S); 18592 18593 // Verify that there isn't already something declared with this name in this 18594 // scope. 18595 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration); 18596 LookupName(R, S); 18597 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>(); 18598 18599 if (PrevDecl && PrevDecl->isTemplateParameter()) { 18600 // Maybe we will complain about the shadowed template parameter. 18601 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 18602 // Just pretend that we didn't see the previous declaration. 18603 PrevDecl = nullptr; 18604 } 18605 18606 // C++ [class.mem]p15: 18607 // If T is the name of a class, then each of the following shall have a name 18608 // different from T: 18609 // - every enumerator of every member of class T that is an unscoped 18610 // enumerated type 18611 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) 18612 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 18613 DeclarationNameInfo(Id, IdLoc)); 18614 18615 EnumConstantDecl *New = 18616 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 18617 if (!New) 18618 return nullptr; 18619 18620 if (PrevDecl) { 18621 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) { 18622 // Check for other kinds of shadowing not already handled. 18623 CheckShadow(New, PrevDecl, R); 18624 } 18625 18626 // When in C++, we may get a TagDecl with the same name; in this case the 18627 // enum constant will 'hide' the tag. 18628 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 18629 "Received TagDecl when not in C++!"); 18630 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 18631 if (isa<EnumConstantDecl>(PrevDecl)) 18632 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 18633 else 18634 Diag(IdLoc, diag::err_redefinition) << Id; 18635 notePreviousDefinition(PrevDecl, IdLoc); 18636 return nullptr; 18637 } 18638 } 18639 18640 // Process attributes. 18641 ProcessDeclAttributeList(S, New, Attrs); 18642 AddPragmaAttributes(S, New); 18643 18644 // Register this decl in the current scope stack. 18645 New->setAccess(TheEnumDecl->getAccess()); 18646 PushOnScopeChains(New, S); 18647 18648 ActOnDocumentableDecl(New); 18649 18650 return New; 18651 } 18652 18653 // Returns true when the enum initial expression does not trigger the 18654 // duplicate enum warning. A few common cases are exempted as follows: 18655 // Element2 = Element1 18656 // Element2 = Element1 + 1 18657 // Element2 = Element1 - 1 18658 // Where Element2 and Element1 are from the same enum. 18659 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 18660 Expr *InitExpr = ECD->getInitExpr(); 18661 if (!InitExpr) 18662 return true; 18663 InitExpr = InitExpr->IgnoreImpCasts(); 18664 18665 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 18666 if (!BO->isAdditiveOp()) 18667 return true; 18668 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 18669 if (!IL) 18670 return true; 18671 if (IL->getValue() != 1) 18672 return true; 18673 18674 InitExpr = BO->getLHS(); 18675 } 18676 18677 // This checks if the elements are from the same enum. 18678 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 18679 if (!DRE) 18680 return true; 18681 18682 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 18683 if (!EnumConstant) 18684 return true; 18685 18686 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 18687 Enum) 18688 return true; 18689 18690 return false; 18691 } 18692 18693 // Emits a warning when an element is implicitly set a value that 18694 // a previous element has already been set to. 18695 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 18696 EnumDecl *Enum, QualType EnumType) { 18697 // Avoid anonymous enums 18698 if (!Enum->getIdentifier()) 18699 return; 18700 18701 // Only check for small enums. 18702 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 18703 return; 18704 18705 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 18706 return; 18707 18708 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 18709 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; 18710 18711 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 18712 18713 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map. 18714 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap; 18715 18716 // Use int64_t as a key to avoid needing special handling for map keys. 18717 auto EnumConstantToKey = [](const EnumConstantDecl *D) { 18718 llvm::APSInt Val = D->getInitVal(); 18719 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); 18720 }; 18721 18722 DuplicatesVector DupVector; 18723 ValueToVectorMap EnumMap; 18724 18725 // Populate the EnumMap with all values represented by enum constants without 18726 // an initializer. 18727 for (auto *Element : Elements) { 18728 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); 18729 18730 // Null EnumConstantDecl means a previous diagnostic has been emitted for 18731 // this constant. Skip this enum since it may be ill-formed. 18732 if (!ECD) { 18733 return; 18734 } 18735 18736 // Constants with initalizers are handled in the next loop. 18737 if (ECD->getInitExpr()) 18738 continue; 18739 18740 // Duplicate values are handled in the next loop. 18741 EnumMap.insert({EnumConstantToKey(ECD), ECD}); 18742 } 18743 18744 if (EnumMap.size() == 0) 18745 return; 18746 18747 // Create vectors for any values that has duplicates. 18748 for (auto *Element : Elements) { 18749 // The last loop returned if any constant was null. 18750 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); 18751 if (!ValidDuplicateEnum(ECD, Enum)) 18752 continue; 18753 18754 auto Iter = EnumMap.find(EnumConstantToKey(ECD)); 18755 if (Iter == EnumMap.end()) 18756 continue; 18757 18758 DeclOrVector& Entry = Iter->second; 18759 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 18760 // Ensure constants are different. 18761 if (D == ECD) 18762 continue; 18763 18764 // Create new vector and push values onto it. 18765 auto Vec = std::make_unique<ECDVector>(); 18766 Vec->push_back(D); 18767 Vec->push_back(ECD); 18768 18769 // Update entry to point to the duplicates vector. 18770 Entry = Vec.get(); 18771 18772 // Store the vector somewhere we can consult later for quick emission of 18773 // diagnostics. 18774 DupVector.emplace_back(std::move(Vec)); 18775 continue; 18776 } 18777 18778 ECDVector *Vec = Entry.get<ECDVector*>(); 18779 // Make sure constants are not added more than once. 18780 if (*Vec->begin() == ECD) 18781 continue; 18782 18783 Vec->push_back(ECD); 18784 } 18785 18786 // Emit diagnostics. 18787 for (const auto &Vec : DupVector) { 18788 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 18789 18790 // Emit warning for one enum constant. 18791 auto *FirstECD = Vec->front(); 18792 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) 18793 << FirstECD << toString(FirstECD->getInitVal(), 10) 18794 << FirstECD->getSourceRange(); 18795 18796 // Emit one note for each of the remaining enum constants with 18797 // the same value. 18798 for (auto *ECD : llvm::drop_begin(*Vec)) 18799 S.Diag(ECD->getLocation(), diag::note_duplicate_element) 18800 << ECD << toString(ECD->getInitVal(), 10) 18801 << ECD->getSourceRange(); 18802 } 18803 } 18804 18805 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 18806 bool AllowMask) const { 18807 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 18808 assert(ED->isCompleteDefinition() && "expected enum definition"); 18809 18810 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 18811 llvm::APInt &FlagBits = R.first->second; 18812 18813 if (R.second) { 18814 for (auto *E : ED->enumerators()) { 18815 const auto &EVal = E->getInitVal(); 18816 // Only single-bit enumerators introduce new flag values. 18817 if (EVal.isPowerOf2()) 18818 FlagBits = FlagBits.zext(EVal.getBitWidth()) | EVal; 18819 } 18820 } 18821 18822 // A value is in a flag enum if either its bits are a subset of the enum's 18823 // flag bits (the first condition) or we are allowing masks and the same is 18824 // true of its complement (the second condition). When masks are allowed, we 18825 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 18826 // 18827 // While it's true that any value could be used as a mask, the assumption is 18828 // that a mask will have all of the insignificant bits set. Anything else is 18829 // likely a logic error. 18830 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 18831 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 18832 } 18833 18834 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 18835 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S, 18836 const ParsedAttributesView &Attrs) { 18837 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 18838 QualType EnumType = Context.getTypeDeclType(Enum); 18839 18840 ProcessDeclAttributeList(S, Enum, Attrs); 18841 18842 if (Enum->isDependentType()) { 18843 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 18844 EnumConstantDecl *ECD = 18845 cast_or_null<EnumConstantDecl>(Elements[i]); 18846 if (!ECD) continue; 18847 18848 ECD->setType(EnumType); 18849 } 18850 18851 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 18852 return; 18853 } 18854 18855 // TODO: If the result value doesn't fit in an int, it must be a long or long 18856 // long value. ISO C does not support this, but GCC does as an extension, 18857 // emit a warning. 18858 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 18859 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 18860 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 18861 18862 // Verify that all the values are okay, compute the size of the values, and 18863 // reverse the list. 18864 unsigned NumNegativeBits = 0; 18865 unsigned NumPositiveBits = 0; 18866 18867 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 18868 EnumConstantDecl *ECD = 18869 cast_or_null<EnumConstantDecl>(Elements[i]); 18870 if (!ECD) continue; // Already issued a diagnostic. 18871 18872 const llvm::APSInt &InitVal = ECD->getInitVal(); 18873 18874 // Keep track of the size of positive and negative values. 18875 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 18876 NumPositiveBits = std::max(NumPositiveBits, 18877 (unsigned)InitVal.getActiveBits()); 18878 else 18879 NumNegativeBits = std::max(NumNegativeBits, 18880 (unsigned)InitVal.getMinSignedBits()); 18881 } 18882 18883 // Figure out the type that should be used for this enum. 18884 QualType BestType; 18885 unsigned BestWidth; 18886 18887 // C++0x N3000 [conv.prom]p3: 18888 // An rvalue of an unscoped enumeration type whose underlying 18889 // type is not fixed can be converted to an rvalue of the first 18890 // of the following types that can represent all the values of 18891 // the enumeration: int, unsigned int, long int, unsigned long 18892 // int, long long int, or unsigned long long int. 18893 // C99 6.4.4.3p2: 18894 // An identifier declared as an enumeration constant has type int. 18895 // The C99 rule is modified by a gcc extension 18896 QualType BestPromotionType; 18897 18898 bool Packed = Enum->hasAttr<PackedAttr>(); 18899 // -fshort-enums is the equivalent to specifying the packed attribute on all 18900 // enum definitions. 18901 if (LangOpts.ShortEnums) 18902 Packed = true; 18903 18904 // If the enum already has a type because it is fixed or dictated by the 18905 // target, promote that type instead of analyzing the enumerators. 18906 if (Enum->isComplete()) { 18907 BestType = Enum->getIntegerType(); 18908 if (BestType->isPromotableIntegerType()) 18909 BestPromotionType = Context.getPromotedIntegerType(BestType); 18910 else 18911 BestPromotionType = BestType; 18912 18913 BestWidth = Context.getIntWidth(BestType); 18914 } 18915 else if (NumNegativeBits) { 18916 // If there is a negative value, figure out the smallest integer type (of 18917 // int/long/longlong) that fits. 18918 // If it's packed, check also if it fits a char or a short. 18919 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 18920 BestType = Context.SignedCharTy; 18921 BestWidth = CharWidth; 18922 } else if (Packed && NumNegativeBits <= ShortWidth && 18923 NumPositiveBits < ShortWidth) { 18924 BestType = Context.ShortTy; 18925 BestWidth = ShortWidth; 18926 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 18927 BestType = Context.IntTy; 18928 BestWidth = IntWidth; 18929 } else { 18930 BestWidth = Context.getTargetInfo().getLongWidth(); 18931 18932 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 18933 BestType = Context.LongTy; 18934 } else { 18935 BestWidth = Context.getTargetInfo().getLongLongWidth(); 18936 18937 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 18938 Diag(Enum->getLocation(), diag::ext_enum_too_large); 18939 BestType = Context.LongLongTy; 18940 } 18941 } 18942 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 18943 } else { 18944 // If there is no negative value, figure out the smallest type that fits 18945 // all of the enumerator values. 18946 // If it's packed, check also if it fits a char or a short. 18947 if (Packed && NumPositiveBits <= CharWidth) { 18948 BestType = Context.UnsignedCharTy; 18949 BestPromotionType = Context.IntTy; 18950 BestWidth = CharWidth; 18951 } else if (Packed && NumPositiveBits <= ShortWidth) { 18952 BestType = Context.UnsignedShortTy; 18953 BestPromotionType = Context.IntTy; 18954 BestWidth = ShortWidth; 18955 } else if (NumPositiveBits <= IntWidth) { 18956 BestType = Context.UnsignedIntTy; 18957 BestWidth = IntWidth; 18958 BestPromotionType 18959 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18960 ? Context.UnsignedIntTy : Context.IntTy; 18961 } else if (NumPositiveBits <= 18962 (BestWidth = Context.getTargetInfo().getLongWidth())) { 18963 BestType = Context.UnsignedLongTy; 18964 BestPromotionType 18965 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18966 ? Context.UnsignedLongTy : Context.LongTy; 18967 } else { 18968 BestWidth = Context.getTargetInfo().getLongLongWidth(); 18969 assert(NumPositiveBits <= BestWidth && 18970 "How could an initializer get larger than ULL?"); 18971 BestType = Context.UnsignedLongLongTy; 18972 BestPromotionType 18973 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18974 ? Context.UnsignedLongLongTy : Context.LongLongTy; 18975 } 18976 } 18977 18978 // Loop over all of the enumerator constants, changing their types to match 18979 // the type of the enum if needed. 18980 for (auto *D : Elements) { 18981 auto *ECD = cast_or_null<EnumConstantDecl>(D); 18982 if (!ECD) continue; // Already issued a diagnostic. 18983 18984 // Standard C says the enumerators have int type, but we allow, as an 18985 // extension, the enumerators to be larger than int size. If each 18986 // enumerator value fits in an int, type it as an int, otherwise type it the 18987 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 18988 // that X has type 'int', not 'unsigned'. 18989 18990 // Determine whether the value fits into an int. 18991 llvm::APSInt InitVal = ECD->getInitVal(); 18992 18993 // If it fits into an integer type, force it. Otherwise force it to match 18994 // the enum decl type. 18995 QualType NewTy; 18996 unsigned NewWidth; 18997 bool NewSign; 18998 if (!getLangOpts().CPlusPlus && 18999 !Enum->isFixed() && 19000 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 19001 NewTy = Context.IntTy; 19002 NewWidth = IntWidth; 19003 NewSign = true; 19004 } else if (ECD->getType() == BestType) { 19005 // Already the right type! 19006 if (getLangOpts().CPlusPlus) 19007 // C++ [dcl.enum]p4: Following the closing brace of an 19008 // enum-specifier, each enumerator has the type of its 19009 // enumeration. 19010 ECD->setType(EnumType); 19011 continue; 19012 } else { 19013 NewTy = BestType; 19014 NewWidth = BestWidth; 19015 NewSign = BestType->isSignedIntegerOrEnumerationType(); 19016 } 19017 19018 // Adjust the APSInt value. 19019 InitVal = InitVal.extOrTrunc(NewWidth); 19020 InitVal.setIsSigned(NewSign); 19021 ECD->setInitVal(InitVal); 19022 19023 // Adjust the Expr initializer and type. 19024 if (ECD->getInitExpr() && 19025 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 19026 ECD->setInitExpr(ImplicitCastExpr::Create( 19027 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(), 19028 /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride())); 19029 if (getLangOpts().CPlusPlus) 19030 // C++ [dcl.enum]p4: Following the closing brace of an 19031 // enum-specifier, each enumerator has the type of its 19032 // enumeration. 19033 ECD->setType(EnumType); 19034 else 19035 ECD->setType(NewTy); 19036 } 19037 19038 Enum->completeDefinition(BestType, BestPromotionType, 19039 NumPositiveBits, NumNegativeBits); 19040 19041 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 19042 19043 if (Enum->isClosedFlag()) { 19044 for (Decl *D : Elements) { 19045 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 19046 if (!ECD) continue; // Already issued a diagnostic. 19047 19048 llvm::APSInt InitVal = ECD->getInitVal(); 19049 if (InitVal != 0 && !InitVal.isPowerOf2() && 19050 !IsValueInFlagEnum(Enum, InitVal, true)) 19051 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 19052 << ECD << Enum; 19053 } 19054 } 19055 19056 // Now that the enum type is defined, ensure it's not been underaligned. 19057 if (Enum->hasAttrs()) 19058 CheckAlignasUnderalignment(Enum); 19059 } 19060 19061 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 19062 SourceLocation StartLoc, 19063 SourceLocation EndLoc) { 19064 StringLiteral *AsmString = cast<StringLiteral>(expr); 19065 19066 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 19067 AsmString, StartLoc, 19068 EndLoc); 19069 CurContext->addDecl(New); 19070 return New; 19071 } 19072 19073 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 19074 IdentifierInfo* AliasName, 19075 SourceLocation PragmaLoc, 19076 SourceLocation NameLoc, 19077 SourceLocation AliasNameLoc) { 19078 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 19079 LookupOrdinaryName); 19080 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc), 19081 AttributeCommonInfo::AS_Pragma); 19082 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit( 19083 Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info); 19084 19085 // If a declaration that: 19086 // 1) declares a function or a variable 19087 // 2) has external linkage 19088 // already exists, add a label attribute to it. 19089 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 19090 if (isDeclExternC(PrevDecl)) 19091 PrevDecl->addAttr(Attr); 19092 else 19093 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 19094 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 19095 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 19096 } else 19097 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 19098 } 19099 19100 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 19101 SourceLocation PragmaLoc, 19102 SourceLocation NameLoc) { 19103 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 19104 19105 if (PrevDecl) { 19106 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma)); 19107 } else { 19108 (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc)); 19109 } 19110 } 19111 19112 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 19113 IdentifierInfo* AliasName, 19114 SourceLocation PragmaLoc, 19115 SourceLocation NameLoc, 19116 SourceLocation AliasNameLoc) { 19117 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 19118 LookupOrdinaryName); 19119 WeakInfo W = WeakInfo(Name, NameLoc); 19120 19121 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 19122 if (!PrevDecl->hasAttr<AliasAttr>()) 19123 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 19124 DeclApplyPragmaWeak(TUScope, ND, W); 19125 } else { 19126 (void)WeakUndeclaredIdentifiers[AliasName].insert(W); 19127 } 19128 } 19129 19130 ObjCContainerDecl *Sema::getObjCDeclContext() const { 19131 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 19132 } 19133 19134 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD, 19135 bool Final) { 19136 assert(FD && "Expected non-null FunctionDecl"); 19137 19138 // SYCL functions can be template, so we check if they have appropriate 19139 // attribute prior to checking if it is a template. 19140 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>()) 19141 return FunctionEmissionStatus::Emitted; 19142 19143 // Templates are emitted when they're instantiated. 19144 if (FD->isDependentContext()) 19145 return FunctionEmissionStatus::TemplateDiscarded; 19146 19147 // Check whether this function is an externally visible definition. 19148 auto IsEmittedForExternalSymbol = [this, FD]() { 19149 // We have to check the GVA linkage of the function's *definition* -- if we 19150 // only have a declaration, we don't know whether or not the function will 19151 // be emitted, because (say) the definition could include "inline". 19152 FunctionDecl *Def = FD->getDefinition(); 19153 19154 return Def && !isDiscardableGVALinkage( 19155 getASTContext().GetGVALinkageForFunction(Def)); 19156 }; 19157 19158 if (LangOpts.OpenMPIsDevice) { 19159 // In OpenMP device mode we will not emit host only functions, or functions 19160 // we don't need due to their linkage. 19161 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 19162 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 19163 // DevTy may be changed later by 19164 // #pragma omp declare target to(*) device_type(*). 19165 // Therefore DevTy having no value does not imply host. The emission status 19166 // will be checked again at the end of compilation unit with Final = true. 19167 if (DevTy) 19168 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host) 19169 return FunctionEmissionStatus::OMPDiscarded; 19170 // If we have an explicit value for the device type, or we are in a target 19171 // declare context, we need to emit all extern and used symbols. 19172 if (isInOpenMPDeclareTargetContext() || DevTy) 19173 if (IsEmittedForExternalSymbol()) 19174 return FunctionEmissionStatus::Emitted; 19175 // Device mode only emits what it must, if it wasn't tagged yet and needed, 19176 // we'll omit it. 19177 if (Final) 19178 return FunctionEmissionStatus::OMPDiscarded; 19179 } else if (LangOpts.OpenMP > 45) { 19180 // In OpenMP host compilation prior to 5.0 everything was an emitted host 19181 // function. In 5.0, no_host was introduced which might cause a function to 19182 // be ommitted. 19183 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 19184 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 19185 if (DevTy) 19186 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) 19187 return FunctionEmissionStatus::OMPDiscarded; 19188 } 19189 19190 if (Final && LangOpts.OpenMP && !LangOpts.CUDA) 19191 return FunctionEmissionStatus::Emitted; 19192 19193 if (LangOpts.CUDA) { 19194 // When compiling for device, host functions are never emitted. Similarly, 19195 // when compiling for host, device and global functions are never emitted. 19196 // (Technically, we do emit a host-side stub for global functions, but this 19197 // doesn't count for our purposes here.) 19198 Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD); 19199 if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host) 19200 return FunctionEmissionStatus::CUDADiscarded; 19201 if (!LangOpts.CUDAIsDevice && 19202 (T == Sema::CFT_Device || T == Sema::CFT_Global)) 19203 return FunctionEmissionStatus::CUDADiscarded; 19204 19205 if (IsEmittedForExternalSymbol()) 19206 return FunctionEmissionStatus::Emitted; 19207 } 19208 19209 // Otherwise, the function is known-emitted if it's in our set of 19210 // known-emitted functions. 19211 return FunctionEmissionStatus::Unknown; 19212 } 19213 19214 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) { 19215 // Host-side references to a __global__ function refer to the stub, so the 19216 // function itself is never emitted and therefore should not be marked. 19217 // If we have host fn calls kernel fn calls host+device, the HD function 19218 // does not get instantiated on the host. We model this by omitting at the 19219 // call to the kernel from the callgraph. This ensures that, when compiling 19220 // for host, only HD functions actually called from the host get marked as 19221 // known-emitted. 19222 return LangOpts.CUDA && !LangOpts.CUDAIsDevice && 19223 IdentifyCUDATarget(Callee) == CFT_Global; 19224 } 19225