1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements semantic analysis for declarations. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "TypeLocBuilder.h" 14 #include "clang/AST/ASTConsumer.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/ASTLambda.h" 17 #include "clang/AST/CXXInheritance.h" 18 #include "clang/AST/CharUnits.h" 19 #include "clang/AST/CommentDiagnostic.h" 20 #include "clang/AST/DeclCXX.h" 21 #include "clang/AST/DeclObjC.h" 22 #include "clang/AST/DeclTemplate.h" 23 #include "clang/AST/EvaluatedExprVisitor.h" 24 #include "clang/AST/ExprCXX.h" 25 #include "clang/AST/NonTrivialTypeVisitor.h" 26 #include "clang/AST/StmtCXX.h" 27 #include "clang/Basic/Builtins.h" 28 #include "clang/Basic/PartialDiagnostic.h" 29 #include "clang/Basic/SourceManager.h" 30 #include "clang/Basic/TargetInfo.h" 31 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex 32 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 33 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex 34 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled() 35 #include "clang/Sema/CXXFieldCollector.h" 36 #include "clang/Sema/DeclSpec.h" 37 #include "clang/Sema/DelayedDiagnostic.h" 38 #include "clang/Sema/Initialization.h" 39 #include "clang/Sema/Lookup.h" 40 #include "clang/Sema/ParsedTemplate.h" 41 #include "clang/Sema/Scope.h" 42 #include "clang/Sema/ScopeInfo.h" 43 #include "clang/Sema/SemaInternal.h" 44 #include "clang/Sema/Template.h" 45 #include "llvm/ADT/SmallString.h" 46 #include "llvm/ADT/Triple.h" 47 #include <algorithm> 48 #include <cstring> 49 #include <functional> 50 51 using namespace clang; 52 using namespace sema; 53 54 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { 55 if (OwnedType) { 56 Decl *Group[2] = { OwnedType, Ptr }; 57 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); 58 } 59 60 return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); 61 } 62 63 namespace { 64 65 class TypeNameValidatorCCC final : public CorrectionCandidateCallback { 66 public: 67 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false, 68 bool AllowTemplates = false, 69 bool AllowNonTemplates = true) 70 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass), 71 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) { 72 WantExpressionKeywords = false; 73 WantCXXNamedCasts = false; 74 WantRemainingKeywords = false; 75 } 76 77 bool ValidateCandidate(const TypoCorrection &candidate) override { 78 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 79 if (!AllowInvalidDecl && ND->isInvalidDecl()) 80 return false; 81 82 if (getAsTypeTemplateDecl(ND)) 83 return AllowTemplates; 84 85 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 86 if (!IsType) 87 return false; 88 89 if (AllowNonTemplates) 90 return true; 91 92 // An injected-class-name of a class template (specialization) is valid 93 // as a template or as a non-template. 94 if (AllowTemplates) { 95 auto *RD = dyn_cast<CXXRecordDecl>(ND); 96 if (!RD || !RD->isInjectedClassName()) 97 return false; 98 RD = cast<CXXRecordDecl>(RD->getDeclContext()); 99 return RD->getDescribedClassTemplate() || 100 isa<ClassTemplateSpecializationDecl>(RD); 101 } 102 103 return false; 104 } 105 106 return !WantClassName && candidate.isKeyword(); 107 } 108 109 std::unique_ptr<CorrectionCandidateCallback> clone() override { 110 return std::make_unique<TypeNameValidatorCCC>(*this); 111 } 112 113 private: 114 bool AllowInvalidDecl; 115 bool WantClassName; 116 bool AllowTemplates; 117 bool AllowNonTemplates; 118 }; 119 120 } // end anonymous namespace 121 122 /// Determine whether the token kind starts a simple-type-specifier. 123 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { 124 switch (Kind) { 125 // FIXME: Take into account the current language when deciding whether a 126 // token kind is a valid type specifier 127 case tok::kw_short: 128 case tok::kw_long: 129 case tok::kw___int64: 130 case tok::kw___int128: 131 case tok::kw_signed: 132 case tok::kw_unsigned: 133 case tok::kw_void: 134 case tok::kw_char: 135 case tok::kw_int: 136 case tok::kw_half: 137 case tok::kw_float: 138 case tok::kw_double: 139 case tok::kw__Float16: 140 case tok::kw___float128: 141 case tok::kw_wchar_t: 142 case tok::kw_bool: 143 case tok::kw___underlying_type: 144 case tok::kw___auto_type: 145 return true; 146 147 case tok::annot_typename: 148 case tok::kw_char16_t: 149 case tok::kw_char32_t: 150 case tok::kw_typeof: 151 case tok::annot_decltype: 152 case tok::kw_decltype: 153 return getLangOpts().CPlusPlus; 154 155 case tok::kw_char8_t: 156 return getLangOpts().Char8; 157 158 default: 159 break; 160 } 161 162 return false; 163 } 164 165 namespace { 166 enum class UnqualifiedTypeNameLookupResult { 167 NotFound, 168 FoundNonType, 169 FoundType 170 }; 171 } // end anonymous namespace 172 173 /// Tries to perform unqualified lookup of the type decls in bases for 174 /// dependent class. 175 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a 176 /// type decl, \a FoundType if only type decls are found. 177 static UnqualifiedTypeNameLookupResult 178 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, 179 SourceLocation NameLoc, 180 const CXXRecordDecl *RD) { 181 if (!RD->hasDefinition()) 182 return UnqualifiedTypeNameLookupResult::NotFound; 183 // Look for type decls in base classes. 184 UnqualifiedTypeNameLookupResult FoundTypeDecl = 185 UnqualifiedTypeNameLookupResult::NotFound; 186 for (const auto &Base : RD->bases()) { 187 const CXXRecordDecl *BaseRD = nullptr; 188 if (auto *BaseTT = Base.getType()->getAs<TagType>()) 189 BaseRD = BaseTT->getAsCXXRecordDecl(); 190 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { 191 // Look for type decls in dependent base classes that have known primary 192 // templates. 193 if (!TST || !TST->isDependentType()) 194 continue; 195 auto *TD = TST->getTemplateName().getAsTemplateDecl(); 196 if (!TD) 197 continue; 198 if (auto *BasePrimaryTemplate = 199 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) { 200 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl()) 201 BaseRD = BasePrimaryTemplate; 202 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) { 203 if (const ClassTemplatePartialSpecializationDecl *PS = 204 CTD->findPartialSpecialization(Base.getType())) 205 if (PS->getCanonicalDecl() != RD->getCanonicalDecl()) 206 BaseRD = PS; 207 } 208 } 209 } 210 if (BaseRD) { 211 for (NamedDecl *ND : BaseRD->lookup(&II)) { 212 if (!isa<TypeDecl>(ND)) 213 return UnqualifiedTypeNameLookupResult::FoundNonType; 214 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 215 } 216 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { 217 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { 218 case UnqualifiedTypeNameLookupResult::FoundNonType: 219 return UnqualifiedTypeNameLookupResult::FoundNonType; 220 case UnqualifiedTypeNameLookupResult::FoundType: 221 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 222 break; 223 case UnqualifiedTypeNameLookupResult::NotFound: 224 break; 225 } 226 } 227 } 228 } 229 230 return FoundTypeDecl; 231 } 232 233 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, 234 const IdentifierInfo &II, 235 SourceLocation NameLoc) { 236 // Lookup in the parent class template context, if any. 237 const CXXRecordDecl *RD = nullptr; 238 UnqualifiedTypeNameLookupResult FoundTypeDecl = 239 UnqualifiedTypeNameLookupResult::NotFound; 240 for (DeclContext *DC = S.CurContext; 241 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; 242 DC = DC->getParent()) { 243 // Look for type decls in dependent base classes that have known primary 244 // templates. 245 RD = dyn_cast<CXXRecordDecl>(DC); 246 if (RD && RD->getDescribedClassTemplate()) 247 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); 248 } 249 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) 250 return nullptr; 251 252 // We found some types in dependent base classes. Recover as if the user 253 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the 254 // lookup during template instantiation. 255 S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II; 256 257 ASTContext &Context = S.Context; 258 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, 259 cast<Type>(Context.getRecordType(RD))); 260 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); 261 262 CXXScopeSpec SS; 263 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 264 265 TypeLocBuilder Builder; 266 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 267 DepTL.setNameLoc(NameLoc); 268 DepTL.setElaboratedKeywordLoc(SourceLocation()); 269 DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); 270 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 271 } 272 273 /// If the identifier refers to a type name within this scope, 274 /// return the declaration of that type. 275 /// 276 /// This routine performs ordinary name lookup of the identifier II 277 /// within the given scope, with optional C++ scope specifier SS, to 278 /// determine whether the name refers to a type. If so, returns an 279 /// opaque pointer (actually a QualType) corresponding to that 280 /// type. Otherwise, returns NULL. 281 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 282 Scope *S, CXXScopeSpec *SS, 283 bool isClassName, bool HasTrailingDot, 284 ParsedType ObjectTypePtr, 285 bool IsCtorOrDtorName, 286 bool WantNontrivialTypeSourceInfo, 287 bool IsClassTemplateDeductionContext, 288 IdentifierInfo **CorrectedII) { 289 // FIXME: Consider allowing this outside C++1z mode as an extension. 290 bool AllowDeducedTemplate = IsClassTemplateDeductionContext && 291 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName && 292 !isClassName && !HasTrailingDot; 293 294 // Determine where we will perform name lookup. 295 DeclContext *LookupCtx = nullptr; 296 if (ObjectTypePtr) { 297 QualType ObjectType = ObjectTypePtr.get(); 298 if (ObjectType->isRecordType()) 299 LookupCtx = computeDeclContext(ObjectType); 300 } else if (SS && SS->isNotEmpty()) { 301 LookupCtx = computeDeclContext(*SS, false); 302 303 if (!LookupCtx) { 304 if (isDependentScopeSpecifier(*SS)) { 305 // C++ [temp.res]p3: 306 // A qualified-id that refers to a type and in which the 307 // nested-name-specifier depends on a template-parameter (14.6.2) 308 // shall be prefixed by the keyword typename to indicate that the 309 // qualified-id denotes a type, forming an 310 // elaborated-type-specifier (7.1.5.3). 311 // 312 // We therefore do not perform any name lookup if the result would 313 // refer to a member of an unknown specialization. 314 if (!isClassName && !IsCtorOrDtorName) 315 return nullptr; 316 317 // We know from the grammar that this name refers to a type, 318 // so build a dependent node to describe the type. 319 if (WantNontrivialTypeSourceInfo) 320 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 321 322 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 323 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 324 II, NameLoc); 325 return ParsedType::make(T); 326 } 327 328 return nullptr; 329 } 330 331 if (!LookupCtx->isDependentContext() && 332 RequireCompleteDeclContext(*SS, LookupCtx)) 333 return nullptr; 334 } 335 336 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 337 // lookup for class-names. 338 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 339 LookupOrdinaryName; 340 LookupResult Result(*this, &II, NameLoc, Kind); 341 if (LookupCtx) { 342 // Perform "qualified" name lookup into the declaration context we 343 // computed, which is either the type of the base of a member access 344 // expression or the declaration context associated with a prior 345 // nested-name-specifier. 346 LookupQualifiedName(Result, LookupCtx); 347 348 if (ObjectTypePtr && Result.empty()) { 349 // C++ [basic.lookup.classref]p3: 350 // If the unqualified-id is ~type-name, the type-name is looked up 351 // in the context of the entire postfix-expression. If the type T of 352 // the object expression is of a class type C, the type-name is also 353 // looked up in the scope of class C. At least one of the lookups shall 354 // find a name that refers to (possibly cv-qualified) T. 355 LookupName(Result, S); 356 } 357 } else { 358 // Perform unqualified name lookup. 359 LookupName(Result, S); 360 361 // For unqualified lookup in a class template in MSVC mode, look into 362 // dependent base classes where the primary class template is known. 363 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { 364 if (ParsedType TypeInBase = 365 recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) 366 return TypeInBase; 367 } 368 } 369 370 NamedDecl *IIDecl = nullptr; 371 switch (Result.getResultKind()) { 372 case LookupResult::NotFound: 373 case LookupResult::NotFoundInCurrentInstantiation: 374 if (CorrectedII) { 375 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName, 376 AllowDeducedTemplate); 377 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind, 378 S, SS, CCC, CTK_ErrorRecovery); 379 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 380 TemplateTy Template; 381 bool MemberOfUnknownSpecialization; 382 UnqualifiedId TemplateName; 383 TemplateName.setIdentifier(NewII, NameLoc); 384 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 385 CXXScopeSpec NewSS, *NewSSPtr = SS; 386 if (SS && NNS) { 387 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 388 NewSSPtr = &NewSS; 389 } 390 if (Correction && (NNS || NewII != &II) && 391 // Ignore a correction to a template type as the to-be-corrected 392 // identifier is not a template (typo correction for template names 393 // is handled elsewhere). 394 !(getLangOpts().CPlusPlus && NewSSPtr && 395 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false, 396 Template, MemberOfUnknownSpecialization))) { 397 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 398 isClassName, HasTrailingDot, ObjectTypePtr, 399 IsCtorOrDtorName, 400 WantNontrivialTypeSourceInfo, 401 IsClassTemplateDeductionContext); 402 if (Ty) { 403 diagnoseTypo(Correction, 404 PDiag(diag::err_unknown_type_or_class_name_suggest) 405 << Result.getLookupName() << isClassName); 406 if (SS && NNS) 407 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 408 *CorrectedII = NewII; 409 return Ty; 410 } 411 } 412 } 413 // If typo correction failed or was not performed, fall through 414 LLVM_FALLTHROUGH; 415 case LookupResult::FoundOverloaded: 416 case LookupResult::FoundUnresolvedValue: 417 Result.suppressDiagnostics(); 418 return nullptr; 419 420 case LookupResult::Ambiguous: 421 // Recover from type-hiding ambiguities by hiding the type. We'll 422 // do the lookup again when looking for an object, and we can 423 // diagnose the error then. If we don't do this, then the error 424 // about hiding the type will be immediately followed by an error 425 // that only makes sense if the identifier was treated like a type. 426 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 427 Result.suppressDiagnostics(); 428 return nullptr; 429 } 430 431 // Look to see if we have a type anywhere in the list of results. 432 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 433 Res != ResEnd; ++Res) { 434 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) || 435 (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) { 436 if (!IIDecl || 437 (*Res)->getLocation().getRawEncoding() < 438 IIDecl->getLocation().getRawEncoding()) 439 IIDecl = *Res; 440 } 441 } 442 443 if (!IIDecl) { 444 // None of the entities we found is a type, so there is no way 445 // to even assume that the result is a type. In this case, don't 446 // complain about the ambiguity. The parser will either try to 447 // perform this lookup again (e.g., as an object name), which 448 // will produce the ambiguity, or will complain that it expected 449 // a type name. 450 Result.suppressDiagnostics(); 451 return nullptr; 452 } 453 454 // We found a type within the ambiguous lookup; diagnose the 455 // ambiguity and then return that type. This might be the right 456 // answer, or it might not be, but it suppresses any attempt to 457 // perform the name lookup again. 458 break; 459 460 case LookupResult::Found: 461 IIDecl = Result.getFoundDecl(); 462 break; 463 } 464 465 assert(IIDecl && "Didn't find decl"); 466 467 QualType T; 468 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 469 // C++ [class.qual]p2: A lookup that would find the injected-class-name 470 // instead names the constructors of the class, except when naming a class. 471 // This is ill-formed when we're not actually forming a ctor or dtor name. 472 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); 473 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD); 474 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD && 475 FoundRD->isInjectedClassName() && 476 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) 477 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor) 478 << &II << /*Type*/1; 479 480 DiagnoseUseOfDecl(IIDecl, NameLoc); 481 482 T = Context.getTypeDeclType(TD); 483 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); 484 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 485 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 486 if (!HasTrailingDot) 487 T = Context.getObjCInterfaceType(IDecl); 488 } else if (AllowDeducedTemplate) { 489 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) 490 T = Context.getDeducedTemplateSpecializationType(TemplateName(TD), 491 QualType(), false); 492 } 493 494 if (T.isNull()) { 495 // If it's not plausibly a type, suppress diagnostics. 496 Result.suppressDiagnostics(); 497 return nullptr; 498 } 499 500 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 501 // constructor or destructor name (in such a case, the scope specifier 502 // will be attached to the enclosing Expr or Decl node). 503 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName && 504 !isa<ObjCInterfaceDecl>(IIDecl)) { 505 if (WantNontrivialTypeSourceInfo) { 506 // Construct a type with type-source information. 507 TypeLocBuilder Builder; 508 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 509 510 T = getElaboratedType(ETK_None, *SS, T); 511 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 512 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 513 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 514 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 515 } else { 516 T = getElaboratedType(ETK_None, *SS, T); 517 } 518 } 519 520 return ParsedType::make(T); 521 } 522 523 // Builds a fake NNS for the given decl context. 524 static NestedNameSpecifier * 525 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { 526 for (;; DC = DC->getLookupParent()) { 527 DC = DC->getPrimaryContext(); 528 auto *ND = dyn_cast<NamespaceDecl>(DC); 529 if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) 530 return NestedNameSpecifier::Create(Context, nullptr, ND); 531 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) 532 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 533 RD->getTypeForDecl()); 534 else if (isa<TranslationUnitDecl>(DC)) 535 return NestedNameSpecifier::GlobalSpecifier(Context); 536 } 537 llvm_unreachable("something isn't in TU scope?"); 538 } 539 540 /// Find the parent class with dependent bases of the innermost enclosing method 541 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end 542 /// up allowing unqualified dependent type names at class-level, which MSVC 543 /// correctly rejects. 544 static const CXXRecordDecl * 545 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) { 546 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) { 547 DC = DC->getPrimaryContext(); 548 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 549 if (MD->getParent()->hasAnyDependentBases()) 550 return MD->getParent(); 551 } 552 return nullptr; 553 } 554 555 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II, 556 SourceLocation NameLoc, 557 bool IsTemplateTypeArg) { 558 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode"); 559 560 NestedNameSpecifier *NNS = nullptr; 561 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) { 562 // If we weren't able to parse a default template argument, delay lookup 563 // until instantiation time by making a non-dependent DependentTypeName. We 564 // pretend we saw a NestedNameSpecifier referring to the current scope, and 565 // lookup is retried. 566 // FIXME: This hurts our diagnostic quality, since we get errors like "no 567 // type named 'Foo' in 'current_namespace'" when the user didn't write any 568 // name specifiers. 569 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext); 570 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; 571 } else if (const CXXRecordDecl *RD = 572 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) { 573 // Build a DependentNameType that will perform lookup into RD at 574 // instantiation time. 575 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 576 RD->getTypeForDecl()); 577 578 // Diagnose that this identifier was undeclared, and retry the lookup during 579 // template instantiation. 580 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II 581 << RD; 582 } else { 583 // This is not a situation that we should recover from. 584 return ParsedType(); 585 } 586 587 QualType T = Context.getDependentNameType(ETK_None, NNS, &II); 588 589 // Build type location information. We synthesized the qualifier, so we have 590 // to build a fake NestedNameSpecifierLoc. 591 NestedNameSpecifierLocBuilder NNSLocBuilder; 592 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 593 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); 594 595 TypeLocBuilder Builder; 596 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 597 DepTL.setNameLoc(NameLoc); 598 DepTL.setElaboratedKeywordLoc(SourceLocation()); 599 DepTL.setQualifierLoc(QualifierLoc); 600 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 601 } 602 603 /// isTagName() - This method is called *for error recovery purposes only* 604 /// to determine if the specified name is a valid tag name ("struct foo"). If 605 /// so, this returns the TST for the tag corresponding to it (TST_enum, 606 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 607 /// cases in C where the user forgot to specify the tag. 608 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 609 // Do a tag name lookup in this scope. 610 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 611 LookupName(R, S, false); 612 R.suppressDiagnostics(); 613 if (R.getResultKind() == LookupResult::Found) 614 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 615 switch (TD->getTagKind()) { 616 case TTK_Struct: return DeclSpec::TST_struct; 617 case TTK_Interface: return DeclSpec::TST_interface; 618 case TTK_Union: return DeclSpec::TST_union; 619 case TTK_Class: return DeclSpec::TST_class; 620 case TTK_Enum: return DeclSpec::TST_enum; 621 } 622 } 623 624 return DeclSpec::TST_unspecified; 625 } 626 627 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 628 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 629 /// then downgrade the missing typename error to a warning. 630 /// This is needed for MSVC compatibility; Example: 631 /// @code 632 /// template<class T> class A { 633 /// public: 634 /// typedef int TYPE; 635 /// }; 636 /// template<class T> class B : public A<T> { 637 /// public: 638 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 639 /// }; 640 /// @endcode 641 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 642 if (CurContext->isRecord()) { 643 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) 644 return true; 645 646 const Type *Ty = SS->getScopeRep()->getAsType(); 647 648 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 649 for (const auto &Base : RD->bases()) 650 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 651 return true; 652 return S->isFunctionPrototypeScope(); 653 } 654 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 655 } 656 657 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 658 SourceLocation IILoc, 659 Scope *S, 660 CXXScopeSpec *SS, 661 ParsedType &SuggestedType, 662 bool IsTemplateName) { 663 // Don't report typename errors for editor placeholders. 664 if (II->isEditorPlaceholder()) 665 return; 666 // We don't have anything to suggest (yet). 667 SuggestedType = nullptr; 668 669 // There may have been a typo in the name of the type. Look up typo 670 // results, in case we have something that we can suggest. 671 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false, 672 /*AllowTemplates=*/IsTemplateName, 673 /*AllowNonTemplates=*/!IsTemplateName); 674 if (TypoCorrection Corrected = 675 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, 676 CCC, CTK_ErrorRecovery)) { 677 // FIXME: Support error recovery for the template-name case. 678 bool CanRecover = !IsTemplateName; 679 if (Corrected.isKeyword()) { 680 // We corrected to a keyword. 681 diagnoseTypo(Corrected, 682 PDiag(IsTemplateName ? diag::err_no_template_suggest 683 : diag::err_unknown_typename_suggest) 684 << II); 685 II = Corrected.getCorrectionAsIdentifierInfo(); 686 } else { 687 // We found a similarly-named type or interface; suggest that. 688 if (!SS || !SS->isSet()) { 689 diagnoseTypo(Corrected, 690 PDiag(IsTemplateName ? diag::err_no_template_suggest 691 : diag::err_unknown_typename_suggest) 692 << II, CanRecover); 693 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 694 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 695 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 696 II->getName().equals(CorrectedStr); 697 diagnoseTypo(Corrected, 698 PDiag(IsTemplateName 699 ? diag::err_no_member_template_suggest 700 : diag::err_unknown_nested_typename_suggest) 701 << II << DC << DroppedSpecifier << SS->getRange(), 702 CanRecover); 703 } else { 704 llvm_unreachable("could not have corrected a typo here"); 705 } 706 707 if (!CanRecover) 708 return; 709 710 CXXScopeSpec tmpSS; 711 if (Corrected.getCorrectionSpecifier()) 712 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 713 SourceRange(IILoc)); 714 // FIXME: Support class template argument deduction here. 715 SuggestedType = 716 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S, 717 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr, 718 /*IsCtorOrDtorName=*/false, 719 /*WantNontrivialTypeSourceInfo=*/true); 720 } 721 return; 722 } 723 724 if (getLangOpts().CPlusPlus && !IsTemplateName) { 725 // See if II is a class template that the user forgot to pass arguments to. 726 UnqualifiedId Name; 727 Name.setIdentifier(II, IILoc); 728 CXXScopeSpec EmptySS; 729 TemplateTy TemplateResult; 730 bool MemberOfUnknownSpecialization; 731 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 732 Name, nullptr, true, TemplateResult, 733 MemberOfUnknownSpecialization) == TNK_Type_template) { 734 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc); 735 return; 736 } 737 } 738 739 // FIXME: Should we move the logic that tries to recover from a missing tag 740 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 741 742 if (!SS || (!SS->isSet() && !SS->isInvalid())) 743 Diag(IILoc, IsTemplateName ? diag::err_no_template 744 : diag::err_unknown_typename) 745 << II; 746 else if (DeclContext *DC = computeDeclContext(*SS, false)) 747 Diag(IILoc, IsTemplateName ? diag::err_no_member_template 748 : diag::err_typename_nested_not_found) 749 << II << DC << SS->getRange(); 750 else if (isDependentScopeSpecifier(*SS)) { 751 unsigned DiagID = diag::err_typename_missing; 752 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 753 DiagID = diag::ext_typename_missing; 754 755 Diag(SS->getRange().getBegin(), DiagID) 756 << SS->getScopeRep() << II->getName() 757 << SourceRange(SS->getRange().getBegin(), IILoc) 758 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 759 SuggestedType = ActOnTypenameType(S, SourceLocation(), 760 *SS, *II, IILoc).get(); 761 } else { 762 assert(SS && SS->isInvalid() && 763 "Invalid scope specifier has already been diagnosed"); 764 } 765 } 766 767 /// Determine whether the given result set contains either a type name 768 /// or 769 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 770 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 771 NextToken.is(tok::less); 772 773 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 774 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 775 return true; 776 777 if (CheckTemplate && isa<TemplateDecl>(*I)) 778 return true; 779 } 780 781 return false; 782 } 783 784 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 785 Scope *S, CXXScopeSpec &SS, 786 IdentifierInfo *&Name, 787 SourceLocation NameLoc) { 788 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 789 SemaRef.LookupParsedName(R, S, &SS); 790 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 791 StringRef FixItTagName; 792 switch (Tag->getTagKind()) { 793 case TTK_Class: 794 FixItTagName = "class "; 795 break; 796 797 case TTK_Enum: 798 FixItTagName = "enum "; 799 break; 800 801 case TTK_Struct: 802 FixItTagName = "struct "; 803 break; 804 805 case TTK_Interface: 806 FixItTagName = "__interface "; 807 break; 808 809 case TTK_Union: 810 FixItTagName = "union "; 811 break; 812 } 813 814 StringRef TagName = FixItTagName.drop_back(); 815 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 816 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 817 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 818 819 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 820 I != IEnd; ++I) 821 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 822 << Name << TagName; 823 824 // Replace lookup results with just the tag decl. 825 Result.clear(Sema::LookupTagName); 826 SemaRef.LookupParsedName(Result, S, &SS); 827 return true; 828 } 829 830 return false; 831 } 832 833 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 834 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 835 QualType T, SourceLocation NameLoc) { 836 ASTContext &Context = S.Context; 837 838 TypeLocBuilder Builder; 839 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 840 841 T = S.getElaboratedType(ETK_None, SS, T); 842 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 843 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 844 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 845 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 846 } 847 848 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, 849 IdentifierInfo *&Name, 850 SourceLocation NameLoc, 851 const Token &NextToken, 852 CorrectionCandidateCallback *CCC) { 853 DeclarationNameInfo NameInfo(Name, NameLoc); 854 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 855 856 assert(NextToken.isNot(tok::coloncolon) && 857 "parse nested name specifiers before calling ClassifyName"); 858 if (getLangOpts().CPlusPlus && SS.isSet() && 859 isCurrentClassName(*Name, S, &SS)) { 860 // Per [class.qual]p2, this names the constructors of SS, not the 861 // injected-class-name. We don't have a classification for that. 862 // There's not much point caching this result, since the parser 863 // will reject it later. 864 return NameClassification::Unknown(); 865 } 866 867 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 868 LookupParsedName(Result, S, &SS, !CurMethod); 869 870 if (SS.isInvalid()) 871 return NameClassification::Error(); 872 873 // For unqualified lookup in a class template in MSVC mode, look into 874 // dependent base classes where the primary class template is known. 875 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { 876 if (ParsedType TypeInBase = 877 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) 878 return TypeInBase; 879 } 880 881 // Perform lookup for Objective-C instance variables (including automatically 882 // synthesized instance variables), if we're in an Objective-C method. 883 // FIXME: This lookup really, really needs to be folded in to the normal 884 // unqualified lookup mechanism. 885 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 886 DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name); 887 if (Ivar.isInvalid()) 888 return NameClassification::Error(); 889 if (Ivar.isUsable()) 890 return NameClassification::NonType(cast<NamedDecl>(Ivar.get())); 891 892 // We defer builtin creation until after ivar lookup inside ObjC methods. 893 if (Result.empty()) 894 LookupBuiltin(Result); 895 } 896 897 bool SecondTry = false; 898 bool IsFilteredTemplateName = false; 899 900 Corrected: 901 switch (Result.getResultKind()) { 902 case LookupResult::NotFound: 903 // If an unqualified-id is followed by a '(', then we have a function 904 // call. 905 if (SS.isEmpty() && NextToken.is(tok::l_paren)) { 906 // In C++, this is an ADL-only call. 907 // FIXME: Reference? 908 if (getLangOpts().CPlusPlus) 909 return NameClassification::UndeclaredNonType(); 910 911 // C90 6.3.2.2: 912 // If the expression that precedes the parenthesized argument list in a 913 // function call consists solely of an identifier, and if no 914 // declaration is visible for this identifier, the identifier is 915 // implicitly declared exactly as if, in the innermost block containing 916 // the function call, the declaration 917 // 918 // extern int identifier (); 919 // 920 // appeared. 921 // 922 // We also allow this in C99 as an extension. 923 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) 924 return NameClassification::NonType(D); 925 } 926 927 if (getLangOpts().CPlusPlus2a && SS.isEmpty() && NextToken.is(tok::less)) { 928 // In C++20 onwards, this could be an ADL-only call to a function 929 // template, and we're required to assume that this is a template name. 930 // 931 // FIXME: Find a way to still do typo correction in this case. 932 TemplateName Template = 933 Context.getAssumedTemplateName(NameInfo.getName()); 934 return NameClassification::UndeclaredTemplate(Template); 935 } 936 937 // In C, we first see whether there is a tag type by the same name, in 938 // which case it's likely that the user just forgot to write "enum", 939 // "struct", or "union". 940 if (!getLangOpts().CPlusPlus && !SecondTry && 941 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 942 break; 943 } 944 945 // Perform typo correction to determine if there is another name that is 946 // close to this name. 947 if (!SecondTry && CCC) { 948 SecondTry = true; 949 if (TypoCorrection Corrected = 950 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S, 951 &SS, *CCC, CTK_ErrorRecovery)) { 952 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 953 unsigned QualifiedDiag = diag::err_no_member_suggest; 954 955 NamedDecl *FirstDecl = Corrected.getFoundDecl(); 956 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); 957 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 958 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 959 UnqualifiedDiag = diag::err_no_template_suggest; 960 QualifiedDiag = diag::err_no_member_template_suggest; 961 } else if (UnderlyingFirstDecl && 962 (isa<TypeDecl>(UnderlyingFirstDecl) || 963 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 964 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 965 UnqualifiedDiag = diag::err_unknown_typename_suggest; 966 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 967 } 968 969 if (SS.isEmpty()) { 970 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 971 } else {// FIXME: is this even reachable? Test it. 972 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 973 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 974 Name->getName().equals(CorrectedStr); 975 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 976 << Name << computeDeclContext(SS, false) 977 << DroppedSpecifier << SS.getRange()); 978 } 979 980 // Update the name, so that the caller has the new name. 981 Name = Corrected.getCorrectionAsIdentifierInfo(); 982 983 // Typo correction corrected to a keyword. 984 if (Corrected.isKeyword()) 985 return Name; 986 987 // Also update the LookupResult... 988 // FIXME: This should probably go away at some point 989 Result.clear(); 990 Result.setLookupName(Corrected.getCorrection()); 991 if (FirstDecl) 992 Result.addDecl(FirstDecl); 993 994 // If we found an Objective-C instance variable, let 995 // LookupInObjCMethod build the appropriate expression to 996 // reference the ivar. 997 // FIXME: This is a gross hack. 998 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 999 DeclResult R = 1000 LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier()); 1001 if (R.isInvalid()) 1002 return NameClassification::Error(); 1003 if (R.isUsable()) 1004 return NameClassification::NonType(Ivar); 1005 } 1006 1007 goto Corrected; 1008 } 1009 } 1010 1011 // We failed to correct; just fall through and let the parser deal with it. 1012 Result.suppressDiagnostics(); 1013 return NameClassification::Unknown(); 1014 1015 case LookupResult::NotFoundInCurrentInstantiation: { 1016 // We performed name lookup into the current instantiation, and there were 1017 // dependent bases, so we treat this result the same way as any other 1018 // dependent nested-name-specifier. 1019 1020 // C++ [temp.res]p2: 1021 // A name used in a template declaration or definition and that is 1022 // dependent on a template-parameter is assumed not to name a type 1023 // unless the applicable name lookup finds a type name or the name is 1024 // qualified by the keyword typename. 1025 // 1026 // FIXME: If the next token is '<', we might want to ask the parser to 1027 // perform some heroics to see if we actually have a 1028 // template-argument-list, which would indicate a missing 'template' 1029 // keyword here. 1030 return NameClassification::DependentNonType(); 1031 } 1032 1033 case LookupResult::Found: 1034 case LookupResult::FoundOverloaded: 1035 case LookupResult::FoundUnresolvedValue: 1036 break; 1037 1038 case LookupResult::Ambiguous: 1039 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1040 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true, 1041 /*AllowDependent=*/false)) { 1042 // C++ [temp.local]p3: 1043 // A lookup that finds an injected-class-name (10.2) can result in an 1044 // ambiguity in certain cases (for example, if it is found in more than 1045 // one base class). If all of the injected-class-names that are found 1046 // refer to specializations of the same class template, and if the name 1047 // is followed by a template-argument-list, the reference refers to the 1048 // class template itself and not a specialization thereof, and is not 1049 // ambiguous. 1050 // 1051 // This filtering can make an ambiguous result into an unambiguous one, 1052 // so try again after filtering out template names. 1053 FilterAcceptableTemplateNames(Result); 1054 if (!Result.isAmbiguous()) { 1055 IsFilteredTemplateName = true; 1056 break; 1057 } 1058 } 1059 1060 // Diagnose the ambiguity and return an error. 1061 return NameClassification::Error(); 1062 } 1063 1064 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1065 (IsFilteredTemplateName || 1066 hasAnyAcceptableTemplateNames( 1067 Result, /*AllowFunctionTemplates=*/true, 1068 /*AllowDependent=*/false, 1069 /*AllowNonTemplateFunctions*/ SS.isEmpty() && 1070 getLangOpts().CPlusPlus2a))) { 1071 // C++ [temp.names]p3: 1072 // After name lookup (3.4) finds that a name is a template-name or that 1073 // an operator-function-id or a literal- operator-id refers to a set of 1074 // overloaded functions any member of which is a function template if 1075 // this is followed by a <, the < is always taken as the delimiter of a 1076 // template-argument-list and never as the less-than operator. 1077 // C++2a [temp.names]p2: 1078 // A name is also considered to refer to a template if it is an 1079 // unqualified-id followed by a < and name lookup finds either one 1080 // or more functions or finds nothing. 1081 if (!IsFilteredTemplateName) 1082 FilterAcceptableTemplateNames(Result); 1083 1084 bool IsFunctionTemplate; 1085 bool IsVarTemplate; 1086 TemplateName Template; 1087 if (Result.end() - Result.begin() > 1) { 1088 IsFunctionTemplate = true; 1089 Template = Context.getOverloadedTemplateName(Result.begin(), 1090 Result.end()); 1091 } else if (!Result.empty()) { 1092 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl( 1093 *Result.begin(), /*AllowFunctionTemplates=*/true, 1094 /*AllowDependent=*/false)); 1095 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 1096 IsVarTemplate = isa<VarTemplateDecl>(TD); 1097 1098 if (SS.isNotEmpty()) 1099 Template = 1100 Context.getQualifiedTemplateName(SS.getScopeRep(), 1101 /*TemplateKeyword=*/false, TD); 1102 else 1103 Template = TemplateName(TD); 1104 } else { 1105 // All results were non-template functions. This is a function template 1106 // name. 1107 IsFunctionTemplate = true; 1108 Template = Context.getAssumedTemplateName(NameInfo.getName()); 1109 } 1110 1111 if (IsFunctionTemplate) { 1112 // Function templates always go through overload resolution, at which 1113 // point we'll perform the various checks (e.g., accessibility) we need 1114 // to based on which function we selected. 1115 Result.suppressDiagnostics(); 1116 1117 return NameClassification::FunctionTemplate(Template); 1118 } 1119 1120 return IsVarTemplate ? NameClassification::VarTemplate(Template) 1121 : NameClassification::TypeTemplate(Template); 1122 } 1123 1124 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 1125 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 1126 DiagnoseUseOfDecl(Type, NameLoc); 1127 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 1128 QualType T = Context.getTypeDeclType(Type); 1129 if (SS.isNotEmpty()) 1130 return buildNestedType(*this, SS, T, NameLoc); 1131 return ParsedType::make(T); 1132 } 1133 1134 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 1135 if (!Class) { 1136 // FIXME: It's unfortunate that we don't have a Type node for handling this. 1137 if (ObjCCompatibleAliasDecl *Alias = 1138 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 1139 Class = Alias->getClassInterface(); 1140 } 1141 1142 if (Class) { 1143 DiagnoseUseOfDecl(Class, NameLoc); 1144 1145 if (NextToken.is(tok::period)) { 1146 // Interface. <something> is parsed as a property reference expression. 1147 // Just return "unknown" as a fall-through for now. 1148 Result.suppressDiagnostics(); 1149 return NameClassification::Unknown(); 1150 } 1151 1152 QualType T = Context.getObjCInterfaceType(Class); 1153 return ParsedType::make(T); 1154 } 1155 1156 if (isa<ConceptDecl>(FirstDecl)) 1157 return NameClassification::Concept( 1158 TemplateName(cast<TemplateDecl>(FirstDecl))); 1159 1160 // We can have a type template here if we're classifying a template argument. 1161 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) && 1162 !isa<VarTemplateDecl>(FirstDecl)) 1163 return NameClassification::TypeTemplate( 1164 TemplateName(cast<TemplateDecl>(FirstDecl))); 1165 1166 // Check for a tag type hidden by a non-type decl in a few cases where it 1167 // seems likely a type is wanted instead of the non-type that was found. 1168 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); 1169 if ((NextToken.is(tok::identifier) || 1170 (NextIsOp && 1171 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 1172 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 1173 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 1174 DiagnoseUseOfDecl(Type, NameLoc); 1175 QualType T = Context.getTypeDeclType(Type); 1176 if (SS.isNotEmpty()) 1177 return buildNestedType(*this, SS, T, NameLoc); 1178 return ParsedType::make(T); 1179 } 1180 1181 // FIXME: This is context-dependent. We need to defer building the member 1182 // expression until the classification is consumed. 1183 if (FirstDecl->isCXXClassMember()) 1184 return NameClassification::ContextIndependentExpr( 1185 BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, nullptr, 1186 S)); 1187 1188 // If we already know which single declaration is referenced, just annotate 1189 // that declaration directly. 1190 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1191 if (Result.isSingleResult() && !ADL) 1192 return NameClassification::NonType(Result.getRepresentativeDecl()); 1193 1194 // Build an UnresolvedLookupExpr. Note that this doesn't depend on the 1195 // context in which we performed classification, so it's safe to do now. 1196 return NameClassification::ContextIndependentExpr( 1197 BuildDeclarationNameExpr(SS, Result, ADL)); 1198 } 1199 1200 ExprResult 1201 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, 1202 SourceLocation NameLoc) { 1203 assert(getLangOpts().CPlusPlus && "ADL-only call in C?"); 1204 CXXScopeSpec SS; 1205 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 1206 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 1207 } 1208 1209 ExprResult 1210 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, 1211 IdentifierInfo *Name, 1212 SourceLocation NameLoc, 1213 bool IsAddressOfOperand) { 1214 DeclarationNameInfo NameInfo(Name, NameLoc); 1215 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 1216 NameInfo, IsAddressOfOperand, 1217 /*TemplateArgs=*/nullptr); 1218 } 1219 1220 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, 1221 NamedDecl *Found, 1222 SourceLocation NameLoc, 1223 const Token &NextToken) { 1224 if (getCurMethodDecl() && SS.isEmpty()) 1225 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl())) 1226 return BuildIvarRefExpr(S, NameLoc, Ivar); 1227 1228 // Reconstruct the lookup result. 1229 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName); 1230 Result.addDecl(Found); 1231 Result.resolveKind(); 1232 1233 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1234 return BuildDeclarationNameExpr(SS, Result, ADL); 1235 } 1236 1237 Sema::TemplateNameKindForDiagnostics 1238 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) { 1239 auto *TD = Name.getAsTemplateDecl(); 1240 if (!TD) 1241 return TemplateNameKindForDiagnostics::DependentTemplate; 1242 if (isa<ClassTemplateDecl>(TD)) 1243 return TemplateNameKindForDiagnostics::ClassTemplate; 1244 if (isa<FunctionTemplateDecl>(TD)) 1245 return TemplateNameKindForDiagnostics::FunctionTemplate; 1246 if (isa<VarTemplateDecl>(TD)) 1247 return TemplateNameKindForDiagnostics::VarTemplate; 1248 if (isa<TypeAliasTemplateDecl>(TD)) 1249 return TemplateNameKindForDiagnostics::AliasTemplate; 1250 if (isa<TemplateTemplateParmDecl>(TD)) 1251 return TemplateNameKindForDiagnostics::TemplateTemplateParam; 1252 if (isa<ConceptDecl>(TD)) 1253 return TemplateNameKindForDiagnostics::Concept; 1254 return TemplateNameKindForDiagnostics::DependentTemplate; 1255 } 1256 1257 // Determines the context to return to after temporarily entering a 1258 // context. This depends in an unnecessarily complicated way on the 1259 // exact ordering of callbacks from the parser. 1260 DeclContext *Sema::getContainingDC(DeclContext *DC) { 1261 1262 // Functions defined inline within classes aren't parsed until we've 1263 // finished parsing the top-level class, so the top-level class is 1264 // the context we'll need to return to. 1265 // A Lambda call operator whose parent is a class must not be treated 1266 // as an inline member function. A Lambda can be used legally 1267 // either as an in-class member initializer or a default argument. These 1268 // are parsed once the class has been marked complete and so the containing 1269 // context would be the nested class (when the lambda is defined in one); 1270 // If the class is not complete, then the lambda is being used in an 1271 // ill-formed fashion (such as to specify the width of a bit-field, or 1272 // in an array-bound) - in which case we still want to return the 1273 // lexically containing DC (which could be a nested class). 1274 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) { 1275 DC = DC->getLexicalParent(); 1276 1277 // A function not defined within a class will always return to its 1278 // lexical context. 1279 if (!isa<CXXRecordDecl>(DC)) 1280 return DC; 1281 1282 // A C++ inline method/friend is parsed *after* the topmost class 1283 // it was declared in is fully parsed ("complete"); the topmost 1284 // class is the context we need to return to. 1285 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 1286 DC = RD; 1287 1288 // Return the declaration context of the topmost class the inline method is 1289 // declared in. 1290 return DC; 1291 } 1292 1293 return DC->getLexicalParent(); 1294 } 1295 1296 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 1297 assert(getContainingDC(DC) == CurContext && 1298 "The next DeclContext should be lexically contained in the current one."); 1299 CurContext = DC; 1300 S->setEntity(DC); 1301 } 1302 1303 void Sema::PopDeclContext() { 1304 assert(CurContext && "DeclContext imbalance!"); 1305 1306 CurContext = getContainingDC(CurContext); 1307 assert(CurContext && "Popped translation unit!"); 1308 } 1309 1310 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, 1311 Decl *D) { 1312 // Unlike PushDeclContext, the context to which we return is not necessarily 1313 // the containing DC of TD, because the new context will be some pre-existing 1314 // TagDecl definition instead of a fresh one. 1315 auto Result = static_cast<SkippedDefinitionContext>(CurContext); 1316 CurContext = cast<TagDecl>(D)->getDefinition(); 1317 assert(CurContext && "skipping definition of undefined tag"); 1318 // Start lookups from the parent of the current context; we don't want to look 1319 // into the pre-existing complete definition. 1320 S->setEntity(CurContext->getLookupParent()); 1321 return Result; 1322 } 1323 1324 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { 1325 CurContext = static_cast<decltype(CurContext)>(Context); 1326 } 1327 1328 /// EnterDeclaratorContext - Used when we must lookup names in the context 1329 /// of a declarator's nested name specifier. 1330 /// 1331 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1332 // C++0x [basic.lookup.unqual]p13: 1333 // A name used in the definition of a static data member of class 1334 // X (after the qualified-id of the static member) is looked up as 1335 // if the name was used in a member function of X. 1336 // C++0x [basic.lookup.unqual]p14: 1337 // If a variable member of a namespace is defined outside of the 1338 // scope of its namespace then any name used in the definition of 1339 // the variable member (after the declarator-id) is looked up as 1340 // if the definition of the variable member occurred in its 1341 // namespace. 1342 // Both of these imply that we should push a scope whose context 1343 // is the semantic context of the declaration. We can't use 1344 // PushDeclContext here because that context is not necessarily 1345 // lexically contained in the current context. Fortunately, 1346 // the containing scope should have the appropriate information. 1347 1348 assert(!S->getEntity() && "scope already has entity"); 1349 1350 #ifndef NDEBUG 1351 Scope *Ancestor = S->getParent(); 1352 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1353 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1354 #endif 1355 1356 CurContext = DC; 1357 S->setEntity(DC); 1358 } 1359 1360 void Sema::ExitDeclaratorContext(Scope *S) { 1361 assert(S->getEntity() == CurContext && "Context imbalance!"); 1362 1363 // Switch back to the lexical context. The safety of this is 1364 // enforced by an assert in EnterDeclaratorContext. 1365 Scope *Ancestor = S->getParent(); 1366 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1367 CurContext = Ancestor->getEntity(); 1368 1369 // We don't need to do anything with the scope, which is going to 1370 // disappear. 1371 } 1372 1373 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1374 // We assume that the caller has already called 1375 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1376 FunctionDecl *FD = D->getAsFunction(); 1377 if (!FD) 1378 return; 1379 1380 // Same implementation as PushDeclContext, but enters the context 1381 // from the lexical parent, rather than the top-level class. 1382 assert(CurContext == FD->getLexicalParent() && 1383 "The next DeclContext should be lexically contained in the current one."); 1384 CurContext = FD; 1385 S->setEntity(CurContext); 1386 1387 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1388 ParmVarDecl *Param = FD->getParamDecl(P); 1389 // If the parameter has an identifier, then add it to the scope 1390 if (Param->getIdentifier()) { 1391 S->AddDecl(Param); 1392 IdResolver.AddDecl(Param); 1393 } 1394 } 1395 } 1396 1397 void Sema::ActOnExitFunctionContext() { 1398 // Same implementation as PopDeclContext, but returns to the lexical parent, 1399 // rather than the top-level class. 1400 assert(CurContext && "DeclContext imbalance!"); 1401 CurContext = CurContext->getLexicalParent(); 1402 assert(CurContext && "Popped translation unit!"); 1403 } 1404 1405 /// Determine whether we allow overloading of the function 1406 /// PrevDecl with another declaration. 1407 /// 1408 /// This routine determines whether overloading is possible, not 1409 /// whether some new function is actually an overload. It will return 1410 /// true in C++ (where we can always provide overloads) or, as an 1411 /// extension, in C when the previous function is already an 1412 /// overloaded function declaration or has the "overloadable" 1413 /// attribute. 1414 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1415 ASTContext &Context, 1416 const FunctionDecl *New) { 1417 if (Context.getLangOpts().CPlusPlus) 1418 return true; 1419 1420 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1421 return true; 1422 1423 return Previous.getResultKind() == LookupResult::Found && 1424 (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() || 1425 New->hasAttr<OverloadableAttr>()); 1426 } 1427 1428 /// Add this decl to the scope shadowed decl chains. 1429 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1430 // Move up the scope chain until we find the nearest enclosing 1431 // non-transparent context. The declaration will be introduced into this 1432 // scope. 1433 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1434 S = S->getParent(); 1435 1436 // Add scoped declarations into their context, so that they can be 1437 // found later. Declarations without a context won't be inserted 1438 // into any context. 1439 if (AddToContext) 1440 CurContext->addDecl(D); 1441 1442 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1443 // are function-local declarations. 1444 if (getLangOpts().CPlusPlus && D->isOutOfLine() && 1445 !D->getDeclContext()->getRedeclContext()->Equals( 1446 D->getLexicalDeclContext()->getRedeclContext()) && 1447 !D->getLexicalDeclContext()->isFunctionOrMethod()) 1448 return; 1449 1450 // Template instantiations should also not be pushed into scope. 1451 if (isa<FunctionDecl>(D) && 1452 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1453 return; 1454 1455 // If this replaces anything in the current scope, 1456 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1457 IEnd = IdResolver.end(); 1458 for (; I != IEnd; ++I) { 1459 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1460 S->RemoveDecl(*I); 1461 IdResolver.RemoveDecl(*I); 1462 1463 // Should only need to replace one decl. 1464 break; 1465 } 1466 } 1467 1468 S->AddDecl(D); 1469 1470 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1471 // Implicitly-generated labels may end up getting generated in an order that 1472 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1473 // the label at the appropriate place in the identifier chain. 1474 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1475 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1476 if (IDC == CurContext) { 1477 if (!S->isDeclScope(*I)) 1478 continue; 1479 } else if (IDC->Encloses(CurContext)) 1480 break; 1481 } 1482 1483 IdResolver.InsertDeclAfter(I, D); 1484 } else { 1485 IdResolver.AddDecl(D); 1486 } 1487 } 1488 1489 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1490 bool AllowInlineNamespace) { 1491 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1492 } 1493 1494 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1495 DeclContext *TargetDC = DC->getPrimaryContext(); 1496 do { 1497 if (DeclContext *ScopeDC = S->getEntity()) 1498 if (ScopeDC->getPrimaryContext() == TargetDC) 1499 return S; 1500 } while ((S = S->getParent())); 1501 1502 return nullptr; 1503 } 1504 1505 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1506 DeclContext*, 1507 ASTContext&); 1508 1509 /// Filters out lookup results that don't fall within the given scope 1510 /// as determined by isDeclInScope. 1511 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1512 bool ConsiderLinkage, 1513 bool AllowInlineNamespace) { 1514 LookupResult::Filter F = R.makeFilter(); 1515 while (F.hasNext()) { 1516 NamedDecl *D = F.next(); 1517 1518 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1519 continue; 1520 1521 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1522 continue; 1523 1524 F.erase(); 1525 } 1526 1527 F.done(); 1528 } 1529 1530 /// We've determined that \p New is a redeclaration of \p Old. Check that they 1531 /// have compatible owning modules. 1532 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) { 1533 // FIXME: The Modules TS is not clear about how friend declarations are 1534 // to be treated. It's not meaningful to have different owning modules for 1535 // linkage in redeclarations of the same entity, so for now allow the 1536 // redeclaration and change the owning modules to match. 1537 if (New->getFriendObjectKind() && 1538 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) { 1539 New->setLocalOwningModule(Old->getOwningModule()); 1540 makeMergedDefinitionVisible(New); 1541 return false; 1542 } 1543 1544 Module *NewM = New->getOwningModule(); 1545 Module *OldM = Old->getOwningModule(); 1546 1547 if (NewM && NewM->Kind == Module::PrivateModuleFragment) 1548 NewM = NewM->Parent; 1549 if (OldM && OldM->Kind == Module::PrivateModuleFragment) 1550 OldM = OldM->Parent; 1551 1552 if (NewM == OldM) 1553 return false; 1554 1555 bool NewIsModuleInterface = NewM && NewM->isModulePurview(); 1556 bool OldIsModuleInterface = OldM && OldM->isModulePurview(); 1557 if (NewIsModuleInterface || OldIsModuleInterface) { 1558 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]: 1559 // if a declaration of D [...] appears in the purview of a module, all 1560 // other such declarations shall appear in the purview of the same module 1561 Diag(New->getLocation(), diag::err_mismatched_owning_module) 1562 << New 1563 << NewIsModuleInterface 1564 << (NewIsModuleInterface ? NewM->getFullModuleName() : "") 1565 << OldIsModuleInterface 1566 << (OldIsModuleInterface ? OldM->getFullModuleName() : ""); 1567 Diag(Old->getLocation(), diag::note_previous_declaration); 1568 New->setInvalidDecl(); 1569 return true; 1570 } 1571 1572 return false; 1573 } 1574 1575 static bool isUsingDecl(NamedDecl *D) { 1576 return isa<UsingShadowDecl>(D) || 1577 isa<UnresolvedUsingTypenameDecl>(D) || 1578 isa<UnresolvedUsingValueDecl>(D); 1579 } 1580 1581 /// Removes using shadow declarations from the lookup results. 1582 static void RemoveUsingDecls(LookupResult &R) { 1583 LookupResult::Filter F = R.makeFilter(); 1584 while (F.hasNext()) 1585 if (isUsingDecl(F.next())) 1586 F.erase(); 1587 1588 F.done(); 1589 } 1590 1591 /// Check for this common pattern: 1592 /// @code 1593 /// class S { 1594 /// S(const S&); // DO NOT IMPLEMENT 1595 /// void operator=(const S&); // DO NOT IMPLEMENT 1596 /// }; 1597 /// @endcode 1598 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1599 // FIXME: Should check for private access too but access is set after we get 1600 // the decl here. 1601 if (D->doesThisDeclarationHaveABody()) 1602 return false; 1603 1604 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1605 return CD->isCopyConstructor(); 1606 return D->isCopyAssignmentOperator(); 1607 } 1608 1609 // We need this to handle 1610 // 1611 // typedef struct { 1612 // void *foo() { return 0; } 1613 // } A; 1614 // 1615 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1616 // for example. If 'A', foo will have external linkage. If we have '*A', 1617 // foo will have no linkage. Since we can't know until we get to the end 1618 // of the typedef, this function finds out if D might have non-external linkage. 1619 // Callers should verify at the end of the TU if it D has external linkage or 1620 // not. 1621 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1622 const DeclContext *DC = D->getDeclContext(); 1623 while (!DC->isTranslationUnit()) { 1624 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1625 if (!RD->hasNameForLinkage()) 1626 return true; 1627 } 1628 DC = DC->getParent(); 1629 } 1630 1631 return !D->isExternallyVisible(); 1632 } 1633 1634 // FIXME: This needs to be refactored; some other isInMainFile users want 1635 // these semantics. 1636 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1637 if (S.TUKind != TU_Complete) 1638 return false; 1639 return S.SourceMgr.isInMainFile(Loc); 1640 } 1641 1642 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1643 assert(D); 1644 1645 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1646 return false; 1647 1648 // Ignore all entities declared within templates, and out-of-line definitions 1649 // of members of class templates. 1650 if (D->getDeclContext()->isDependentContext() || 1651 D->getLexicalDeclContext()->isDependentContext()) 1652 return false; 1653 1654 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1655 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1656 return false; 1657 // A non-out-of-line declaration of a member specialization was implicitly 1658 // instantiated; it's the out-of-line declaration that we're interested in. 1659 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1660 FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) 1661 return false; 1662 1663 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1664 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1665 return false; 1666 } else { 1667 // 'static inline' functions are defined in headers; don't warn. 1668 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1669 return false; 1670 } 1671 1672 if (FD->doesThisDeclarationHaveABody() && 1673 Context.DeclMustBeEmitted(FD)) 1674 return false; 1675 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1676 // Constants and utility variables are defined in headers with internal 1677 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1678 // like "inline".) 1679 if (!isMainFileLoc(*this, VD->getLocation())) 1680 return false; 1681 1682 if (Context.DeclMustBeEmitted(VD)) 1683 return false; 1684 1685 if (VD->isStaticDataMember() && 1686 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1687 return false; 1688 if (VD->isStaticDataMember() && 1689 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1690 VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) 1691 return false; 1692 1693 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) 1694 return false; 1695 } else { 1696 return false; 1697 } 1698 1699 // Only warn for unused decls internal to the translation unit. 1700 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1701 // for inline functions defined in the main source file, for instance. 1702 return mightHaveNonExternalLinkage(D); 1703 } 1704 1705 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1706 if (!D) 1707 return; 1708 1709 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1710 const FunctionDecl *First = FD->getFirstDecl(); 1711 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1712 return; // First should already be in the vector. 1713 } 1714 1715 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1716 const VarDecl *First = VD->getFirstDecl(); 1717 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1718 return; // First should already be in the vector. 1719 } 1720 1721 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1722 UnusedFileScopedDecls.push_back(D); 1723 } 1724 1725 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1726 if (D->isInvalidDecl()) 1727 return false; 1728 1729 bool Referenced = false; 1730 if (auto *DD = dyn_cast<DecompositionDecl>(D)) { 1731 // For a decomposition declaration, warn if none of the bindings are 1732 // referenced, instead of if the variable itself is referenced (which 1733 // it is, by the bindings' expressions). 1734 for (auto *BD : DD->bindings()) { 1735 if (BD->isReferenced()) { 1736 Referenced = true; 1737 break; 1738 } 1739 } 1740 } else if (!D->getDeclName()) { 1741 return false; 1742 } else if (D->isReferenced() || D->isUsed()) { 1743 Referenced = true; 1744 } 1745 1746 if (Referenced || D->hasAttr<UnusedAttr>() || 1747 D->hasAttr<ObjCPreciseLifetimeAttr>()) 1748 return false; 1749 1750 if (isa<LabelDecl>(D)) 1751 return true; 1752 1753 // Except for labels, we only care about unused decls that are local to 1754 // functions. 1755 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1756 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1757 // For dependent types, the diagnostic is deferred. 1758 WithinFunction = 1759 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1760 if (!WithinFunction) 1761 return false; 1762 1763 if (isa<TypedefNameDecl>(D)) 1764 return true; 1765 1766 // White-list anything that isn't a local variable. 1767 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1768 return false; 1769 1770 // Types of valid local variables should be complete, so this should succeed. 1771 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1772 1773 // White-list anything with an __attribute__((unused)) type. 1774 const auto *Ty = VD->getType().getTypePtr(); 1775 1776 // Only look at the outermost level of typedef. 1777 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1778 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1779 return false; 1780 } 1781 1782 // If we failed to complete the type for some reason, or if the type is 1783 // dependent, don't diagnose the variable. 1784 if (Ty->isIncompleteType() || Ty->isDependentType()) 1785 return false; 1786 1787 // Look at the element type to ensure that the warning behaviour is 1788 // consistent for both scalars and arrays. 1789 Ty = Ty->getBaseElementTypeUnsafe(); 1790 1791 if (const TagType *TT = Ty->getAs<TagType>()) { 1792 const TagDecl *Tag = TT->getDecl(); 1793 if (Tag->hasAttr<UnusedAttr>()) 1794 return false; 1795 1796 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1797 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1798 return false; 1799 1800 if (const Expr *Init = VD->getInit()) { 1801 if (const ExprWithCleanups *Cleanups = 1802 dyn_cast<ExprWithCleanups>(Init)) 1803 Init = Cleanups->getSubExpr(); 1804 const CXXConstructExpr *Construct = 1805 dyn_cast<CXXConstructExpr>(Init); 1806 if (Construct && !Construct->isElidable()) { 1807 CXXConstructorDecl *CD = Construct->getConstructor(); 1808 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() && 1809 (VD->getInit()->isValueDependent() || !VD->evaluateValue())) 1810 return false; 1811 } 1812 1813 // Suppress the warning if we don't know how this is constructed, and 1814 // it could possibly be non-trivial constructor. 1815 if (Init->isTypeDependent()) 1816 for (const CXXConstructorDecl *Ctor : RD->ctors()) 1817 if (!Ctor->isTrivial()) 1818 return false; 1819 } 1820 } 1821 } 1822 1823 // TODO: __attribute__((unused)) templates? 1824 } 1825 1826 return true; 1827 } 1828 1829 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1830 FixItHint &Hint) { 1831 if (isa<LabelDecl>(D)) { 1832 SourceLocation AfterColon = Lexer::findLocationAfterToken( 1833 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), 1834 true); 1835 if (AfterColon.isInvalid()) 1836 return; 1837 Hint = FixItHint::CreateRemoval( 1838 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon)); 1839 } 1840 } 1841 1842 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1843 if (D->getTypeForDecl()->isDependentType()) 1844 return; 1845 1846 for (auto *TmpD : D->decls()) { 1847 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1848 DiagnoseUnusedDecl(T); 1849 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1850 DiagnoseUnusedNestedTypedefs(R); 1851 } 1852 } 1853 1854 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1855 /// unless they are marked attr(unused). 1856 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1857 if (!ShouldDiagnoseUnusedDecl(D)) 1858 return; 1859 1860 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1861 // typedefs can be referenced later on, so the diagnostics are emitted 1862 // at end-of-translation-unit. 1863 UnusedLocalTypedefNameCandidates.insert(TD); 1864 return; 1865 } 1866 1867 FixItHint Hint; 1868 GenerateFixForUnusedDecl(D, Context, Hint); 1869 1870 unsigned DiagID; 1871 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1872 DiagID = diag::warn_unused_exception_param; 1873 else if (isa<LabelDecl>(D)) 1874 DiagID = diag::warn_unused_label; 1875 else 1876 DiagID = diag::warn_unused_variable; 1877 1878 Diag(D->getLocation(), DiagID) << D << Hint; 1879 } 1880 1881 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1882 // Verify that we have no forward references left. If so, there was a goto 1883 // or address of a label taken, but no definition of it. Label fwd 1884 // definitions are indicated with a null substmt which is also not a resolved 1885 // MS inline assembly label name. 1886 bool Diagnose = false; 1887 if (L->isMSAsmLabel()) 1888 Diagnose = !L->isResolvedMSAsmLabel(); 1889 else 1890 Diagnose = L->getStmt() == nullptr; 1891 if (Diagnose) 1892 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1893 } 1894 1895 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1896 S->mergeNRVOIntoParent(); 1897 1898 if (S->decl_empty()) return; 1899 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1900 "Scope shouldn't contain decls!"); 1901 1902 for (auto *TmpD : S->decls()) { 1903 assert(TmpD && "This decl didn't get pushed??"); 1904 1905 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1906 NamedDecl *D = cast<NamedDecl>(TmpD); 1907 1908 // Diagnose unused variables in this scope. 1909 if (!S->hasUnrecoverableErrorOccurred()) { 1910 DiagnoseUnusedDecl(D); 1911 if (const auto *RD = dyn_cast<RecordDecl>(D)) 1912 DiagnoseUnusedNestedTypedefs(RD); 1913 } 1914 1915 if (!D->getDeclName()) continue; 1916 1917 // If this was a forward reference to a label, verify it was defined. 1918 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1919 CheckPoppedLabel(LD, *this); 1920 1921 // Remove this name from our lexical scope, and warn on it if we haven't 1922 // already. 1923 IdResolver.RemoveDecl(D); 1924 auto ShadowI = ShadowingDecls.find(D); 1925 if (ShadowI != ShadowingDecls.end()) { 1926 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { 1927 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) 1928 << D << FD << FD->getParent(); 1929 Diag(FD->getLocation(), diag::note_previous_declaration); 1930 } 1931 ShadowingDecls.erase(ShadowI); 1932 } 1933 } 1934 } 1935 1936 /// Look for an Objective-C class in the translation unit. 1937 /// 1938 /// \param Id The name of the Objective-C class we're looking for. If 1939 /// typo-correction fixes this name, the Id will be updated 1940 /// to the fixed name. 1941 /// 1942 /// \param IdLoc The location of the name in the translation unit. 1943 /// 1944 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1945 /// if there is no class with the given name. 1946 /// 1947 /// \returns The declaration of the named Objective-C class, or NULL if the 1948 /// class could not be found. 1949 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1950 SourceLocation IdLoc, 1951 bool DoTypoCorrection) { 1952 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1953 // creation from this context. 1954 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1955 1956 if (!IDecl && DoTypoCorrection) { 1957 // Perform typo correction at the given location, but only if we 1958 // find an Objective-C class name. 1959 DeclFilterCCC<ObjCInterfaceDecl> CCC{}; 1960 if (TypoCorrection C = 1961 CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, 1962 TUScope, nullptr, CCC, CTK_ErrorRecovery)) { 1963 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1964 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1965 Id = IDecl->getIdentifier(); 1966 } 1967 } 1968 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1969 // This routine must always return a class definition, if any. 1970 if (Def && Def->getDefinition()) 1971 Def = Def->getDefinition(); 1972 return Def; 1973 } 1974 1975 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 1976 /// from S, where a non-field would be declared. This routine copes 1977 /// with the difference between C and C++ scoping rules in structs and 1978 /// unions. For example, the following code is well-formed in C but 1979 /// ill-formed in C++: 1980 /// @code 1981 /// struct S6 { 1982 /// enum { BAR } e; 1983 /// }; 1984 /// 1985 /// void test_S6() { 1986 /// struct S6 a; 1987 /// a.e = BAR; 1988 /// } 1989 /// @endcode 1990 /// For the declaration of BAR, this routine will return a different 1991 /// scope. The scope S will be the scope of the unnamed enumeration 1992 /// within S6. In C++, this routine will return the scope associated 1993 /// with S6, because the enumeration's scope is a transparent 1994 /// context but structures can contain non-field names. In C, this 1995 /// routine will return the translation unit scope, since the 1996 /// enumeration's scope is a transparent context and structures cannot 1997 /// contain non-field names. 1998 Scope *Sema::getNonFieldDeclScope(Scope *S) { 1999 while (((S->getFlags() & Scope::DeclScope) == 0) || 2000 (S->getEntity() && S->getEntity()->isTransparentContext()) || 2001 (S->isClassScope() && !getLangOpts().CPlusPlus)) 2002 S = S->getParent(); 2003 return S; 2004 } 2005 2006 /// Looks up the declaration of "struct objc_super" and 2007 /// saves it for later use in building builtin declaration of 2008 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such 2009 /// pre-existing declaration exists no action takes place. 2010 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, 2011 IdentifierInfo *II) { 2012 if (!II->isStr("objc_msgSendSuper")) 2013 return; 2014 ASTContext &Context = ThisSema.Context; 2015 2016 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), 2017 SourceLocation(), Sema::LookupTagName); 2018 ThisSema.LookupName(Result, S); 2019 if (Result.getResultKind() == LookupResult::Found) 2020 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 2021 Context.setObjCSuperType(Context.getTagDeclType(TD)); 2022 } 2023 2024 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, 2025 ASTContext::GetBuiltinTypeError Error) { 2026 switch (Error) { 2027 case ASTContext::GE_None: 2028 return ""; 2029 case ASTContext::GE_Missing_type: 2030 return BuiltinInfo.getHeaderName(ID); 2031 case ASTContext::GE_Missing_stdio: 2032 return "stdio.h"; 2033 case ASTContext::GE_Missing_setjmp: 2034 return "setjmp.h"; 2035 case ASTContext::GE_Missing_ucontext: 2036 return "ucontext.h"; 2037 } 2038 llvm_unreachable("unhandled error kind"); 2039 } 2040 2041 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 2042 /// file scope. lazily create a decl for it. ForRedeclaration is true 2043 /// if we're creating this built-in in anticipation of redeclaring the 2044 /// built-in. 2045 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 2046 Scope *S, bool ForRedeclaration, 2047 SourceLocation Loc) { 2048 LookupPredefedObjCSuperType(*this, S, II); 2049 2050 ASTContext::GetBuiltinTypeError Error; 2051 QualType R = Context.GetBuiltinType(ID, Error); 2052 if (Error) { 2053 if (!ForRedeclaration) 2054 return nullptr; 2055 2056 // If we have a builtin without an associated type we should not emit a 2057 // warning when we were not able to find a type for it. 2058 if (Error == ASTContext::GE_Missing_type) 2059 return nullptr; 2060 2061 // If we could not find a type for setjmp it is because the jmp_buf type was 2062 // not defined prior to the setjmp declaration. 2063 if (Error == ASTContext::GE_Missing_setjmp) { 2064 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf) 2065 << Context.BuiltinInfo.getName(ID); 2066 return nullptr; 2067 } 2068 2069 // Generally, we emit a warning that the declaration requires the 2070 // appropriate header. 2071 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 2072 << getHeaderName(Context.BuiltinInfo, ID, Error) 2073 << Context.BuiltinInfo.getName(ID); 2074 return nullptr; 2075 } 2076 2077 if (!ForRedeclaration && 2078 (Context.BuiltinInfo.isPredefinedLibFunction(ID) || 2079 Context.BuiltinInfo.isHeaderDependentFunction(ID))) { 2080 Diag(Loc, diag::ext_implicit_lib_function_decl) 2081 << Context.BuiltinInfo.getName(ID) << R; 2082 if (Context.BuiltinInfo.getHeaderName(ID) && 2083 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc)) 2084 Diag(Loc, diag::note_include_header_or_declare) 2085 << Context.BuiltinInfo.getHeaderName(ID) 2086 << Context.BuiltinInfo.getName(ID); 2087 } 2088 2089 if (R.isNull()) 2090 return nullptr; 2091 2092 DeclContext *Parent = Context.getTranslationUnitDecl(); 2093 if (getLangOpts().CPlusPlus) { 2094 LinkageSpecDecl *CLinkageDecl = 2095 LinkageSpecDecl::Create(Context, Parent, Loc, Loc, 2096 LinkageSpecDecl::lang_c, false); 2097 CLinkageDecl->setImplicit(); 2098 Parent->addDecl(CLinkageDecl); 2099 Parent = CLinkageDecl; 2100 } 2101 2102 FunctionDecl *New = FunctionDecl::Create(Context, 2103 Parent, 2104 Loc, Loc, II, R, /*TInfo=*/nullptr, 2105 SC_Extern, 2106 false, 2107 R->isFunctionProtoType()); 2108 New->setImplicit(); 2109 2110 // Create Decl objects for each parameter, adding them to the 2111 // FunctionDecl. 2112 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 2113 SmallVector<ParmVarDecl*, 16> Params; 2114 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 2115 ParmVarDecl *parm = 2116 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(), 2117 nullptr, FT->getParamType(i), /*TInfo=*/nullptr, 2118 SC_None, nullptr); 2119 parm->setScopeInfo(0, i); 2120 Params.push_back(parm); 2121 } 2122 New->setParams(Params); 2123 } 2124 2125 AddKnownFunctionAttributes(New); 2126 RegisterLocallyScopedExternCDecl(New, S); 2127 2128 // TUScope is the translation-unit scope to insert this function into. 2129 // FIXME: This is hideous. We need to teach PushOnScopeChains to 2130 // relate Scopes to DeclContexts, and probably eliminate CurContext 2131 // entirely, but we're not there yet. 2132 DeclContext *SavedContext = CurContext; 2133 CurContext = Parent; 2134 PushOnScopeChains(New, TUScope); 2135 CurContext = SavedContext; 2136 return New; 2137 } 2138 2139 /// Typedef declarations don't have linkage, but they still denote the same 2140 /// entity if their types are the same. 2141 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 2142 /// isSameEntity. 2143 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 2144 TypedefNameDecl *Decl, 2145 LookupResult &Previous) { 2146 // This is only interesting when modules are enabled. 2147 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 2148 return; 2149 2150 // Empty sets are uninteresting. 2151 if (Previous.empty()) 2152 return; 2153 2154 LookupResult::Filter Filter = Previous.makeFilter(); 2155 while (Filter.hasNext()) { 2156 NamedDecl *Old = Filter.next(); 2157 2158 // Non-hidden declarations are never ignored. 2159 if (S.isVisible(Old)) 2160 continue; 2161 2162 // Declarations of the same entity are not ignored, even if they have 2163 // different linkages. 2164 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2165 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 2166 Decl->getUnderlyingType())) 2167 continue; 2168 2169 // If both declarations give a tag declaration a typedef name for linkage 2170 // purposes, then they declare the same entity. 2171 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 2172 Decl->getAnonDeclWithTypedefName()) 2173 continue; 2174 } 2175 2176 Filter.erase(); 2177 } 2178 2179 Filter.done(); 2180 } 2181 2182 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 2183 QualType OldType; 2184 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 2185 OldType = OldTypedef->getUnderlyingType(); 2186 else 2187 OldType = Context.getTypeDeclType(Old); 2188 QualType NewType = New->getUnderlyingType(); 2189 2190 if (NewType->isVariablyModifiedType()) { 2191 // Must not redefine a typedef with a variably-modified type. 2192 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2193 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 2194 << Kind << NewType; 2195 if (Old->getLocation().isValid()) 2196 notePreviousDefinition(Old, New->getLocation()); 2197 New->setInvalidDecl(); 2198 return true; 2199 } 2200 2201 if (OldType != NewType && 2202 !OldType->isDependentType() && 2203 !NewType->isDependentType() && 2204 !Context.hasSameType(OldType, NewType)) { 2205 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2206 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 2207 << Kind << NewType << OldType; 2208 if (Old->getLocation().isValid()) 2209 notePreviousDefinition(Old, New->getLocation()); 2210 New->setInvalidDecl(); 2211 return true; 2212 } 2213 return false; 2214 } 2215 2216 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 2217 /// same name and scope as a previous declaration 'Old'. Figure out 2218 /// how to resolve this situation, merging decls or emitting 2219 /// diagnostics as appropriate. If there was an error, set New to be invalid. 2220 /// 2221 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 2222 LookupResult &OldDecls) { 2223 // If the new decl is known invalid already, don't bother doing any 2224 // merging checks. 2225 if (New->isInvalidDecl()) return; 2226 2227 // Allow multiple definitions for ObjC built-in typedefs. 2228 // FIXME: Verify the underlying types are equivalent! 2229 if (getLangOpts().ObjC) { 2230 const IdentifierInfo *TypeID = New->getIdentifier(); 2231 switch (TypeID->getLength()) { 2232 default: break; 2233 case 2: 2234 { 2235 if (!TypeID->isStr("id")) 2236 break; 2237 QualType T = New->getUnderlyingType(); 2238 if (!T->isPointerType()) 2239 break; 2240 if (!T->isVoidPointerType()) { 2241 QualType PT = T->castAs<PointerType>()->getPointeeType(); 2242 if (!PT->isStructureType()) 2243 break; 2244 } 2245 Context.setObjCIdRedefinitionType(T); 2246 // Install the built-in type for 'id', ignoring the current definition. 2247 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 2248 return; 2249 } 2250 case 5: 2251 if (!TypeID->isStr("Class")) 2252 break; 2253 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 2254 // Install the built-in type for 'Class', ignoring the current definition. 2255 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 2256 return; 2257 case 3: 2258 if (!TypeID->isStr("SEL")) 2259 break; 2260 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 2261 // Install the built-in type for 'SEL', ignoring the current definition. 2262 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 2263 return; 2264 } 2265 // Fall through - the typedef name was not a builtin type. 2266 } 2267 2268 // Verify the old decl was also a type. 2269 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 2270 if (!Old) { 2271 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2272 << New->getDeclName(); 2273 2274 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 2275 if (OldD->getLocation().isValid()) 2276 notePreviousDefinition(OldD, New->getLocation()); 2277 2278 return New->setInvalidDecl(); 2279 } 2280 2281 // If the old declaration is invalid, just give up here. 2282 if (Old->isInvalidDecl()) 2283 return New->setInvalidDecl(); 2284 2285 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2286 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2287 auto *NewTag = New->getAnonDeclWithTypedefName(); 2288 NamedDecl *Hidden = nullptr; 2289 if (OldTag && NewTag && 2290 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 2291 !hasVisibleDefinition(OldTag, &Hidden)) { 2292 // There is a definition of this tag, but it is not visible. Use it 2293 // instead of our tag. 2294 New->setTypeForDecl(OldTD->getTypeForDecl()); 2295 if (OldTD->isModed()) 2296 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 2297 OldTD->getUnderlyingType()); 2298 else 2299 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 2300 2301 // Make the old tag definition visible. 2302 makeMergedDefinitionVisible(Hidden); 2303 2304 // If this was an unscoped enumeration, yank all of its enumerators 2305 // out of the scope. 2306 if (isa<EnumDecl>(NewTag)) { 2307 Scope *EnumScope = getNonFieldDeclScope(S); 2308 for (auto *D : NewTag->decls()) { 2309 auto *ED = cast<EnumConstantDecl>(D); 2310 assert(EnumScope->isDeclScope(ED)); 2311 EnumScope->RemoveDecl(ED); 2312 IdResolver.RemoveDecl(ED); 2313 ED->getLexicalDeclContext()->removeDecl(ED); 2314 } 2315 } 2316 } 2317 } 2318 2319 // If the typedef types are not identical, reject them in all languages and 2320 // with any extensions enabled. 2321 if (isIncompatibleTypedef(Old, New)) 2322 return; 2323 2324 // The types match. Link up the redeclaration chain and merge attributes if 2325 // the old declaration was a typedef. 2326 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2327 New->setPreviousDecl(Typedef); 2328 mergeDeclAttributes(New, Old); 2329 } 2330 2331 if (getLangOpts().MicrosoftExt) 2332 return; 2333 2334 if (getLangOpts().CPlusPlus) { 2335 // C++ [dcl.typedef]p2: 2336 // In a given non-class scope, a typedef specifier can be used to 2337 // redefine the name of any type declared in that scope to refer 2338 // to the type to which it already refers. 2339 if (!isa<CXXRecordDecl>(CurContext)) 2340 return; 2341 2342 // C++0x [dcl.typedef]p4: 2343 // In a given class scope, a typedef specifier can be used to redefine 2344 // any class-name declared in that scope that is not also a typedef-name 2345 // to refer to the type to which it already refers. 2346 // 2347 // This wording came in via DR424, which was a correction to the 2348 // wording in DR56, which accidentally banned code like: 2349 // 2350 // struct S { 2351 // typedef struct A { } A; 2352 // }; 2353 // 2354 // in the C++03 standard. We implement the C++0x semantics, which 2355 // allow the above but disallow 2356 // 2357 // struct S { 2358 // typedef int I; 2359 // typedef int I; 2360 // }; 2361 // 2362 // since that was the intent of DR56. 2363 if (!isa<TypedefNameDecl>(Old)) 2364 return; 2365 2366 Diag(New->getLocation(), diag::err_redefinition) 2367 << New->getDeclName(); 2368 notePreviousDefinition(Old, New->getLocation()); 2369 return New->setInvalidDecl(); 2370 } 2371 2372 // Modules always permit redefinition of typedefs, as does C11. 2373 if (getLangOpts().Modules || getLangOpts().C11) 2374 return; 2375 2376 // If we have a redefinition of a typedef in C, emit a warning. This warning 2377 // is normally mapped to an error, but can be controlled with 2378 // -Wtypedef-redefinition. If either the original or the redefinition is 2379 // in a system header, don't emit this for compatibility with GCC. 2380 if (getDiagnostics().getSuppressSystemWarnings() && 2381 // Some standard types are defined implicitly in Clang (e.g. OpenCL). 2382 (Old->isImplicit() || 2383 Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2384 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2385 return; 2386 2387 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2388 << New->getDeclName(); 2389 notePreviousDefinition(Old, New->getLocation()); 2390 } 2391 2392 /// DeclhasAttr - returns true if decl Declaration already has the target 2393 /// attribute. 2394 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2395 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2396 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2397 for (const auto *i : D->attrs()) 2398 if (i->getKind() == A->getKind()) { 2399 if (Ann) { 2400 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2401 return true; 2402 continue; 2403 } 2404 // FIXME: Don't hardcode this check 2405 if (OA && isa<OwnershipAttr>(i)) 2406 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2407 return true; 2408 } 2409 2410 return false; 2411 } 2412 2413 static bool isAttributeTargetADefinition(Decl *D) { 2414 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2415 return VD->isThisDeclarationADefinition(); 2416 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2417 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2418 return true; 2419 } 2420 2421 /// Merge alignment attributes from \p Old to \p New, taking into account the 2422 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2423 /// 2424 /// \return \c true if any attributes were added to \p New. 2425 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2426 // Look for alignas attributes on Old, and pick out whichever attribute 2427 // specifies the strictest alignment requirement. 2428 AlignedAttr *OldAlignasAttr = nullptr; 2429 AlignedAttr *OldStrictestAlignAttr = nullptr; 2430 unsigned OldAlign = 0; 2431 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2432 // FIXME: We have no way of representing inherited dependent alignments 2433 // in a case like: 2434 // template<int A, int B> struct alignas(A) X; 2435 // template<int A, int B> struct alignas(B) X {}; 2436 // For now, we just ignore any alignas attributes which are not on the 2437 // definition in such a case. 2438 if (I->isAlignmentDependent()) 2439 return false; 2440 2441 if (I->isAlignas()) 2442 OldAlignasAttr = I; 2443 2444 unsigned Align = I->getAlignment(S.Context); 2445 if (Align > OldAlign) { 2446 OldAlign = Align; 2447 OldStrictestAlignAttr = I; 2448 } 2449 } 2450 2451 // Look for alignas attributes on New. 2452 AlignedAttr *NewAlignasAttr = nullptr; 2453 unsigned NewAlign = 0; 2454 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2455 if (I->isAlignmentDependent()) 2456 return false; 2457 2458 if (I->isAlignas()) 2459 NewAlignasAttr = I; 2460 2461 unsigned Align = I->getAlignment(S.Context); 2462 if (Align > NewAlign) 2463 NewAlign = Align; 2464 } 2465 2466 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2467 // Both declarations have 'alignas' attributes. We require them to match. 2468 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2469 // fall short. (If two declarations both have alignas, they must both match 2470 // every definition, and so must match each other if there is a definition.) 2471 2472 // If either declaration only contains 'alignas(0)' specifiers, then it 2473 // specifies the natural alignment for the type. 2474 if (OldAlign == 0 || NewAlign == 0) { 2475 QualType Ty; 2476 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2477 Ty = VD->getType(); 2478 else 2479 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2480 2481 if (OldAlign == 0) 2482 OldAlign = S.Context.getTypeAlign(Ty); 2483 if (NewAlign == 0) 2484 NewAlign = S.Context.getTypeAlign(Ty); 2485 } 2486 2487 if (OldAlign != NewAlign) { 2488 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2489 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2490 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2491 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2492 } 2493 } 2494 2495 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2496 // C++11 [dcl.align]p6: 2497 // if any declaration of an entity has an alignment-specifier, 2498 // every defining declaration of that entity shall specify an 2499 // equivalent alignment. 2500 // C11 6.7.5/7: 2501 // If the definition of an object does not have an alignment 2502 // specifier, any other declaration of that object shall also 2503 // have no alignment specifier. 2504 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2505 << OldAlignasAttr; 2506 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2507 << OldAlignasAttr; 2508 } 2509 2510 bool AnyAdded = false; 2511 2512 // Ensure we have an attribute representing the strictest alignment. 2513 if (OldAlign > NewAlign) { 2514 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2515 Clone->setInherited(true); 2516 New->addAttr(Clone); 2517 AnyAdded = true; 2518 } 2519 2520 // Ensure we have an alignas attribute if the old declaration had one. 2521 if (OldAlignasAttr && !NewAlignasAttr && 2522 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2523 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2524 Clone->setInherited(true); 2525 New->addAttr(Clone); 2526 AnyAdded = true; 2527 } 2528 2529 return AnyAdded; 2530 } 2531 2532 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2533 const InheritableAttr *Attr, 2534 Sema::AvailabilityMergeKind AMK) { 2535 // This function copies an attribute Attr from a previous declaration to the 2536 // new declaration D if the new declaration doesn't itself have that attribute 2537 // yet or if that attribute allows duplicates. 2538 // If you're adding a new attribute that requires logic different from 2539 // "use explicit attribute on decl if present, else use attribute from 2540 // previous decl", for example if the attribute needs to be consistent 2541 // between redeclarations, you need to call a custom merge function here. 2542 InheritableAttr *NewAttr = nullptr; 2543 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2544 NewAttr = S.mergeAvailabilityAttr( 2545 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(), 2546 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(), 2547 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK, 2548 AA->getPriority()); 2549 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2550 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility()); 2551 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2552 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility()); 2553 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2554 NewAttr = S.mergeDLLImportAttr(D, *ImportA); 2555 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2556 NewAttr = S.mergeDLLExportAttr(D, *ExportA); 2557 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2558 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(), 2559 FA->getFirstArg()); 2560 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2561 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName()); 2562 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr)) 2563 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName()); 2564 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2565 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(), 2566 IA->getInheritanceModel()); 2567 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2568 NewAttr = S.mergeAlwaysInlineAttr(D, *AA, 2569 &S.Context.Idents.get(AA->getSpelling())); 2570 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2571 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2572 isa<CUDAGlobalAttr>(Attr))) { 2573 // CUDA target attributes are part of function signature for 2574 // overloading purposes and must not be merged. 2575 return false; 2576 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2577 NewAttr = S.mergeMinSizeAttr(D, *MA); 2578 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2579 NewAttr = S.mergeOptimizeNoneAttr(D, *OA); 2580 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2581 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA); 2582 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr)) 2583 NewAttr = S.mergeCommonAttr(D, *CommonA); 2584 else if (isa<AlignedAttr>(Attr)) 2585 // AlignedAttrs are handled separately, because we need to handle all 2586 // such attributes on a declaration at the same time. 2587 NewAttr = nullptr; 2588 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2589 (AMK == Sema::AMK_Override || 2590 AMK == Sema::AMK_ProtocolImplementation)) 2591 NewAttr = nullptr; 2592 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2593 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid()); 2594 else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr)) 2595 NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA); 2596 else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr)) 2597 NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA); 2598 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr)) 2599 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2600 2601 if (NewAttr) { 2602 NewAttr->setInherited(true); 2603 D->addAttr(NewAttr); 2604 if (isa<MSInheritanceAttr>(NewAttr)) 2605 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2606 return true; 2607 } 2608 2609 return false; 2610 } 2611 2612 static const NamedDecl *getDefinition(const Decl *D) { 2613 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2614 return TD->getDefinition(); 2615 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2616 const VarDecl *Def = VD->getDefinition(); 2617 if (Def) 2618 return Def; 2619 return VD->getActingDefinition(); 2620 } 2621 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 2622 return FD->getDefinition(); 2623 return nullptr; 2624 } 2625 2626 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2627 for (const auto *Attribute : D->attrs()) 2628 if (Attribute->getKind() == Kind) 2629 return true; 2630 return false; 2631 } 2632 2633 /// checkNewAttributesAfterDef - If we already have a definition, check that 2634 /// there are no new attributes in this declaration. 2635 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2636 if (!New->hasAttrs()) 2637 return; 2638 2639 const NamedDecl *Def = getDefinition(Old); 2640 if (!Def || Def == New) 2641 return; 2642 2643 AttrVec &NewAttributes = New->getAttrs(); 2644 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2645 const Attr *NewAttribute = NewAttributes[I]; 2646 2647 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 2648 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2649 Sema::SkipBodyInfo SkipBody; 2650 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2651 2652 // If we're skipping this definition, drop the "alias" attribute. 2653 if (SkipBody.ShouldSkip) { 2654 NewAttributes.erase(NewAttributes.begin() + I); 2655 --E; 2656 continue; 2657 } 2658 } else { 2659 VarDecl *VD = cast<VarDecl>(New); 2660 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2661 VarDecl::TentativeDefinition 2662 ? diag::err_alias_after_tentative 2663 : diag::err_redefinition; 2664 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2665 if (Diag == diag::err_redefinition) 2666 S.notePreviousDefinition(Def, VD->getLocation()); 2667 else 2668 S.Diag(Def->getLocation(), diag::note_previous_definition); 2669 VD->setInvalidDecl(); 2670 } 2671 ++I; 2672 continue; 2673 } 2674 2675 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2676 // Tentative definitions are only interesting for the alias check above. 2677 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2678 ++I; 2679 continue; 2680 } 2681 } 2682 2683 if (hasAttribute(Def, NewAttribute->getKind())) { 2684 ++I; 2685 continue; // regular attr merging will take care of validating this. 2686 } 2687 2688 if (isa<C11NoReturnAttr>(NewAttribute)) { 2689 // C's _Noreturn is allowed to be added to a function after it is defined. 2690 ++I; 2691 continue; 2692 } else if (isa<UuidAttr>(NewAttribute)) { 2693 // msvc will allow a subsequent definition to add an uuid to a class 2694 ++I; 2695 continue; 2696 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2697 if (AA->isAlignas()) { 2698 // C++11 [dcl.align]p6: 2699 // if any declaration of an entity has an alignment-specifier, 2700 // every defining declaration of that entity shall specify an 2701 // equivalent alignment. 2702 // C11 6.7.5/7: 2703 // If the definition of an object does not have an alignment 2704 // specifier, any other declaration of that object shall also 2705 // have no alignment specifier. 2706 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2707 << AA; 2708 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2709 << AA; 2710 NewAttributes.erase(NewAttributes.begin() + I); 2711 --E; 2712 continue; 2713 } 2714 } else if (isa<SelectAnyAttr>(NewAttribute) && 2715 cast<VarDecl>(New)->isInline() && 2716 !cast<VarDecl>(New)->isInlineSpecified()) { 2717 // Don't warn about applying selectany to implicitly inline variables. 2718 // Older compilers and language modes would require the use of selectany 2719 // to make such variables inline, and it would have no effect if we 2720 // honored it. 2721 ++I; 2722 continue; 2723 } 2724 2725 S.Diag(NewAttribute->getLocation(), 2726 diag::warn_attribute_precede_definition); 2727 S.Diag(Def->getLocation(), diag::note_previous_definition); 2728 NewAttributes.erase(NewAttributes.begin() + I); 2729 --E; 2730 } 2731 } 2732 2733 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, 2734 const ConstInitAttr *CIAttr, 2735 bool AttrBeforeInit) { 2736 SourceLocation InsertLoc = InitDecl->getInnerLocStart(); 2737 2738 // Figure out a good way to write this specifier on the old declaration. 2739 // FIXME: We should just use the spelling of CIAttr, but we don't preserve 2740 // enough of the attribute list spelling information to extract that without 2741 // heroics. 2742 std::string SuitableSpelling; 2743 if (S.getLangOpts().CPlusPlus2a) 2744 SuitableSpelling = std::string( 2745 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit})); 2746 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2747 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2748 InsertLoc, {tok::l_square, tok::l_square, 2749 S.PP.getIdentifierInfo("clang"), tok::coloncolon, 2750 S.PP.getIdentifierInfo("require_constant_initialization"), 2751 tok::r_square, tok::r_square})); 2752 if (SuitableSpelling.empty()) 2753 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2754 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren, 2755 S.PP.getIdentifierInfo("require_constant_initialization"), 2756 tok::r_paren, tok::r_paren})); 2757 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus2a) 2758 SuitableSpelling = "constinit"; 2759 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2760 SuitableSpelling = "[[clang::require_constant_initialization]]"; 2761 if (SuitableSpelling.empty()) 2762 SuitableSpelling = "__attribute__((require_constant_initialization))"; 2763 SuitableSpelling += " "; 2764 2765 if (AttrBeforeInit) { 2766 // extern constinit int a; 2767 // int a = 0; // error (missing 'constinit'), accepted as extension 2768 assert(CIAttr->isConstinit() && "should not diagnose this for attribute"); 2769 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing) 2770 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 2771 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here); 2772 } else { 2773 // int a = 0; 2774 // constinit extern int a; // error (missing 'constinit') 2775 S.Diag(CIAttr->getLocation(), 2776 CIAttr->isConstinit() ? diag::err_constinit_added_too_late 2777 : diag::warn_require_const_init_added_too_late) 2778 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation())); 2779 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here) 2780 << CIAttr->isConstinit() 2781 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 2782 } 2783 } 2784 2785 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2786 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2787 AvailabilityMergeKind AMK) { 2788 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2789 UsedAttr *NewAttr = OldAttr->clone(Context); 2790 NewAttr->setInherited(true); 2791 New->addAttr(NewAttr); 2792 } 2793 2794 if (!Old->hasAttrs() && !New->hasAttrs()) 2795 return; 2796 2797 // [dcl.constinit]p1: 2798 // If the [constinit] specifier is applied to any declaration of a 2799 // variable, it shall be applied to the initializing declaration. 2800 const auto *OldConstInit = Old->getAttr<ConstInitAttr>(); 2801 const auto *NewConstInit = New->getAttr<ConstInitAttr>(); 2802 if (bool(OldConstInit) != bool(NewConstInit)) { 2803 const auto *OldVD = cast<VarDecl>(Old); 2804 auto *NewVD = cast<VarDecl>(New); 2805 2806 // Find the initializing declaration. Note that we might not have linked 2807 // the new declaration into the redeclaration chain yet. 2808 const VarDecl *InitDecl = OldVD->getInitializingDeclaration(); 2809 if (!InitDecl && 2810 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition())) 2811 InitDecl = NewVD; 2812 2813 if (InitDecl == NewVD) { 2814 // This is the initializing declaration. If it would inherit 'constinit', 2815 // that's ill-formed. (Note that we do not apply this to the attribute 2816 // form). 2817 if (OldConstInit && OldConstInit->isConstinit()) 2818 diagnoseMissingConstinit(*this, NewVD, OldConstInit, 2819 /*AttrBeforeInit=*/true); 2820 } else if (NewConstInit) { 2821 // This is the first time we've been told that this declaration should 2822 // have a constant initializer. If we already saw the initializing 2823 // declaration, this is too late. 2824 if (InitDecl && InitDecl != NewVD) { 2825 diagnoseMissingConstinit(*this, InitDecl, NewConstInit, 2826 /*AttrBeforeInit=*/false); 2827 NewVD->dropAttr<ConstInitAttr>(); 2828 } 2829 } 2830 } 2831 2832 // Attributes declared post-definition are currently ignored. 2833 checkNewAttributesAfterDef(*this, New, Old); 2834 2835 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 2836 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 2837 if (!OldA->isEquivalent(NewA)) { 2838 // This redeclaration changes __asm__ label. 2839 Diag(New->getLocation(), diag::err_different_asm_label); 2840 Diag(OldA->getLocation(), diag::note_previous_declaration); 2841 } 2842 } else if (Old->isUsed()) { 2843 // This redeclaration adds an __asm__ label to a declaration that has 2844 // already been ODR-used. 2845 Diag(New->getLocation(), diag::err_late_asm_label_name) 2846 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 2847 } 2848 } 2849 2850 // Re-declaration cannot add abi_tag's. 2851 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 2852 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 2853 for (const auto &NewTag : NewAbiTagAttr->tags()) { 2854 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(), 2855 NewTag) == OldAbiTagAttr->tags_end()) { 2856 Diag(NewAbiTagAttr->getLocation(), 2857 diag::err_new_abi_tag_on_redeclaration) 2858 << NewTag; 2859 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 2860 } 2861 } 2862 } else { 2863 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 2864 Diag(Old->getLocation(), diag::note_previous_declaration); 2865 } 2866 } 2867 2868 // This redeclaration adds a section attribute. 2869 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { 2870 if (auto *VD = dyn_cast<VarDecl>(New)) { 2871 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) { 2872 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration); 2873 Diag(Old->getLocation(), diag::note_previous_declaration); 2874 } 2875 } 2876 } 2877 2878 // Redeclaration adds code-seg attribute. 2879 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 2880 if (NewCSA && !Old->hasAttr<CodeSegAttr>() && 2881 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) { 2882 Diag(New->getLocation(), diag::warn_mismatched_section) 2883 << 0 /*codeseg*/; 2884 Diag(Old->getLocation(), diag::note_previous_declaration); 2885 } 2886 2887 if (!Old->hasAttrs()) 2888 return; 2889 2890 bool foundAny = New->hasAttrs(); 2891 2892 // Ensure that any moving of objects within the allocated map is done before 2893 // we process them. 2894 if (!foundAny) New->setAttrs(AttrVec()); 2895 2896 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2897 // Ignore deprecated/unavailable/availability attributes if requested. 2898 AvailabilityMergeKind LocalAMK = AMK_None; 2899 if (isa<DeprecatedAttr>(I) || 2900 isa<UnavailableAttr>(I) || 2901 isa<AvailabilityAttr>(I)) { 2902 switch (AMK) { 2903 case AMK_None: 2904 continue; 2905 2906 case AMK_Redeclaration: 2907 case AMK_Override: 2908 case AMK_ProtocolImplementation: 2909 LocalAMK = AMK; 2910 break; 2911 } 2912 } 2913 2914 // Already handled. 2915 if (isa<UsedAttr>(I)) 2916 continue; 2917 2918 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 2919 foundAny = true; 2920 } 2921 2922 if (mergeAlignedAttrs(*this, New, Old)) 2923 foundAny = true; 2924 2925 if (!foundAny) New->dropAttrs(); 2926 } 2927 2928 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2929 /// to the new one. 2930 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2931 const ParmVarDecl *oldDecl, 2932 Sema &S) { 2933 // C++11 [dcl.attr.depend]p2: 2934 // The first declaration of a function shall specify the 2935 // carries_dependency attribute for its declarator-id if any declaration 2936 // of the function specifies the carries_dependency attribute. 2937 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2938 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2939 S.Diag(CDA->getLocation(), 2940 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2941 // Find the first declaration of the parameter. 2942 // FIXME: Should we build redeclaration chains for function parameters? 2943 const FunctionDecl *FirstFD = 2944 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2945 const ParmVarDecl *FirstVD = 2946 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2947 S.Diag(FirstVD->getLocation(), 2948 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2949 } 2950 2951 if (!oldDecl->hasAttrs()) 2952 return; 2953 2954 bool foundAny = newDecl->hasAttrs(); 2955 2956 // Ensure that any moving of objects within the allocated map is 2957 // done before we process them. 2958 if (!foundAny) newDecl->setAttrs(AttrVec()); 2959 2960 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 2961 if (!DeclHasAttr(newDecl, I)) { 2962 InheritableAttr *newAttr = 2963 cast<InheritableParamAttr>(I->clone(S.Context)); 2964 newAttr->setInherited(true); 2965 newDecl->addAttr(newAttr); 2966 foundAny = true; 2967 } 2968 } 2969 2970 if (!foundAny) newDecl->dropAttrs(); 2971 } 2972 2973 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 2974 const ParmVarDecl *OldParam, 2975 Sema &S) { 2976 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 2977 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 2978 if (*Oldnullability != *Newnullability) { 2979 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 2980 << DiagNullabilityKind( 2981 *Newnullability, 2982 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2983 != 0)) 2984 << DiagNullabilityKind( 2985 *Oldnullability, 2986 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2987 != 0)); 2988 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 2989 } 2990 } else { 2991 QualType NewT = NewParam->getType(); 2992 NewT = S.Context.getAttributedType( 2993 AttributedType::getNullabilityAttrKind(*Oldnullability), 2994 NewT, NewT); 2995 NewParam->setType(NewT); 2996 } 2997 } 2998 } 2999 3000 namespace { 3001 3002 /// Used in MergeFunctionDecl to keep track of function parameters in 3003 /// C. 3004 struct GNUCompatibleParamWarning { 3005 ParmVarDecl *OldParm; 3006 ParmVarDecl *NewParm; 3007 QualType PromotedType; 3008 }; 3009 3010 } // end anonymous namespace 3011 3012 // Determine whether the previous declaration was a definition, implicit 3013 // declaration, or a declaration. 3014 template <typename T> 3015 static std::pair<diag::kind, SourceLocation> 3016 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 3017 diag::kind PrevDiag; 3018 SourceLocation OldLocation = Old->getLocation(); 3019 if (Old->isThisDeclarationADefinition()) 3020 PrevDiag = diag::note_previous_definition; 3021 else if (Old->isImplicit()) { 3022 PrevDiag = diag::note_previous_implicit_declaration; 3023 if (OldLocation.isInvalid()) 3024 OldLocation = New->getLocation(); 3025 } else 3026 PrevDiag = diag::note_previous_declaration; 3027 return std::make_pair(PrevDiag, OldLocation); 3028 } 3029 3030 /// canRedefineFunction - checks if a function can be redefined. Currently, 3031 /// only extern inline functions can be redefined, and even then only in 3032 /// GNU89 mode. 3033 static bool canRedefineFunction(const FunctionDecl *FD, 3034 const LangOptions& LangOpts) { 3035 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 3036 !LangOpts.CPlusPlus && 3037 FD->isInlineSpecified() && 3038 FD->getStorageClass() == SC_Extern); 3039 } 3040 3041 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 3042 const AttributedType *AT = T->getAs<AttributedType>(); 3043 while (AT && !AT->isCallingConv()) 3044 AT = AT->getModifiedType()->getAs<AttributedType>(); 3045 return AT; 3046 } 3047 3048 template <typename T> 3049 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 3050 const DeclContext *DC = Old->getDeclContext(); 3051 if (DC->isRecord()) 3052 return false; 3053 3054 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 3055 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 3056 return true; 3057 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 3058 return true; 3059 return false; 3060 } 3061 3062 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 3063 static bool isExternC(VarTemplateDecl *) { return false; } 3064 3065 /// Check whether a redeclaration of an entity introduced by a 3066 /// using-declaration is valid, given that we know it's not an overload 3067 /// (nor a hidden tag declaration). 3068 template<typename ExpectedDecl> 3069 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 3070 ExpectedDecl *New) { 3071 // C++11 [basic.scope.declarative]p4: 3072 // Given a set of declarations in a single declarative region, each of 3073 // which specifies the same unqualified name, 3074 // -- they shall all refer to the same entity, or all refer to functions 3075 // and function templates; or 3076 // -- exactly one declaration shall declare a class name or enumeration 3077 // name that is not a typedef name and the other declarations shall all 3078 // refer to the same variable or enumerator, or all refer to functions 3079 // and function templates; in this case the class name or enumeration 3080 // name is hidden (3.3.10). 3081 3082 // C++11 [namespace.udecl]p14: 3083 // If a function declaration in namespace scope or block scope has the 3084 // same name and the same parameter-type-list as a function introduced 3085 // by a using-declaration, and the declarations do not declare the same 3086 // function, the program is ill-formed. 3087 3088 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 3089 if (Old && 3090 !Old->getDeclContext()->getRedeclContext()->Equals( 3091 New->getDeclContext()->getRedeclContext()) && 3092 !(isExternC(Old) && isExternC(New))) 3093 Old = nullptr; 3094 3095 if (!Old) { 3096 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 3097 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 3098 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 3099 return true; 3100 } 3101 return false; 3102 } 3103 3104 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 3105 const FunctionDecl *B) { 3106 assert(A->getNumParams() == B->getNumParams()); 3107 3108 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 3109 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 3110 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 3111 if (AttrA == AttrB) 3112 return true; 3113 return AttrA && AttrB && AttrA->getType() == AttrB->getType() && 3114 AttrA->isDynamic() == AttrB->isDynamic(); 3115 }; 3116 3117 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 3118 } 3119 3120 /// If necessary, adjust the semantic declaration context for a qualified 3121 /// declaration to name the correct inline namespace within the qualifier. 3122 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, 3123 DeclaratorDecl *OldD) { 3124 // The only case where we need to update the DeclContext is when 3125 // redeclaration lookup for a qualified name finds a declaration 3126 // in an inline namespace within the context named by the qualifier: 3127 // 3128 // inline namespace N { int f(); } 3129 // int ::f(); // Sema DC needs adjusting from :: to N::. 3130 // 3131 // For unqualified declarations, the semantic context *can* change 3132 // along the redeclaration chain (for local extern declarations, 3133 // extern "C" declarations, and friend declarations in particular). 3134 if (!NewD->getQualifier()) 3135 return; 3136 3137 // NewD is probably already in the right context. 3138 auto *NamedDC = NewD->getDeclContext()->getRedeclContext(); 3139 auto *SemaDC = OldD->getDeclContext()->getRedeclContext(); 3140 if (NamedDC->Equals(SemaDC)) 3141 return; 3142 3143 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || 3144 NewD->isInvalidDecl() || OldD->isInvalidDecl()) && 3145 "unexpected context for redeclaration"); 3146 3147 auto *LexDC = NewD->getLexicalDeclContext(); 3148 auto FixSemaDC = [=](NamedDecl *D) { 3149 if (!D) 3150 return; 3151 D->setDeclContext(SemaDC); 3152 D->setLexicalDeclContext(LexDC); 3153 }; 3154 3155 FixSemaDC(NewD); 3156 if (auto *FD = dyn_cast<FunctionDecl>(NewD)) 3157 FixSemaDC(FD->getDescribedFunctionTemplate()); 3158 else if (auto *VD = dyn_cast<VarDecl>(NewD)) 3159 FixSemaDC(VD->getDescribedVarTemplate()); 3160 } 3161 3162 /// MergeFunctionDecl - We just parsed a function 'New' from 3163 /// declarator D which has the same name and scope as a previous 3164 /// declaration 'Old'. Figure out how to resolve this situation, 3165 /// merging decls or emitting diagnostics as appropriate. 3166 /// 3167 /// In C++, New and Old must be declarations that are not 3168 /// overloaded. Use IsOverload to determine whether New and Old are 3169 /// overloaded, and to select the Old declaration that New should be 3170 /// merged with. 3171 /// 3172 /// Returns true if there was an error, false otherwise. 3173 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 3174 Scope *S, bool MergeTypeWithOld) { 3175 // Verify the old decl was also a function. 3176 FunctionDecl *Old = OldD->getAsFunction(); 3177 if (!Old) { 3178 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 3179 if (New->getFriendObjectKind()) { 3180 Diag(New->getLocation(), diag::err_using_decl_friend); 3181 Diag(Shadow->getTargetDecl()->getLocation(), 3182 diag::note_using_decl_target); 3183 Diag(Shadow->getUsingDecl()->getLocation(), 3184 diag::note_using_decl) << 0; 3185 return true; 3186 } 3187 3188 // Check whether the two declarations might declare the same function. 3189 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 3190 return true; 3191 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 3192 } else { 3193 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3194 << New->getDeclName(); 3195 notePreviousDefinition(OldD, New->getLocation()); 3196 return true; 3197 } 3198 } 3199 3200 // If the old declaration is invalid, just give up here. 3201 if (Old->isInvalidDecl()) 3202 return true; 3203 3204 // Disallow redeclaration of some builtins. 3205 if (!getASTContext().canBuiltinBeRedeclared(Old)) { 3206 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName(); 3207 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 3208 << Old << Old->getType(); 3209 return true; 3210 } 3211 3212 diag::kind PrevDiag; 3213 SourceLocation OldLocation; 3214 std::tie(PrevDiag, OldLocation) = 3215 getNoteDiagForInvalidRedeclaration(Old, New); 3216 3217 // Don't complain about this if we're in GNU89 mode and the old function 3218 // is an extern inline function. 3219 // Don't complain about specializations. They are not supposed to have 3220 // storage classes. 3221 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 3222 New->getStorageClass() == SC_Static && 3223 Old->hasExternalFormalLinkage() && 3224 !New->getTemplateSpecializationInfo() && 3225 !canRedefineFunction(Old, getLangOpts())) { 3226 if (getLangOpts().MicrosoftExt) { 3227 Diag(New->getLocation(), diag::ext_static_non_static) << New; 3228 Diag(OldLocation, PrevDiag); 3229 } else { 3230 Diag(New->getLocation(), diag::err_static_non_static) << New; 3231 Diag(OldLocation, PrevDiag); 3232 return true; 3233 } 3234 } 3235 3236 if (New->hasAttr<InternalLinkageAttr>() && 3237 !Old->hasAttr<InternalLinkageAttr>()) { 3238 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3239 << New->getDeclName(); 3240 notePreviousDefinition(Old, New->getLocation()); 3241 New->dropAttr<InternalLinkageAttr>(); 3242 } 3243 3244 if (CheckRedeclarationModuleOwnership(New, Old)) 3245 return true; 3246 3247 if (!getLangOpts().CPlusPlus) { 3248 bool OldOvl = Old->hasAttr<OverloadableAttr>(); 3249 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { 3250 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) 3251 << New << OldOvl; 3252 3253 // Try our best to find a decl that actually has the overloadable 3254 // attribute for the note. In most cases (e.g. programs with only one 3255 // broken declaration/definition), this won't matter. 3256 // 3257 // FIXME: We could do this if we juggled some extra state in 3258 // OverloadableAttr, rather than just removing it. 3259 const Decl *DiagOld = Old; 3260 if (OldOvl) { 3261 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { 3262 const auto *A = D->getAttr<OverloadableAttr>(); 3263 return A && !A->isImplicit(); 3264 }); 3265 // If we've implicitly added *all* of the overloadable attrs to this 3266 // chain, emitting a "previous redecl" note is pointless. 3267 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; 3268 } 3269 3270 if (DiagOld) 3271 Diag(DiagOld->getLocation(), 3272 diag::note_attribute_overloadable_prev_overload) 3273 << OldOvl; 3274 3275 if (OldOvl) 3276 New->addAttr(OverloadableAttr::CreateImplicit(Context)); 3277 else 3278 New->dropAttr<OverloadableAttr>(); 3279 } 3280 } 3281 3282 // If a function is first declared with a calling convention, but is later 3283 // declared or defined without one, all following decls assume the calling 3284 // convention of the first. 3285 // 3286 // It's OK if a function is first declared without a calling convention, 3287 // but is later declared or defined with the default calling convention. 3288 // 3289 // To test if either decl has an explicit calling convention, we look for 3290 // AttributedType sugar nodes on the type as written. If they are missing or 3291 // were canonicalized away, we assume the calling convention was implicit. 3292 // 3293 // Note also that we DO NOT return at this point, because we still have 3294 // other tests to run. 3295 QualType OldQType = Context.getCanonicalType(Old->getType()); 3296 QualType NewQType = Context.getCanonicalType(New->getType()); 3297 const FunctionType *OldType = cast<FunctionType>(OldQType); 3298 const FunctionType *NewType = cast<FunctionType>(NewQType); 3299 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 3300 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 3301 bool RequiresAdjustment = false; 3302 3303 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 3304 FunctionDecl *First = Old->getFirstDecl(); 3305 const FunctionType *FT = 3306 First->getType().getCanonicalType()->castAs<FunctionType>(); 3307 FunctionType::ExtInfo FI = FT->getExtInfo(); 3308 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 3309 if (!NewCCExplicit) { 3310 // Inherit the CC from the previous declaration if it was specified 3311 // there but not here. 3312 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3313 RequiresAdjustment = true; 3314 } else if (New->getBuiltinID()) { 3315 // Calling Conventions on a Builtin aren't really useful and setting a 3316 // default calling convention and cdecl'ing some builtin redeclarations is 3317 // common, so warn and ignore the calling convention on the redeclaration. 3318 Diag(New->getLocation(), diag::warn_cconv_unsupported) 3319 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3320 << (int)CallingConventionIgnoredReason::BuiltinFunction; 3321 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3322 RequiresAdjustment = true; 3323 } else { 3324 // Calling conventions aren't compatible, so complain. 3325 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 3326 Diag(New->getLocation(), diag::err_cconv_change) 3327 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3328 << !FirstCCExplicit 3329 << (!FirstCCExplicit ? "" : 3330 FunctionType::getNameForCallConv(FI.getCC())); 3331 3332 // Put the note on the first decl, since it is the one that matters. 3333 Diag(First->getLocation(), diag::note_previous_declaration); 3334 return true; 3335 } 3336 } 3337 3338 // FIXME: diagnose the other way around? 3339 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 3340 NewTypeInfo = NewTypeInfo.withNoReturn(true); 3341 RequiresAdjustment = true; 3342 } 3343 3344 // Merge regparm attribute. 3345 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 3346 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 3347 if (NewTypeInfo.getHasRegParm()) { 3348 Diag(New->getLocation(), diag::err_regparm_mismatch) 3349 << NewType->getRegParmType() 3350 << OldType->getRegParmType(); 3351 Diag(OldLocation, diag::note_previous_declaration); 3352 return true; 3353 } 3354 3355 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 3356 RequiresAdjustment = true; 3357 } 3358 3359 // Merge ns_returns_retained attribute. 3360 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 3361 if (NewTypeInfo.getProducesResult()) { 3362 Diag(New->getLocation(), diag::err_function_attribute_mismatch) 3363 << "'ns_returns_retained'"; 3364 Diag(OldLocation, diag::note_previous_declaration); 3365 return true; 3366 } 3367 3368 NewTypeInfo = NewTypeInfo.withProducesResult(true); 3369 RequiresAdjustment = true; 3370 } 3371 3372 if (OldTypeInfo.getNoCallerSavedRegs() != 3373 NewTypeInfo.getNoCallerSavedRegs()) { 3374 if (NewTypeInfo.getNoCallerSavedRegs()) { 3375 AnyX86NoCallerSavedRegistersAttr *Attr = 3376 New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); 3377 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; 3378 Diag(OldLocation, diag::note_previous_declaration); 3379 return true; 3380 } 3381 3382 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); 3383 RequiresAdjustment = true; 3384 } 3385 3386 if (RequiresAdjustment) { 3387 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 3388 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 3389 New->setType(QualType(AdjustedType, 0)); 3390 NewQType = Context.getCanonicalType(New->getType()); 3391 } 3392 3393 // If this redeclaration makes the function inline, we may need to add it to 3394 // UndefinedButUsed. 3395 if (!Old->isInlined() && New->isInlined() && 3396 !New->hasAttr<GNUInlineAttr>() && 3397 !getLangOpts().GNUInline && 3398 Old->isUsed(false) && 3399 !Old->isDefined() && !New->isThisDeclarationADefinition()) 3400 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3401 SourceLocation())); 3402 3403 // If this redeclaration makes it newly gnu_inline, we don't want to warn 3404 // about it. 3405 if (New->hasAttr<GNUInlineAttr>() && 3406 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 3407 UndefinedButUsed.erase(Old->getCanonicalDecl()); 3408 } 3409 3410 // If pass_object_size params don't match up perfectly, this isn't a valid 3411 // redeclaration. 3412 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 3413 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 3414 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 3415 << New->getDeclName(); 3416 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3417 return true; 3418 } 3419 3420 if (getLangOpts().CPlusPlus) { 3421 // C++1z [over.load]p2 3422 // Certain function declarations cannot be overloaded: 3423 // -- Function declarations that differ only in the return type, 3424 // the exception specification, or both cannot be overloaded. 3425 3426 // Check the exception specifications match. This may recompute the type of 3427 // both Old and New if it resolved exception specifications, so grab the 3428 // types again after this. Because this updates the type, we do this before 3429 // any of the other checks below, which may update the "de facto" NewQType 3430 // but do not necessarily update the type of New. 3431 if (CheckEquivalentExceptionSpec(Old, New)) 3432 return true; 3433 OldQType = Context.getCanonicalType(Old->getType()); 3434 NewQType = Context.getCanonicalType(New->getType()); 3435 3436 // Go back to the type source info to compare the declared return types, 3437 // per C++1y [dcl.type.auto]p13: 3438 // Redeclarations or specializations of a function or function template 3439 // with a declared return type that uses a placeholder type shall also 3440 // use that placeholder, not a deduced type. 3441 QualType OldDeclaredReturnType = Old->getDeclaredReturnType(); 3442 QualType NewDeclaredReturnType = New->getDeclaredReturnType(); 3443 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 3444 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType, 3445 OldDeclaredReturnType)) { 3446 QualType ResQT; 3447 if (NewDeclaredReturnType->isObjCObjectPointerType() && 3448 OldDeclaredReturnType->isObjCObjectPointerType()) 3449 // FIXME: This does the wrong thing for a deduced return type. 3450 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 3451 if (ResQT.isNull()) { 3452 if (New->isCXXClassMember() && New->isOutOfLine()) 3453 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 3454 << New << New->getReturnTypeSourceRange(); 3455 else 3456 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 3457 << New->getReturnTypeSourceRange(); 3458 Diag(OldLocation, PrevDiag) << Old << Old->getType() 3459 << Old->getReturnTypeSourceRange(); 3460 return true; 3461 } 3462 else 3463 NewQType = ResQT; 3464 } 3465 3466 QualType OldReturnType = OldType->getReturnType(); 3467 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 3468 if (OldReturnType != NewReturnType) { 3469 // If this function has a deduced return type and has already been 3470 // defined, copy the deduced value from the old declaration. 3471 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 3472 if (OldAT && OldAT->isDeduced()) { 3473 New->setType( 3474 SubstAutoType(New->getType(), 3475 OldAT->isDependentType() ? Context.DependentTy 3476 : OldAT->getDeducedType())); 3477 NewQType = Context.getCanonicalType( 3478 SubstAutoType(NewQType, 3479 OldAT->isDependentType() ? Context.DependentTy 3480 : OldAT->getDeducedType())); 3481 } 3482 } 3483 3484 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 3485 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 3486 if (OldMethod && NewMethod) { 3487 // Preserve triviality. 3488 NewMethod->setTrivial(OldMethod->isTrivial()); 3489 3490 // MSVC allows explicit template specialization at class scope: 3491 // 2 CXXMethodDecls referring to the same function will be injected. 3492 // We don't want a redeclaration error. 3493 bool IsClassScopeExplicitSpecialization = 3494 OldMethod->isFunctionTemplateSpecialization() && 3495 NewMethod->isFunctionTemplateSpecialization(); 3496 bool isFriend = NewMethod->getFriendObjectKind(); 3497 3498 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 3499 !IsClassScopeExplicitSpecialization) { 3500 // -- Member function declarations with the same name and the 3501 // same parameter types cannot be overloaded if any of them 3502 // is a static member function declaration. 3503 if (OldMethod->isStatic() != NewMethod->isStatic()) { 3504 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 3505 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3506 return true; 3507 } 3508 3509 // C++ [class.mem]p1: 3510 // [...] A member shall not be declared twice in the 3511 // member-specification, except that a nested class or member 3512 // class template can be declared and then later defined. 3513 if (!inTemplateInstantiation()) { 3514 unsigned NewDiag; 3515 if (isa<CXXConstructorDecl>(OldMethod)) 3516 NewDiag = diag::err_constructor_redeclared; 3517 else if (isa<CXXDestructorDecl>(NewMethod)) 3518 NewDiag = diag::err_destructor_redeclared; 3519 else if (isa<CXXConversionDecl>(NewMethod)) 3520 NewDiag = diag::err_conv_function_redeclared; 3521 else 3522 NewDiag = diag::err_member_redeclared; 3523 3524 Diag(New->getLocation(), NewDiag); 3525 } else { 3526 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 3527 << New << New->getType(); 3528 } 3529 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3530 return true; 3531 3532 // Complain if this is an explicit declaration of a special 3533 // member that was initially declared implicitly. 3534 // 3535 // As an exception, it's okay to befriend such methods in order 3536 // to permit the implicit constructor/destructor/operator calls. 3537 } else if (OldMethod->isImplicit()) { 3538 if (isFriend) { 3539 NewMethod->setImplicit(); 3540 } else { 3541 Diag(NewMethod->getLocation(), 3542 diag::err_definition_of_implicitly_declared_member) 3543 << New << getSpecialMember(OldMethod); 3544 return true; 3545 } 3546 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 3547 Diag(NewMethod->getLocation(), 3548 diag::err_definition_of_explicitly_defaulted_member) 3549 << getSpecialMember(OldMethod); 3550 return true; 3551 } 3552 } 3553 3554 // C++11 [dcl.attr.noreturn]p1: 3555 // The first declaration of a function shall specify the noreturn 3556 // attribute if any declaration of that function specifies the noreturn 3557 // attribute. 3558 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 3559 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 3560 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 3561 Diag(Old->getFirstDecl()->getLocation(), 3562 diag::note_noreturn_missing_first_decl); 3563 } 3564 3565 // C++11 [dcl.attr.depend]p2: 3566 // The first declaration of a function shall specify the 3567 // carries_dependency attribute for its declarator-id if any declaration 3568 // of the function specifies the carries_dependency attribute. 3569 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 3570 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 3571 Diag(CDA->getLocation(), 3572 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 3573 Diag(Old->getFirstDecl()->getLocation(), 3574 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 3575 } 3576 3577 // (C++98 8.3.5p3): 3578 // All declarations for a function shall agree exactly in both the 3579 // return type and the parameter-type-list. 3580 // We also want to respect all the extended bits except noreturn. 3581 3582 // noreturn should now match unless the old type info didn't have it. 3583 QualType OldQTypeForComparison = OldQType; 3584 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3585 auto *OldType = OldQType->castAs<FunctionProtoType>(); 3586 const FunctionType *OldTypeForComparison 3587 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3588 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3589 assert(OldQTypeForComparison.isCanonical()); 3590 } 3591 3592 if (haveIncompatibleLanguageLinkages(Old, New)) { 3593 // As a special case, retain the language linkage from previous 3594 // declarations of a friend function as an extension. 3595 // 3596 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3597 // and is useful because there's otherwise no way to specify language 3598 // linkage within class scope. 3599 // 3600 // Check cautiously as the friend object kind isn't yet complete. 3601 if (New->getFriendObjectKind() != Decl::FOK_None) { 3602 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3603 Diag(OldLocation, PrevDiag); 3604 } else { 3605 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3606 Diag(OldLocation, PrevDiag); 3607 return true; 3608 } 3609 } 3610 3611 // If the function types are compatible, merge the declarations. Ignore the 3612 // exception specifier because it was already checked above in 3613 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics 3614 // about incompatible types under -fms-compatibility. 3615 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison, 3616 NewQType)) 3617 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3618 3619 // If the types are imprecise (due to dependent constructs in friends or 3620 // local extern declarations), it's OK if they differ. We'll check again 3621 // during instantiation. 3622 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType)) 3623 return false; 3624 3625 // Fall through for conflicting redeclarations and redefinitions. 3626 } 3627 3628 // C: Function types need to be compatible, not identical. This handles 3629 // duplicate function decls like "void f(int); void f(enum X);" properly. 3630 if (!getLangOpts().CPlusPlus && 3631 Context.typesAreCompatible(OldQType, NewQType)) { 3632 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 3633 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 3634 const FunctionProtoType *OldProto = nullptr; 3635 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 3636 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 3637 // The old declaration provided a function prototype, but the 3638 // new declaration does not. Merge in the prototype. 3639 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 3640 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 3641 NewQType = 3642 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 3643 OldProto->getExtProtoInfo()); 3644 New->setType(NewQType); 3645 New->setHasInheritedPrototype(); 3646 3647 // Synthesize parameters with the same types. 3648 SmallVector<ParmVarDecl*, 16> Params; 3649 for (const auto &ParamType : OldProto->param_types()) { 3650 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 3651 SourceLocation(), nullptr, 3652 ParamType, /*TInfo=*/nullptr, 3653 SC_None, nullptr); 3654 Param->setScopeInfo(0, Params.size()); 3655 Param->setImplicit(); 3656 Params.push_back(Param); 3657 } 3658 3659 New->setParams(Params); 3660 } 3661 3662 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3663 } 3664 3665 // Check if the function types are compatible when pointer size address 3666 // spaces are ignored. 3667 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType)) 3668 return false; 3669 3670 // GNU C permits a K&R definition to follow a prototype declaration 3671 // if the declared types of the parameters in the K&R definition 3672 // match the types in the prototype declaration, even when the 3673 // promoted types of the parameters from the K&R definition differ 3674 // from the types in the prototype. GCC then keeps the types from 3675 // the prototype. 3676 // 3677 // If a variadic prototype is followed by a non-variadic K&R definition, 3678 // the K&R definition becomes variadic. This is sort of an edge case, but 3679 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 3680 // C99 6.9.1p8. 3681 if (!getLangOpts().CPlusPlus && 3682 Old->hasPrototype() && !New->hasPrototype() && 3683 New->getType()->getAs<FunctionProtoType>() && 3684 Old->getNumParams() == New->getNumParams()) { 3685 SmallVector<QualType, 16> ArgTypes; 3686 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 3687 const FunctionProtoType *OldProto 3688 = Old->getType()->getAs<FunctionProtoType>(); 3689 const FunctionProtoType *NewProto 3690 = New->getType()->getAs<FunctionProtoType>(); 3691 3692 // Determine whether this is the GNU C extension. 3693 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 3694 NewProto->getReturnType()); 3695 bool LooseCompatible = !MergedReturn.isNull(); 3696 for (unsigned Idx = 0, End = Old->getNumParams(); 3697 LooseCompatible && Idx != End; ++Idx) { 3698 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 3699 ParmVarDecl *NewParm = New->getParamDecl(Idx); 3700 if (Context.typesAreCompatible(OldParm->getType(), 3701 NewProto->getParamType(Idx))) { 3702 ArgTypes.push_back(NewParm->getType()); 3703 } else if (Context.typesAreCompatible(OldParm->getType(), 3704 NewParm->getType(), 3705 /*CompareUnqualified=*/true)) { 3706 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 3707 NewProto->getParamType(Idx) }; 3708 Warnings.push_back(Warn); 3709 ArgTypes.push_back(NewParm->getType()); 3710 } else 3711 LooseCompatible = false; 3712 } 3713 3714 if (LooseCompatible) { 3715 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 3716 Diag(Warnings[Warn].NewParm->getLocation(), 3717 diag::ext_param_promoted_not_compatible_with_prototype) 3718 << Warnings[Warn].PromotedType 3719 << Warnings[Warn].OldParm->getType(); 3720 if (Warnings[Warn].OldParm->getLocation().isValid()) 3721 Diag(Warnings[Warn].OldParm->getLocation(), 3722 diag::note_previous_declaration); 3723 } 3724 3725 if (MergeTypeWithOld) 3726 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 3727 OldProto->getExtProtoInfo())); 3728 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3729 } 3730 3731 // Fall through to diagnose conflicting types. 3732 } 3733 3734 // A function that has already been declared has been redeclared or 3735 // defined with a different type; show an appropriate diagnostic. 3736 3737 // If the previous declaration was an implicitly-generated builtin 3738 // declaration, then at the very least we should use a specialized note. 3739 unsigned BuiltinID; 3740 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3741 // If it's actually a library-defined builtin function like 'malloc' 3742 // or 'printf', just warn about the incompatible redeclaration. 3743 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3744 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3745 Diag(OldLocation, diag::note_previous_builtin_declaration) 3746 << Old << Old->getType(); 3747 3748 // If this is a global redeclaration, just forget hereafter 3749 // about the "builtin-ness" of the function. 3750 // 3751 // Doing this for local extern declarations is problematic. If 3752 // the builtin declaration remains visible, a second invalid 3753 // local declaration will produce a hard error; if it doesn't 3754 // remain visible, a single bogus local redeclaration (which is 3755 // actually only a warning) could break all the downstream code. 3756 if (!New->getLexicalDeclContext()->isFunctionOrMethod()) 3757 New->getIdentifier()->revertBuiltin(); 3758 3759 return false; 3760 } 3761 3762 PrevDiag = diag::note_previous_builtin_declaration; 3763 } 3764 3765 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3766 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3767 return true; 3768 } 3769 3770 /// Completes the merge of two function declarations that are 3771 /// known to be compatible. 3772 /// 3773 /// This routine handles the merging of attributes and other 3774 /// properties of function declarations from the old declaration to 3775 /// the new declaration, once we know that New is in fact a 3776 /// redeclaration of Old. 3777 /// 3778 /// \returns false 3779 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3780 Scope *S, bool MergeTypeWithOld) { 3781 // Merge the attributes 3782 mergeDeclAttributes(New, Old); 3783 3784 // Merge "pure" flag. 3785 if (Old->isPure()) 3786 New->setPure(); 3787 3788 // Merge "used" flag. 3789 if (Old->getMostRecentDecl()->isUsed(false)) 3790 New->setIsUsed(); 3791 3792 // Merge attributes from the parameters. These can mismatch with K&R 3793 // declarations. 3794 if (New->getNumParams() == Old->getNumParams()) 3795 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 3796 ParmVarDecl *NewParam = New->getParamDecl(i); 3797 ParmVarDecl *OldParam = Old->getParamDecl(i); 3798 mergeParamDeclAttributes(NewParam, OldParam, *this); 3799 mergeParamDeclTypes(NewParam, OldParam, *this); 3800 } 3801 3802 if (getLangOpts().CPlusPlus) 3803 return MergeCXXFunctionDecl(New, Old, S); 3804 3805 // Merge the function types so the we get the composite types for the return 3806 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3807 // was visible. 3808 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3809 if (!Merged.isNull() && MergeTypeWithOld) 3810 New->setType(Merged); 3811 3812 return false; 3813 } 3814 3815 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3816 ObjCMethodDecl *oldMethod) { 3817 // Merge the attributes, including deprecated/unavailable 3818 AvailabilityMergeKind MergeKind = 3819 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 3820 ? AMK_ProtocolImplementation 3821 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3822 : AMK_Override; 3823 3824 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3825 3826 // Merge attributes from the parameters. 3827 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3828 oe = oldMethod->param_end(); 3829 for (ObjCMethodDecl::param_iterator 3830 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3831 ni != ne && oi != oe; ++ni, ++oi) 3832 mergeParamDeclAttributes(*ni, *oi, *this); 3833 3834 CheckObjCMethodOverride(newMethod, oldMethod); 3835 } 3836 3837 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 3838 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 3839 3840 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 3841 ? diag::err_redefinition_different_type 3842 : diag::err_redeclaration_different_type) 3843 << New->getDeclName() << New->getType() << Old->getType(); 3844 3845 diag::kind PrevDiag; 3846 SourceLocation OldLocation; 3847 std::tie(PrevDiag, OldLocation) 3848 = getNoteDiagForInvalidRedeclaration(Old, New); 3849 S.Diag(OldLocation, PrevDiag); 3850 New->setInvalidDecl(); 3851 } 3852 3853 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3854 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3855 /// emitting diagnostics as appropriate. 3856 /// 3857 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3858 /// to here in AddInitializerToDecl. We can't check them before the initializer 3859 /// is attached. 3860 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3861 bool MergeTypeWithOld) { 3862 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3863 return; 3864 3865 QualType MergedT; 3866 if (getLangOpts().CPlusPlus) { 3867 if (New->getType()->isUndeducedType()) { 3868 // We don't know what the new type is until the initializer is attached. 3869 return; 3870 } else if (Context.hasSameType(New->getType(), Old->getType())) { 3871 // These could still be something that needs exception specs checked. 3872 return MergeVarDeclExceptionSpecs(New, Old); 3873 } 3874 // C++ [basic.link]p10: 3875 // [...] the types specified by all declarations referring to a given 3876 // object or function shall be identical, except that declarations for an 3877 // array object can specify array types that differ by the presence or 3878 // absence of a major array bound (8.3.4). 3879 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 3880 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3881 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3882 3883 // We are merging a variable declaration New into Old. If it has an array 3884 // bound, and that bound differs from Old's bound, we should diagnose the 3885 // mismatch. 3886 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 3887 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 3888 PrevVD = PrevVD->getPreviousDecl()) { 3889 const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType()); 3890 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 3891 continue; 3892 3893 if (!Context.hasSameType(NewArray, PrevVDTy)) 3894 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 3895 } 3896 } 3897 3898 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 3899 if (Context.hasSameType(OldArray->getElementType(), 3900 NewArray->getElementType())) 3901 MergedT = New->getType(); 3902 } 3903 // FIXME: Check visibility. New is hidden but has a complete type. If New 3904 // has no array bound, it should not inherit one from Old, if Old is not 3905 // visible. 3906 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 3907 if (Context.hasSameType(OldArray->getElementType(), 3908 NewArray->getElementType())) 3909 MergedT = Old->getType(); 3910 } 3911 } 3912 else if (New->getType()->isObjCObjectPointerType() && 3913 Old->getType()->isObjCObjectPointerType()) { 3914 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 3915 Old->getType()); 3916 } 3917 } else { 3918 // C 6.2.7p2: 3919 // All declarations that refer to the same object or function shall have 3920 // compatible type. 3921 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 3922 } 3923 if (MergedT.isNull()) { 3924 // It's OK if we couldn't merge types if either type is dependent, for a 3925 // block-scope variable. In other cases (static data members of class 3926 // templates, variable templates, ...), we require the types to be 3927 // equivalent. 3928 // FIXME: The C++ standard doesn't say anything about this. 3929 if ((New->getType()->isDependentType() || 3930 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 3931 // If the old type was dependent, we can't merge with it, so the new type 3932 // becomes dependent for now. We'll reproduce the original type when we 3933 // instantiate the TypeSourceInfo for the variable. 3934 if (!New->getType()->isDependentType() && MergeTypeWithOld) 3935 New->setType(Context.DependentTy); 3936 return; 3937 } 3938 return diagnoseVarDeclTypeMismatch(*this, New, Old); 3939 } 3940 3941 // Don't actually update the type on the new declaration if the old 3942 // declaration was an extern declaration in a different scope. 3943 if (MergeTypeWithOld) 3944 New->setType(MergedT); 3945 } 3946 3947 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 3948 LookupResult &Previous) { 3949 // C11 6.2.7p4: 3950 // For an identifier with internal or external linkage declared 3951 // in a scope in which a prior declaration of that identifier is 3952 // visible, if the prior declaration specifies internal or 3953 // external linkage, the type of the identifier at the later 3954 // declaration becomes the composite type. 3955 // 3956 // If the variable isn't visible, we do not merge with its type. 3957 if (Previous.isShadowed()) 3958 return false; 3959 3960 if (S.getLangOpts().CPlusPlus) { 3961 // C++11 [dcl.array]p3: 3962 // If there is a preceding declaration of the entity in the same 3963 // scope in which the bound was specified, an omitted array bound 3964 // is taken to be the same as in that earlier declaration. 3965 return NewVD->isPreviousDeclInSameBlockScope() || 3966 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 3967 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 3968 } else { 3969 // If the old declaration was function-local, don't merge with its 3970 // type unless we're in the same function. 3971 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 3972 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 3973 } 3974 } 3975 3976 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 3977 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 3978 /// situation, merging decls or emitting diagnostics as appropriate. 3979 /// 3980 /// Tentative definition rules (C99 6.9.2p2) are checked by 3981 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 3982 /// definitions here, since the initializer hasn't been attached. 3983 /// 3984 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 3985 // If the new decl is already invalid, don't do any other checking. 3986 if (New->isInvalidDecl()) 3987 return; 3988 3989 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 3990 return; 3991 3992 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 3993 3994 // Verify the old decl was also a variable or variable template. 3995 VarDecl *Old = nullptr; 3996 VarTemplateDecl *OldTemplate = nullptr; 3997 if (Previous.isSingleResult()) { 3998 if (NewTemplate) { 3999 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 4000 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 4001 4002 if (auto *Shadow = 4003 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4004 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 4005 return New->setInvalidDecl(); 4006 } else { 4007 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 4008 4009 if (auto *Shadow = 4010 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4011 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 4012 return New->setInvalidDecl(); 4013 } 4014 } 4015 if (!Old) { 4016 Diag(New->getLocation(), diag::err_redefinition_different_kind) 4017 << New->getDeclName(); 4018 notePreviousDefinition(Previous.getRepresentativeDecl(), 4019 New->getLocation()); 4020 return New->setInvalidDecl(); 4021 } 4022 4023 // Ensure the template parameters are compatible. 4024 if (NewTemplate && 4025 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 4026 OldTemplate->getTemplateParameters(), 4027 /*Complain=*/true, TPL_TemplateMatch)) 4028 return New->setInvalidDecl(); 4029 4030 // C++ [class.mem]p1: 4031 // A member shall not be declared twice in the member-specification [...] 4032 // 4033 // Here, we need only consider static data members. 4034 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 4035 Diag(New->getLocation(), diag::err_duplicate_member) 4036 << New->getIdentifier(); 4037 Diag(Old->getLocation(), diag::note_previous_declaration); 4038 New->setInvalidDecl(); 4039 } 4040 4041 mergeDeclAttributes(New, Old); 4042 // Warn if an already-declared variable is made a weak_import in a subsequent 4043 // declaration 4044 if (New->hasAttr<WeakImportAttr>() && 4045 Old->getStorageClass() == SC_None && 4046 !Old->hasAttr<WeakImportAttr>()) { 4047 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 4048 notePreviousDefinition(Old, New->getLocation()); 4049 // Remove weak_import attribute on new declaration. 4050 New->dropAttr<WeakImportAttr>(); 4051 } 4052 4053 if (New->hasAttr<InternalLinkageAttr>() && 4054 !Old->hasAttr<InternalLinkageAttr>()) { 4055 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 4056 << New->getDeclName(); 4057 notePreviousDefinition(Old, New->getLocation()); 4058 New->dropAttr<InternalLinkageAttr>(); 4059 } 4060 4061 // Merge the types. 4062 VarDecl *MostRecent = Old->getMostRecentDecl(); 4063 if (MostRecent != Old) { 4064 MergeVarDeclTypes(New, MostRecent, 4065 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 4066 if (New->isInvalidDecl()) 4067 return; 4068 } 4069 4070 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 4071 if (New->isInvalidDecl()) 4072 return; 4073 4074 diag::kind PrevDiag; 4075 SourceLocation OldLocation; 4076 std::tie(PrevDiag, OldLocation) = 4077 getNoteDiagForInvalidRedeclaration(Old, New); 4078 4079 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 4080 if (New->getStorageClass() == SC_Static && 4081 !New->isStaticDataMember() && 4082 Old->hasExternalFormalLinkage()) { 4083 if (getLangOpts().MicrosoftExt) { 4084 Diag(New->getLocation(), diag::ext_static_non_static) 4085 << New->getDeclName(); 4086 Diag(OldLocation, PrevDiag); 4087 } else { 4088 Diag(New->getLocation(), diag::err_static_non_static) 4089 << New->getDeclName(); 4090 Diag(OldLocation, PrevDiag); 4091 return New->setInvalidDecl(); 4092 } 4093 } 4094 // C99 6.2.2p4: 4095 // For an identifier declared with the storage-class specifier 4096 // extern in a scope in which a prior declaration of that 4097 // identifier is visible,23) if the prior declaration specifies 4098 // internal or external linkage, the linkage of the identifier at 4099 // the later declaration is the same as the linkage specified at 4100 // the prior declaration. If no prior declaration is visible, or 4101 // if the prior declaration specifies no linkage, then the 4102 // identifier has external linkage. 4103 if (New->hasExternalStorage() && Old->hasLinkage()) 4104 /* Okay */; 4105 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 4106 !New->isStaticDataMember() && 4107 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 4108 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 4109 Diag(OldLocation, PrevDiag); 4110 return New->setInvalidDecl(); 4111 } 4112 4113 // Check if extern is followed by non-extern and vice-versa. 4114 if (New->hasExternalStorage() && 4115 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 4116 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 4117 Diag(OldLocation, PrevDiag); 4118 return New->setInvalidDecl(); 4119 } 4120 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 4121 !New->hasExternalStorage()) { 4122 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 4123 Diag(OldLocation, PrevDiag); 4124 return New->setInvalidDecl(); 4125 } 4126 4127 if (CheckRedeclarationModuleOwnership(New, Old)) 4128 return; 4129 4130 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 4131 4132 // FIXME: The test for external storage here seems wrong? We still 4133 // need to check for mismatches. 4134 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 4135 // Don't complain about out-of-line definitions of static members. 4136 !(Old->getLexicalDeclContext()->isRecord() && 4137 !New->getLexicalDeclContext()->isRecord())) { 4138 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 4139 Diag(OldLocation, PrevDiag); 4140 return New->setInvalidDecl(); 4141 } 4142 4143 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 4144 if (VarDecl *Def = Old->getDefinition()) { 4145 // C++1z [dcl.fcn.spec]p4: 4146 // If the definition of a variable appears in a translation unit before 4147 // its first declaration as inline, the program is ill-formed. 4148 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 4149 Diag(Def->getLocation(), diag::note_previous_definition); 4150 } 4151 } 4152 4153 // If this redeclaration makes the variable inline, we may need to add it to 4154 // UndefinedButUsed. 4155 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 4156 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 4157 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 4158 SourceLocation())); 4159 4160 if (New->getTLSKind() != Old->getTLSKind()) { 4161 if (!Old->getTLSKind()) { 4162 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 4163 Diag(OldLocation, PrevDiag); 4164 } else if (!New->getTLSKind()) { 4165 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 4166 Diag(OldLocation, PrevDiag); 4167 } else { 4168 // Do not allow redeclaration to change the variable between requiring 4169 // static and dynamic initialization. 4170 // FIXME: GCC allows this, but uses the TLS keyword on the first 4171 // declaration to determine the kind. Do we need to be compatible here? 4172 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 4173 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 4174 Diag(OldLocation, PrevDiag); 4175 } 4176 } 4177 4178 // C++ doesn't have tentative definitions, so go right ahead and check here. 4179 if (getLangOpts().CPlusPlus && 4180 New->isThisDeclarationADefinition() == VarDecl::Definition) { 4181 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 4182 Old->getCanonicalDecl()->isConstexpr()) { 4183 // This definition won't be a definition any more once it's been merged. 4184 Diag(New->getLocation(), 4185 diag::warn_deprecated_redundant_constexpr_static_def); 4186 } else if (VarDecl *Def = Old->getDefinition()) { 4187 if (checkVarDeclRedefinition(Def, New)) 4188 return; 4189 } 4190 } 4191 4192 if (haveIncompatibleLanguageLinkages(Old, New)) { 4193 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 4194 Diag(OldLocation, PrevDiag); 4195 New->setInvalidDecl(); 4196 return; 4197 } 4198 4199 // Merge "used" flag. 4200 if (Old->getMostRecentDecl()->isUsed(false)) 4201 New->setIsUsed(); 4202 4203 // Keep a chain of previous declarations. 4204 New->setPreviousDecl(Old); 4205 if (NewTemplate) 4206 NewTemplate->setPreviousDecl(OldTemplate); 4207 adjustDeclContextForDeclaratorDecl(New, Old); 4208 4209 // Inherit access appropriately. 4210 New->setAccess(Old->getAccess()); 4211 if (NewTemplate) 4212 NewTemplate->setAccess(New->getAccess()); 4213 4214 if (Old->isInline()) 4215 New->setImplicitlyInline(); 4216 } 4217 4218 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { 4219 SourceManager &SrcMgr = getSourceManager(); 4220 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); 4221 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); 4222 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); 4223 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); 4224 auto &HSI = PP.getHeaderSearchInfo(); 4225 StringRef HdrFilename = 4226 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); 4227 4228 auto noteFromModuleOrInclude = [&](Module *Mod, 4229 SourceLocation IncLoc) -> bool { 4230 // Redefinition errors with modules are common with non modular mapped 4231 // headers, example: a non-modular header H in module A that also gets 4232 // included directly in a TU. Pointing twice to the same header/definition 4233 // is confusing, try to get better diagnostics when modules is on. 4234 if (IncLoc.isValid()) { 4235 if (Mod) { 4236 Diag(IncLoc, diag::note_redefinition_modules_same_file) 4237 << HdrFilename.str() << Mod->getFullModuleName(); 4238 if (!Mod->DefinitionLoc.isInvalid()) 4239 Diag(Mod->DefinitionLoc, diag::note_defined_here) 4240 << Mod->getFullModuleName(); 4241 } else { 4242 Diag(IncLoc, diag::note_redefinition_include_same_file) 4243 << HdrFilename.str(); 4244 } 4245 return true; 4246 } 4247 4248 return false; 4249 }; 4250 4251 // Is it the same file and same offset? Provide more information on why 4252 // this leads to a redefinition error. 4253 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { 4254 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); 4255 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); 4256 bool EmittedDiag = 4257 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); 4258 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); 4259 4260 // If the header has no guards, emit a note suggesting one. 4261 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) 4262 Diag(Old->getLocation(), diag::note_use_ifdef_guards); 4263 4264 if (EmittedDiag) 4265 return; 4266 } 4267 4268 // Redefinition coming from different files or couldn't do better above. 4269 if (Old->getLocation().isValid()) 4270 Diag(Old->getLocation(), diag::note_previous_definition); 4271 } 4272 4273 /// We've just determined that \p Old and \p New both appear to be definitions 4274 /// of the same variable. Either diagnose or fix the problem. 4275 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 4276 if (!hasVisibleDefinition(Old) && 4277 (New->getFormalLinkage() == InternalLinkage || 4278 New->isInline() || 4279 New->getDescribedVarTemplate() || 4280 New->getNumTemplateParameterLists() || 4281 New->getDeclContext()->isDependentContext())) { 4282 // The previous definition is hidden, and multiple definitions are 4283 // permitted (in separate TUs). Demote this to a declaration. 4284 New->demoteThisDefinitionToDeclaration(); 4285 4286 // Make the canonical definition visible. 4287 if (auto *OldTD = Old->getDescribedVarTemplate()) 4288 makeMergedDefinitionVisible(OldTD); 4289 makeMergedDefinitionVisible(Old); 4290 return false; 4291 } else { 4292 Diag(New->getLocation(), diag::err_redefinition) << New; 4293 notePreviousDefinition(Old, New->getLocation()); 4294 New->setInvalidDecl(); 4295 return true; 4296 } 4297 } 4298 4299 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4300 /// no declarator (e.g. "struct foo;") is parsed. 4301 Decl * 4302 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4303 RecordDecl *&AnonRecord) { 4304 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, 4305 AnonRecord); 4306 } 4307 4308 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 4309 // disambiguate entities defined in different scopes. 4310 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 4311 // compatibility. 4312 // We will pick our mangling number depending on which version of MSVC is being 4313 // targeted. 4314 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 4315 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 4316 ? S->getMSCurManglingNumber() 4317 : S->getMSLastManglingNumber(); 4318 } 4319 4320 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 4321 if (!Context.getLangOpts().CPlusPlus) 4322 return; 4323 4324 if (isa<CXXRecordDecl>(Tag->getParent())) { 4325 // If this tag is the direct child of a class, number it if 4326 // it is anonymous. 4327 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 4328 return; 4329 MangleNumberingContext &MCtx = 4330 Context.getManglingNumberContext(Tag->getParent()); 4331 Context.setManglingNumber( 4332 Tag, MCtx.getManglingNumber( 4333 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4334 return; 4335 } 4336 4337 // If this tag isn't a direct child of a class, number it if it is local. 4338 MangleNumberingContext *MCtx; 4339 Decl *ManglingContextDecl; 4340 std::tie(MCtx, ManglingContextDecl) = 4341 getCurrentMangleNumberContext(Tag->getDeclContext()); 4342 if (MCtx) { 4343 Context.setManglingNumber( 4344 Tag, MCtx->getManglingNumber( 4345 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4346 } 4347 } 4348 4349 namespace { 4350 struct NonCLikeKind { 4351 enum { 4352 None, 4353 BaseClass, 4354 DefaultMemberInit, 4355 Lambda, 4356 Friend, 4357 OtherMember, 4358 Invalid, 4359 } Kind = None; 4360 SourceRange Range; 4361 4362 explicit operator bool() { return Kind != None; } 4363 }; 4364 } 4365 4366 /// Determine whether a class is C-like, according to the rules of C++ 4367 /// [dcl.typedef] for anonymous classes with typedef names for linkage. 4368 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) { 4369 if (RD->isInvalidDecl()) 4370 return {NonCLikeKind::Invalid, {}}; 4371 4372 // C++ [dcl.typedef]p9: [P1766R1] 4373 // An unnamed class with a typedef name for linkage purposes shall not 4374 // 4375 // -- have any base classes 4376 if (RD->getNumBases()) 4377 return {NonCLikeKind::BaseClass, 4378 SourceRange(RD->bases_begin()->getBeginLoc(), 4379 RD->bases_end()[-1].getEndLoc())}; 4380 bool Invalid = false; 4381 for (Decl *D : RD->decls()) { 4382 // Don't complain about things we already diagnosed. 4383 if (D->isInvalidDecl()) { 4384 Invalid = true; 4385 continue; 4386 } 4387 4388 // -- have any [...] default member initializers 4389 if (auto *FD = dyn_cast<FieldDecl>(D)) { 4390 if (FD->hasInClassInitializer()) { 4391 auto *Init = FD->getInClassInitializer(); 4392 return {NonCLikeKind::DefaultMemberInit, 4393 Init ? Init->getSourceRange() : D->getSourceRange()}; 4394 } 4395 continue; 4396 } 4397 4398 // FIXME: We don't allow friend declarations. This violates the wording of 4399 // P1766, but not the intent. 4400 if (isa<FriendDecl>(D)) 4401 return {NonCLikeKind::Friend, D->getSourceRange()}; 4402 4403 // -- declare any members other than non-static data members, member 4404 // enumerations, or member classes, 4405 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) || 4406 isa<EnumDecl>(D)) 4407 continue; 4408 auto *MemberRD = dyn_cast<CXXRecordDecl>(D); 4409 if (!MemberRD) 4410 return {NonCLikeKind::OtherMember, D->getSourceRange()}; 4411 4412 // -- contain a lambda-expression, 4413 if (MemberRD->isLambda()) 4414 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()}; 4415 4416 // and all member classes shall also satisfy these requirements 4417 // (recursively). 4418 if (MemberRD->isThisDeclarationADefinition()) { 4419 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD)) 4420 return Kind; 4421 } 4422 } 4423 4424 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}}; 4425 } 4426 4427 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 4428 TypedefNameDecl *NewTD) { 4429 if (TagFromDeclSpec->isInvalidDecl()) 4430 return; 4431 4432 // Do nothing if the tag already has a name for linkage purposes. 4433 if (TagFromDeclSpec->hasNameForLinkage()) 4434 return; 4435 4436 // A well-formed anonymous tag must always be a TUK_Definition. 4437 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 4438 4439 // The type must match the tag exactly; no qualifiers allowed. 4440 if (!Context.hasSameType(NewTD->getUnderlyingType(), 4441 Context.getTagDeclType(TagFromDeclSpec))) { 4442 if (getLangOpts().CPlusPlus) 4443 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 4444 return; 4445 } 4446 4447 // C++ [dcl.typedef]p9: [P1766R1, applied as DR] 4448 // An unnamed class with a typedef name for linkage purposes shall [be 4449 // C-like]. 4450 // 4451 // FIXME: Also diagnose if we've already computed the linkage. That ideally 4452 // shouldn't happen, but there are constructs that the language rule doesn't 4453 // disallow for which we can't reasonably avoid computing linkage early. 4454 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec); 4455 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD) 4456 : NonCLikeKind(); 4457 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed(); 4458 if (NonCLike || ChangesLinkage) { 4459 if (NonCLike.Kind == NonCLikeKind::Invalid) 4460 return; 4461 4462 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef; 4463 if (ChangesLinkage) { 4464 // If the linkage changes, we can't accept this as an extension. 4465 if (NonCLike.Kind == NonCLikeKind::None) 4466 DiagID = diag::err_typedef_changes_linkage; 4467 else 4468 DiagID = diag::err_non_c_like_anon_struct_in_typedef; 4469 } 4470 4471 SourceLocation FixitLoc = 4472 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart()); 4473 llvm::SmallString<40> TextToInsert; 4474 TextToInsert += ' '; 4475 TextToInsert += NewTD->getIdentifier()->getName(); 4476 4477 Diag(FixitLoc, DiagID) 4478 << isa<TypeAliasDecl>(NewTD) 4479 << FixItHint::CreateInsertion(FixitLoc, TextToInsert); 4480 if (NonCLike.Kind != NonCLikeKind::None) { 4481 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct) 4482 << NonCLike.Kind - 1 << NonCLike.Range; 4483 } 4484 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here) 4485 << NewTD << isa<TypeAliasDecl>(NewTD); 4486 4487 if (ChangesLinkage) 4488 return; 4489 } 4490 4491 // Otherwise, set this as the anon-decl typedef for the tag. 4492 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 4493 } 4494 4495 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 4496 switch (T) { 4497 case DeclSpec::TST_class: 4498 return 0; 4499 case DeclSpec::TST_struct: 4500 return 1; 4501 case DeclSpec::TST_interface: 4502 return 2; 4503 case DeclSpec::TST_union: 4504 return 3; 4505 case DeclSpec::TST_enum: 4506 return 4; 4507 default: 4508 llvm_unreachable("unexpected type specifier"); 4509 } 4510 } 4511 4512 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4513 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 4514 /// parameters to cope with template friend declarations. 4515 Decl * 4516 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4517 MultiTemplateParamsArg TemplateParams, 4518 bool IsExplicitInstantiation, 4519 RecordDecl *&AnonRecord) { 4520 Decl *TagD = nullptr; 4521 TagDecl *Tag = nullptr; 4522 if (DS.getTypeSpecType() == DeclSpec::TST_class || 4523 DS.getTypeSpecType() == DeclSpec::TST_struct || 4524 DS.getTypeSpecType() == DeclSpec::TST_interface || 4525 DS.getTypeSpecType() == DeclSpec::TST_union || 4526 DS.getTypeSpecType() == DeclSpec::TST_enum) { 4527 TagD = DS.getRepAsDecl(); 4528 4529 if (!TagD) // We probably had an error 4530 return nullptr; 4531 4532 // Note that the above type specs guarantee that the 4533 // type rep is a Decl, whereas in many of the others 4534 // it's a Type. 4535 if (isa<TagDecl>(TagD)) 4536 Tag = cast<TagDecl>(TagD); 4537 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 4538 Tag = CTD->getTemplatedDecl(); 4539 } 4540 4541 if (Tag) { 4542 handleTagNumbering(Tag, S); 4543 Tag->setFreeStanding(); 4544 if (Tag->isInvalidDecl()) 4545 return Tag; 4546 } 4547 4548 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 4549 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 4550 // or incomplete types shall not be restrict-qualified." 4551 if (TypeQuals & DeclSpec::TQ_restrict) 4552 Diag(DS.getRestrictSpecLoc(), 4553 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 4554 << DS.getSourceRange(); 4555 } 4556 4557 if (DS.isInlineSpecified()) 4558 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 4559 << getLangOpts().CPlusPlus17; 4560 4561 if (DS.hasConstexprSpecifier()) { 4562 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 4563 // and definitions of functions and variables. 4564 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to 4565 // the declaration of a function or function template 4566 if (Tag) 4567 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 4568 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) 4569 << DS.getConstexprSpecifier(); 4570 else 4571 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind) 4572 << DS.getConstexprSpecifier(); 4573 // Don't emit warnings after this error. 4574 return TagD; 4575 } 4576 4577 DiagnoseFunctionSpecifiers(DS); 4578 4579 if (DS.isFriendSpecified()) { 4580 // If we're dealing with a decl but not a TagDecl, assume that 4581 // whatever routines created it handled the friendship aspect. 4582 if (TagD && !Tag) 4583 return nullptr; 4584 return ActOnFriendTypeDecl(S, DS, TemplateParams); 4585 } 4586 4587 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 4588 bool IsExplicitSpecialization = 4589 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 4590 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 4591 !IsExplicitInstantiation && !IsExplicitSpecialization && 4592 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 4593 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 4594 // nested-name-specifier unless it is an explicit instantiation 4595 // or an explicit specialization. 4596 // 4597 // FIXME: We allow class template partial specializations here too, per the 4598 // obvious intent of DR1819. 4599 // 4600 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 4601 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 4602 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 4603 return nullptr; 4604 } 4605 4606 // Track whether this decl-specifier declares anything. 4607 bool DeclaresAnything = true; 4608 4609 // Handle anonymous struct definitions. 4610 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 4611 if (!Record->getDeclName() && Record->isCompleteDefinition() && 4612 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 4613 if (getLangOpts().CPlusPlus || 4614 Record->getDeclContext()->isRecord()) { 4615 // If CurContext is a DeclContext that can contain statements, 4616 // RecursiveASTVisitor won't visit the decls that 4617 // BuildAnonymousStructOrUnion() will put into CurContext. 4618 // Also store them here so that they can be part of the 4619 // DeclStmt that gets created in this case. 4620 // FIXME: Also return the IndirectFieldDecls created by 4621 // BuildAnonymousStructOr union, for the same reason? 4622 if (CurContext->isFunctionOrMethod()) 4623 AnonRecord = Record; 4624 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 4625 Context.getPrintingPolicy()); 4626 } 4627 4628 DeclaresAnything = false; 4629 } 4630 } 4631 4632 // C11 6.7.2.1p2: 4633 // A struct-declaration that does not declare an anonymous structure or 4634 // anonymous union shall contain a struct-declarator-list. 4635 // 4636 // This rule also existed in C89 and C99; the grammar for struct-declaration 4637 // did not permit a struct-declaration without a struct-declarator-list. 4638 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 4639 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 4640 // Check for Microsoft C extension: anonymous struct/union member. 4641 // Handle 2 kinds of anonymous struct/union: 4642 // struct STRUCT; 4643 // union UNION; 4644 // and 4645 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 4646 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 4647 if ((Tag && Tag->getDeclName()) || 4648 DS.getTypeSpecType() == DeclSpec::TST_typename) { 4649 RecordDecl *Record = nullptr; 4650 if (Tag) 4651 Record = dyn_cast<RecordDecl>(Tag); 4652 else if (const RecordType *RT = 4653 DS.getRepAsType().get()->getAsStructureType()) 4654 Record = RT->getDecl(); 4655 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 4656 Record = UT->getDecl(); 4657 4658 if (Record && getLangOpts().MicrosoftExt) { 4659 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record) 4660 << Record->isUnion() << DS.getSourceRange(); 4661 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 4662 } 4663 4664 DeclaresAnything = false; 4665 } 4666 } 4667 4668 // Skip all the checks below if we have a type error. 4669 if (DS.getTypeSpecType() == DeclSpec::TST_error || 4670 (TagD && TagD->isInvalidDecl())) 4671 return TagD; 4672 4673 if (getLangOpts().CPlusPlus && 4674 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 4675 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 4676 if (Enum->enumerator_begin() == Enum->enumerator_end() && 4677 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 4678 DeclaresAnything = false; 4679 4680 if (!DS.isMissingDeclaratorOk()) { 4681 // Customize diagnostic for a typedef missing a name. 4682 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 4683 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name) 4684 << DS.getSourceRange(); 4685 else 4686 DeclaresAnything = false; 4687 } 4688 4689 if (DS.isModulePrivateSpecified() && 4690 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 4691 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 4692 << Tag->getTagKind() 4693 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 4694 4695 ActOnDocumentableDecl(TagD); 4696 4697 // C 6.7/2: 4698 // A declaration [...] shall declare at least a declarator [...], a tag, 4699 // or the members of an enumeration. 4700 // C++ [dcl.dcl]p3: 4701 // [If there are no declarators], and except for the declaration of an 4702 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 4703 // names into the program, or shall redeclare a name introduced by a 4704 // previous declaration. 4705 if (!DeclaresAnything) { 4706 // In C, we allow this as a (popular) extension / bug. Don't bother 4707 // producing further diagnostics for redundant qualifiers after this. 4708 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); 4709 return TagD; 4710 } 4711 4712 // C++ [dcl.stc]p1: 4713 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 4714 // init-declarator-list of the declaration shall not be empty. 4715 // C++ [dcl.fct.spec]p1: 4716 // If a cv-qualifier appears in a decl-specifier-seq, the 4717 // init-declarator-list of the declaration shall not be empty. 4718 // 4719 // Spurious qualifiers here appear to be valid in C. 4720 unsigned DiagID = diag::warn_standalone_specifier; 4721 if (getLangOpts().CPlusPlus) 4722 DiagID = diag::ext_standalone_specifier; 4723 4724 // Note that a linkage-specification sets a storage class, but 4725 // 'extern "C" struct foo;' is actually valid and not theoretically 4726 // useless. 4727 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 4728 if (SCS == DeclSpec::SCS_mutable) 4729 // Since mutable is not a viable storage class specifier in C, there is 4730 // no reason to treat it as an extension. Instead, diagnose as an error. 4731 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 4732 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 4733 Diag(DS.getStorageClassSpecLoc(), DiagID) 4734 << DeclSpec::getSpecifierName(SCS); 4735 } 4736 4737 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 4738 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 4739 << DeclSpec::getSpecifierName(TSCS); 4740 if (DS.getTypeQualifiers()) { 4741 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4742 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 4743 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4744 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 4745 // Restrict is covered above. 4746 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4747 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 4748 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4749 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 4750 } 4751 4752 // Warn about ignored type attributes, for example: 4753 // __attribute__((aligned)) struct A; 4754 // Attributes should be placed after tag to apply to type declaration. 4755 if (!DS.getAttributes().empty()) { 4756 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 4757 if (TypeSpecType == DeclSpec::TST_class || 4758 TypeSpecType == DeclSpec::TST_struct || 4759 TypeSpecType == DeclSpec::TST_interface || 4760 TypeSpecType == DeclSpec::TST_union || 4761 TypeSpecType == DeclSpec::TST_enum) { 4762 for (const ParsedAttr &AL : DS.getAttributes()) 4763 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored) 4764 << AL << GetDiagnosticTypeSpecifierID(TypeSpecType); 4765 } 4766 } 4767 4768 return TagD; 4769 } 4770 4771 /// We are trying to inject an anonymous member into the given scope; 4772 /// check if there's an existing declaration that can't be overloaded. 4773 /// 4774 /// \return true if this is a forbidden redeclaration 4775 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 4776 Scope *S, 4777 DeclContext *Owner, 4778 DeclarationName Name, 4779 SourceLocation NameLoc, 4780 bool IsUnion) { 4781 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 4782 Sema::ForVisibleRedeclaration); 4783 if (!SemaRef.LookupName(R, S)) return false; 4784 4785 // Pick a representative declaration. 4786 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 4787 assert(PrevDecl && "Expected a non-null Decl"); 4788 4789 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 4790 return false; 4791 4792 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 4793 << IsUnion << Name; 4794 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4795 4796 return true; 4797 } 4798 4799 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 4800 /// anonymous struct or union AnonRecord into the owning context Owner 4801 /// and scope S. This routine will be invoked just after we realize 4802 /// that an unnamed union or struct is actually an anonymous union or 4803 /// struct, e.g., 4804 /// 4805 /// @code 4806 /// union { 4807 /// int i; 4808 /// float f; 4809 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 4810 /// // f into the surrounding scope.x 4811 /// @endcode 4812 /// 4813 /// This routine is recursive, injecting the names of nested anonymous 4814 /// structs/unions into the owning context and scope as well. 4815 static bool 4816 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 4817 RecordDecl *AnonRecord, AccessSpecifier AS, 4818 SmallVectorImpl<NamedDecl *> &Chaining) { 4819 bool Invalid = false; 4820 4821 // Look every FieldDecl and IndirectFieldDecl with a name. 4822 for (auto *D : AnonRecord->decls()) { 4823 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 4824 cast<NamedDecl>(D)->getDeclName()) { 4825 ValueDecl *VD = cast<ValueDecl>(D); 4826 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 4827 VD->getLocation(), 4828 AnonRecord->isUnion())) { 4829 // C++ [class.union]p2: 4830 // The names of the members of an anonymous union shall be 4831 // distinct from the names of any other entity in the 4832 // scope in which the anonymous union is declared. 4833 Invalid = true; 4834 } else { 4835 // C++ [class.union]p2: 4836 // For the purpose of name lookup, after the anonymous union 4837 // definition, the members of the anonymous union are 4838 // considered to have been defined in the scope in which the 4839 // anonymous union is declared. 4840 unsigned OldChainingSize = Chaining.size(); 4841 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 4842 Chaining.append(IF->chain_begin(), IF->chain_end()); 4843 else 4844 Chaining.push_back(VD); 4845 4846 assert(Chaining.size() >= 2); 4847 NamedDecl **NamedChain = 4848 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 4849 for (unsigned i = 0; i < Chaining.size(); i++) 4850 NamedChain[i] = Chaining[i]; 4851 4852 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 4853 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 4854 VD->getType(), {NamedChain, Chaining.size()}); 4855 4856 for (const auto *Attr : VD->attrs()) 4857 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 4858 4859 IndirectField->setAccess(AS); 4860 IndirectField->setImplicit(); 4861 SemaRef.PushOnScopeChains(IndirectField, S); 4862 4863 // That includes picking up the appropriate access specifier. 4864 if (AS != AS_none) IndirectField->setAccess(AS); 4865 4866 Chaining.resize(OldChainingSize); 4867 } 4868 } 4869 } 4870 4871 return Invalid; 4872 } 4873 4874 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 4875 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 4876 /// illegal input values are mapped to SC_None. 4877 static StorageClass 4878 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 4879 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 4880 assert(StorageClassSpec != DeclSpec::SCS_typedef && 4881 "Parser allowed 'typedef' as storage class VarDecl."); 4882 switch (StorageClassSpec) { 4883 case DeclSpec::SCS_unspecified: return SC_None; 4884 case DeclSpec::SCS_extern: 4885 if (DS.isExternInLinkageSpec()) 4886 return SC_None; 4887 return SC_Extern; 4888 case DeclSpec::SCS_static: return SC_Static; 4889 case DeclSpec::SCS_auto: return SC_Auto; 4890 case DeclSpec::SCS_register: return SC_Register; 4891 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 4892 // Illegal SCSs map to None: error reporting is up to the caller. 4893 case DeclSpec::SCS_mutable: // Fall through. 4894 case DeclSpec::SCS_typedef: return SC_None; 4895 } 4896 llvm_unreachable("unknown storage class specifier"); 4897 } 4898 4899 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 4900 assert(Record->hasInClassInitializer()); 4901 4902 for (const auto *I : Record->decls()) { 4903 const auto *FD = dyn_cast<FieldDecl>(I); 4904 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 4905 FD = IFD->getAnonField(); 4906 if (FD && FD->hasInClassInitializer()) 4907 return FD->getLocation(); 4908 } 4909 4910 llvm_unreachable("couldn't find in-class initializer"); 4911 } 4912 4913 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4914 SourceLocation DefaultInitLoc) { 4915 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4916 return; 4917 4918 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 4919 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 4920 } 4921 4922 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4923 CXXRecordDecl *AnonUnion) { 4924 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4925 return; 4926 4927 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 4928 } 4929 4930 /// BuildAnonymousStructOrUnion - Handle the declaration of an 4931 /// anonymous structure or union. Anonymous unions are a C++ feature 4932 /// (C++ [class.union]) and a C11 feature; anonymous structures 4933 /// are a C11 feature and GNU C++ extension. 4934 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 4935 AccessSpecifier AS, 4936 RecordDecl *Record, 4937 const PrintingPolicy &Policy) { 4938 DeclContext *Owner = Record->getDeclContext(); 4939 4940 // Diagnose whether this anonymous struct/union is an extension. 4941 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 4942 Diag(Record->getLocation(), diag::ext_anonymous_union); 4943 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 4944 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 4945 else if (!Record->isUnion() && !getLangOpts().C11) 4946 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 4947 4948 // C and C++ require different kinds of checks for anonymous 4949 // structs/unions. 4950 bool Invalid = false; 4951 if (getLangOpts().CPlusPlus) { 4952 const char *PrevSpec = nullptr; 4953 if (Record->isUnion()) { 4954 // C++ [class.union]p6: 4955 // C++17 [class.union.anon]p2: 4956 // Anonymous unions declared in a named namespace or in the 4957 // global namespace shall be declared static. 4958 unsigned DiagID; 4959 DeclContext *OwnerScope = Owner->getRedeclContext(); 4960 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 4961 (OwnerScope->isTranslationUnit() || 4962 (OwnerScope->isNamespace() && 4963 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) { 4964 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 4965 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 4966 4967 // Recover by adding 'static'. 4968 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 4969 PrevSpec, DiagID, Policy); 4970 } 4971 // C++ [class.union]p6: 4972 // A storage class is not allowed in a declaration of an 4973 // anonymous union in a class scope. 4974 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 4975 isa<RecordDecl>(Owner)) { 4976 Diag(DS.getStorageClassSpecLoc(), 4977 diag::err_anonymous_union_with_storage_spec) 4978 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 4979 4980 // Recover by removing the storage specifier. 4981 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 4982 SourceLocation(), 4983 PrevSpec, DiagID, Context.getPrintingPolicy()); 4984 } 4985 } 4986 4987 // Ignore const/volatile/restrict qualifiers. 4988 if (DS.getTypeQualifiers()) { 4989 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4990 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 4991 << Record->isUnion() << "const" 4992 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 4993 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4994 Diag(DS.getVolatileSpecLoc(), 4995 diag::ext_anonymous_struct_union_qualified) 4996 << Record->isUnion() << "volatile" 4997 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 4998 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 4999 Diag(DS.getRestrictSpecLoc(), 5000 diag::ext_anonymous_struct_union_qualified) 5001 << Record->isUnion() << "restrict" 5002 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 5003 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 5004 Diag(DS.getAtomicSpecLoc(), 5005 diag::ext_anonymous_struct_union_qualified) 5006 << Record->isUnion() << "_Atomic" 5007 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 5008 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 5009 Diag(DS.getUnalignedSpecLoc(), 5010 diag::ext_anonymous_struct_union_qualified) 5011 << Record->isUnion() << "__unaligned" 5012 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 5013 5014 DS.ClearTypeQualifiers(); 5015 } 5016 5017 // C++ [class.union]p2: 5018 // The member-specification of an anonymous union shall only 5019 // define non-static data members. [Note: nested types and 5020 // functions cannot be declared within an anonymous union. ] 5021 for (auto *Mem : Record->decls()) { 5022 // Ignore invalid declarations; we already diagnosed them. 5023 if (Mem->isInvalidDecl()) 5024 continue; 5025 5026 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 5027 // C++ [class.union]p3: 5028 // An anonymous union shall not have private or protected 5029 // members (clause 11). 5030 assert(FD->getAccess() != AS_none); 5031 if (FD->getAccess() != AS_public) { 5032 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 5033 << Record->isUnion() << (FD->getAccess() == AS_protected); 5034 Invalid = true; 5035 } 5036 5037 // C++ [class.union]p1 5038 // An object of a class with a non-trivial constructor, a non-trivial 5039 // copy constructor, a non-trivial destructor, or a non-trivial copy 5040 // assignment operator cannot be a member of a union, nor can an 5041 // array of such objects. 5042 if (CheckNontrivialField(FD)) 5043 Invalid = true; 5044 } else if (Mem->isImplicit()) { 5045 // Any implicit members are fine. 5046 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 5047 // This is a type that showed up in an 5048 // elaborated-type-specifier inside the anonymous struct or 5049 // union, but which actually declares a type outside of the 5050 // anonymous struct or union. It's okay. 5051 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 5052 if (!MemRecord->isAnonymousStructOrUnion() && 5053 MemRecord->getDeclName()) { 5054 // Visual C++ allows type definition in anonymous struct or union. 5055 if (getLangOpts().MicrosoftExt) 5056 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 5057 << Record->isUnion(); 5058 else { 5059 // This is a nested type declaration. 5060 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 5061 << Record->isUnion(); 5062 Invalid = true; 5063 } 5064 } else { 5065 // This is an anonymous type definition within another anonymous type. 5066 // This is a popular extension, provided by Plan9, MSVC and GCC, but 5067 // not part of standard C++. 5068 Diag(MemRecord->getLocation(), 5069 diag::ext_anonymous_record_with_anonymous_type) 5070 << Record->isUnion(); 5071 } 5072 } else if (isa<AccessSpecDecl>(Mem)) { 5073 // Any access specifier is fine. 5074 } else if (isa<StaticAssertDecl>(Mem)) { 5075 // In C++1z, static_assert declarations are also fine. 5076 } else { 5077 // We have something that isn't a non-static data 5078 // member. Complain about it. 5079 unsigned DK = diag::err_anonymous_record_bad_member; 5080 if (isa<TypeDecl>(Mem)) 5081 DK = diag::err_anonymous_record_with_type; 5082 else if (isa<FunctionDecl>(Mem)) 5083 DK = diag::err_anonymous_record_with_function; 5084 else if (isa<VarDecl>(Mem)) 5085 DK = diag::err_anonymous_record_with_static; 5086 5087 // Visual C++ allows type definition in anonymous struct or union. 5088 if (getLangOpts().MicrosoftExt && 5089 DK == diag::err_anonymous_record_with_type) 5090 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 5091 << Record->isUnion(); 5092 else { 5093 Diag(Mem->getLocation(), DK) << Record->isUnion(); 5094 Invalid = true; 5095 } 5096 } 5097 } 5098 5099 // C++11 [class.union]p8 (DR1460): 5100 // At most one variant member of a union may have a 5101 // brace-or-equal-initializer. 5102 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 5103 Owner->isRecord()) 5104 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 5105 cast<CXXRecordDecl>(Record)); 5106 } 5107 5108 if (!Record->isUnion() && !Owner->isRecord()) { 5109 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 5110 << getLangOpts().CPlusPlus; 5111 Invalid = true; 5112 } 5113 5114 // C++ [dcl.dcl]p3: 5115 // [If there are no declarators], and except for the declaration of an 5116 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 5117 // names into the program 5118 // C++ [class.mem]p2: 5119 // each such member-declaration shall either declare at least one member 5120 // name of the class or declare at least one unnamed bit-field 5121 // 5122 // For C this is an error even for a named struct, and is diagnosed elsewhere. 5123 if (getLangOpts().CPlusPlus && Record->field_empty()) 5124 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); 5125 5126 // Mock up a declarator. 5127 Declarator Dc(DS, DeclaratorContext::MemberContext); 5128 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5129 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 5130 5131 // Create a declaration for this anonymous struct/union. 5132 NamedDecl *Anon = nullptr; 5133 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 5134 Anon = FieldDecl::Create( 5135 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(), 5136 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo, 5137 /*BitWidth=*/nullptr, /*Mutable=*/false, 5138 /*InitStyle=*/ICIS_NoInit); 5139 Anon->setAccess(AS); 5140 ProcessDeclAttributes(S, Anon, Dc); 5141 5142 if (getLangOpts().CPlusPlus) 5143 FieldCollector->Add(cast<FieldDecl>(Anon)); 5144 } else { 5145 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 5146 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 5147 if (SCSpec == DeclSpec::SCS_mutable) { 5148 // mutable can only appear on non-static class members, so it's always 5149 // an error here 5150 Diag(Record->getLocation(), diag::err_mutable_nonmember); 5151 Invalid = true; 5152 SC = SC_None; 5153 } 5154 5155 assert(DS.getAttributes().empty() && "No attribute expected"); 5156 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(), 5157 Record->getLocation(), /*IdentifierInfo=*/nullptr, 5158 Context.getTypeDeclType(Record), TInfo, SC); 5159 5160 // Default-initialize the implicit variable. This initialization will be 5161 // trivial in almost all cases, except if a union member has an in-class 5162 // initializer: 5163 // union { int n = 0; }; 5164 ActOnUninitializedDecl(Anon); 5165 } 5166 Anon->setImplicit(); 5167 5168 // Mark this as an anonymous struct/union type. 5169 Record->setAnonymousStructOrUnion(true); 5170 5171 // Add the anonymous struct/union object to the current 5172 // context. We'll be referencing this object when we refer to one of 5173 // its members. 5174 Owner->addDecl(Anon); 5175 5176 // Inject the members of the anonymous struct/union into the owning 5177 // context and into the identifier resolver chain for name lookup 5178 // purposes. 5179 SmallVector<NamedDecl*, 2> Chain; 5180 Chain.push_back(Anon); 5181 5182 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 5183 Invalid = true; 5184 5185 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 5186 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 5187 MangleNumberingContext *MCtx; 5188 Decl *ManglingContextDecl; 5189 std::tie(MCtx, ManglingContextDecl) = 5190 getCurrentMangleNumberContext(NewVD->getDeclContext()); 5191 if (MCtx) { 5192 Context.setManglingNumber( 5193 NewVD, MCtx->getManglingNumber( 5194 NewVD, getMSManglingNumber(getLangOpts(), S))); 5195 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 5196 } 5197 } 5198 } 5199 5200 if (Invalid) 5201 Anon->setInvalidDecl(); 5202 5203 return Anon; 5204 } 5205 5206 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 5207 /// Microsoft C anonymous structure. 5208 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 5209 /// Example: 5210 /// 5211 /// struct A { int a; }; 5212 /// struct B { struct A; int b; }; 5213 /// 5214 /// void foo() { 5215 /// B var; 5216 /// var.a = 3; 5217 /// } 5218 /// 5219 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 5220 RecordDecl *Record) { 5221 assert(Record && "expected a record!"); 5222 5223 // Mock up a declarator. 5224 Declarator Dc(DS, DeclaratorContext::TypeNameContext); 5225 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5226 assert(TInfo && "couldn't build declarator info for anonymous struct"); 5227 5228 auto *ParentDecl = cast<RecordDecl>(CurContext); 5229 QualType RecTy = Context.getTypeDeclType(Record); 5230 5231 // Create a declaration for this anonymous struct. 5232 NamedDecl *Anon = 5233 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(), 5234 /*IdentifierInfo=*/nullptr, RecTy, TInfo, 5235 /*BitWidth=*/nullptr, /*Mutable=*/false, 5236 /*InitStyle=*/ICIS_NoInit); 5237 Anon->setImplicit(); 5238 5239 // Add the anonymous struct object to the current context. 5240 CurContext->addDecl(Anon); 5241 5242 // Inject the members of the anonymous struct into the current 5243 // context and into the identifier resolver chain for name lookup 5244 // purposes. 5245 SmallVector<NamedDecl*, 2> Chain; 5246 Chain.push_back(Anon); 5247 5248 RecordDecl *RecordDef = Record->getDefinition(); 5249 if (RequireCompleteType(Anon->getLocation(), RecTy, 5250 diag::err_field_incomplete) || 5251 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 5252 AS_none, Chain)) { 5253 Anon->setInvalidDecl(); 5254 ParentDecl->setInvalidDecl(); 5255 } 5256 5257 return Anon; 5258 } 5259 5260 /// GetNameForDeclarator - Determine the full declaration name for the 5261 /// given Declarator. 5262 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 5263 return GetNameFromUnqualifiedId(D.getName()); 5264 } 5265 5266 /// Retrieves the declaration name from a parsed unqualified-id. 5267 DeclarationNameInfo 5268 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 5269 DeclarationNameInfo NameInfo; 5270 NameInfo.setLoc(Name.StartLocation); 5271 5272 switch (Name.getKind()) { 5273 5274 case UnqualifiedIdKind::IK_ImplicitSelfParam: 5275 case UnqualifiedIdKind::IK_Identifier: 5276 NameInfo.setName(Name.Identifier); 5277 return NameInfo; 5278 5279 case UnqualifiedIdKind::IK_DeductionGuideName: { 5280 // C++ [temp.deduct.guide]p3: 5281 // The simple-template-id shall name a class template specialization. 5282 // The template-name shall be the same identifier as the template-name 5283 // of the simple-template-id. 5284 // These together intend to imply that the template-name shall name a 5285 // class template. 5286 // FIXME: template<typename T> struct X {}; 5287 // template<typename T> using Y = X<T>; 5288 // Y(int) -> Y<int>; 5289 // satisfies these rules but does not name a class template. 5290 TemplateName TN = Name.TemplateName.get().get(); 5291 auto *Template = TN.getAsTemplateDecl(); 5292 if (!Template || !isa<ClassTemplateDecl>(Template)) { 5293 Diag(Name.StartLocation, 5294 diag::err_deduction_guide_name_not_class_template) 5295 << (int)getTemplateNameKindForDiagnostics(TN) << TN; 5296 if (Template) 5297 Diag(Template->getLocation(), diag::note_template_decl_here); 5298 return DeclarationNameInfo(); 5299 } 5300 5301 NameInfo.setName( 5302 Context.DeclarationNames.getCXXDeductionGuideName(Template)); 5303 return NameInfo; 5304 } 5305 5306 case UnqualifiedIdKind::IK_OperatorFunctionId: 5307 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 5308 Name.OperatorFunctionId.Operator)); 5309 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 5310 = Name.OperatorFunctionId.SymbolLocations[0]; 5311 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 5312 = Name.EndLocation.getRawEncoding(); 5313 return NameInfo; 5314 5315 case UnqualifiedIdKind::IK_LiteralOperatorId: 5316 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 5317 Name.Identifier)); 5318 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 5319 return NameInfo; 5320 5321 case UnqualifiedIdKind::IK_ConversionFunctionId: { 5322 TypeSourceInfo *TInfo; 5323 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 5324 if (Ty.isNull()) 5325 return DeclarationNameInfo(); 5326 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 5327 Context.getCanonicalType(Ty))); 5328 NameInfo.setNamedTypeInfo(TInfo); 5329 return NameInfo; 5330 } 5331 5332 case UnqualifiedIdKind::IK_ConstructorName: { 5333 TypeSourceInfo *TInfo; 5334 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 5335 if (Ty.isNull()) 5336 return DeclarationNameInfo(); 5337 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5338 Context.getCanonicalType(Ty))); 5339 NameInfo.setNamedTypeInfo(TInfo); 5340 return NameInfo; 5341 } 5342 5343 case UnqualifiedIdKind::IK_ConstructorTemplateId: { 5344 // In well-formed code, we can only have a constructor 5345 // template-id that refers to the current context, so go there 5346 // to find the actual type being constructed. 5347 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 5348 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 5349 return DeclarationNameInfo(); 5350 5351 // Determine the type of the class being constructed. 5352 QualType CurClassType = Context.getTypeDeclType(CurClass); 5353 5354 // FIXME: Check two things: that the template-id names the same type as 5355 // CurClassType, and that the template-id does not occur when the name 5356 // was qualified. 5357 5358 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5359 Context.getCanonicalType(CurClassType))); 5360 // FIXME: should we retrieve TypeSourceInfo? 5361 NameInfo.setNamedTypeInfo(nullptr); 5362 return NameInfo; 5363 } 5364 5365 case UnqualifiedIdKind::IK_DestructorName: { 5366 TypeSourceInfo *TInfo; 5367 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 5368 if (Ty.isNull()) 5369 return DeclarationNameInfo(); 5370 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 5371 Context.getCanonicalType(Ty))); 5372 NameInfo.setNamedTypeInfo(TInfo); 5373 return NameInfo; 5374 } 5375 5376 case UnqualifiedIdKind::IK_TemplateId: { 5377 TemplateName TName = Name.TemplateId->Template.get(); 5378 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 5379 return Context.getNameForTemplate(TName, TNameLoc); 5380 } 5381 5382 } // switch (Name.getKind()) 5383 5384 llvm_unreachable("Unknown name kind"); 5385 } 5386 5387 static QualType getCoreType(QualType Ty) { 5388 do { 5389 if (Ty->isPointerType() || Ty->isReferenceType()) 5390 Ty = Ty->getPointeeType(); 5391 else if (Ty->isArrayType()) 5392 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 5393 else 5394 return Ty.withoutLocalFastQualifiers(); 5395 } while (true); 5396 } 5397 5398 /// hasSimilarParameters - Determine whether the C++ functions Declaration 5399 /// and Definition have "nearly" matching parameters. This heuristic is 5400 /// used to improve diagnostics in the case where an out-of-line function 5401 /// definition doesn't match any declaration within the class or namespace. 5402 /// Also sets Params to the list of indices to the parameters that differ 5403 /// between the declaration and the definition. If hasSimilarParameters 5404 /// returns true and Params is empty, then all of the parameters match. 5405 static bool hasSimilarParameters(ASTContext &Context, 5406 FunctionDecl *Declaration, 5407 FunctionDecl *Definition, 5408 SmallVectorImpl<unsigned> &Params) { 5409 Params.clear(); 5410 if (Declaration->param_size() != Definition->param_size()) 5411 return false; 5412 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 5413 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 5414 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 5415 5416 // The parameter types are identical 5417 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy)) 5418 continue; 5419 5420 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 5421 QualType DefParamBaseTy = getCoreType(DefParamTy); 5422 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 5423 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 5424 5425 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 5426 (DeclTyName && DeclTyName == DefTyName)) 5427 Params.push_back(Idx); 5428 else // The two parameters aren't even close 5429 return false; 5430 } 5431 5432 return true; 5433 } 5434 5435 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 5436 /// declarator needs to be rebuilt in the current instantiation. 5437 /// Any bits of declarator which appear before the name are valid for 5438 /// consideration here. That's specifically the type in the decl spec 5439 /// and the base type in any member-pointer chunks. 5440 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 5441 DeclarationName Name) { 5442 // The types we specifically need to rebuild are: 5443 // - typenames, typeofs, and decltypes 5444 // - types which will become injected class names 5445 // Of course, we also need to rebuild any type referencing such a 5446 // type. It's safest to just say "dependent", but we call out a 5447 // few cases here. 5448 5449 DeclSpec &DS = D.getMutableDeclSpec(); 5450 switch (DS.getTypeSpecType()) { 5451 case DeclSpec::TST_typename: 5452 case DeclSpec::TST_typeofType: 5453 case DeclSpec::TST_underlyingType: 5454 case DeclSpec::TST_atomic: { 5455 // Grab the type from the parser. 5456 TypeSourceInfo *TSI = nullptr; 5457 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 5458 if (T.isNull() || !T->isDependentType()) break; 5459 5460 // Make sure there's a type source info. This isn't really much 5461 // of a waste; most dependent types should have type source info 5462 // attached already. 5463 if (!TSI) 5464 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 5465 5466 // Rebuild the type in the current instantiation. 5467 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 5468 if (!TSI) return true; 5469 5470 // Store the new type back in the decl spec. 5471 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 5472 DS.UpdateTypeRep(LocType); 5473 break; 5474 } 5475 5476 case DeclSpec::TST_decltype: 5477 case DeclSpec::TST_typeofExpr: { 5478 Expr *E = DS.getRepAsExpr(); 5479 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 5480 if (Result.isInvalid()) return true; 5481 DS.UpdateExprRep(Result.get()); 5482 break; 5483 } 5484 5485 default: 5486 // Nothing to do for these decl specs. 5487 break; 5488 } 5489 5490 // It doesn't matter what order we do this in. 5491 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 5492 DeclaratorChunk &Chunk = D.getTypeObject(I); 5493 5494 // The only type information in the declarator which can come 5495 // before the declaration name is the base type of a member 5496 // pointer. 5497 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 5498 continue; 5499 5500 // Rebuild the scope specifier in-place. 5501 CXXScopeSpec &SS = Chunk.Mem.Scope(); 5502 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 5503 return true; 5504 } 5505 5506 return false; 5507 } 5508 5509 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 5510 D.setFunctionDefinitionKind(FDK_Declaration); 5511 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 5512 5513 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 5514 Dcl && Dcl->getDeclContext()->isFileContext()) 5515 Dcl->setTopLevelDeclInObjCContainer(); 5516 5517 if (getLangOpts().OpenCL) 5518 setCurrentOpenCLExtensionForDecl(Dcl); 5519 5520 return Dcl; 5521 } 5522 5523 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 5524 /// If T is the name of a class, then each of the following shall have a 5525 /// name different from T: 5526 /// - every static data member of class T; 5527 /// - every member function of class T 5528 /// - every member of class T that is itself a type; 5529 /// \returns true if the declaration name violates these rules. 5530 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 5531 DeclarationNameInfo NameInfo) { 5532 DeclarationName Name = NameInfo.getName(); 5533 5534 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 5535 while (Record && Record->isAnonymousStructOrUnion()) 5536 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 5537 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 5538 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 5539 return true; 5540 } 5541 5542 return false; 5543 } 5544 5545 /// Diagnose a declaration whose declarator-id has the given 5546 /// nested-name-specifier. 5547 /// 5548 /// \param SS The nested-name-specifier of the declarator-id. 5549 /// 5550 /// \param DC The declaration context to which the nested-name-specifier 5551 /// resolves. 5552 /// 5553 /// \param Name The name of the entity being declared. 5554 /// 5555 /// \param Loc The location of the name of the entity being declared. 5556 /// 5557 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus 5558 /// we're declaring an explicit / partial specialization / instantiation. 5559 /// 5560 /// \returns true if we cannot safely recover from this error, false otherwise. 5561 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 5562 DeclarationName Name, 5563 SourceLocation Loc, bool IsTemplateId) { 5564 DeclContext *Cur = CurContext; 5565 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 5566 Cur = Cur->getParent(); 5567 5568 // If the user provided a superfluous scope specifier that refers back to the 5569 // class in which the entity is already declared, diagnose and ignore it. 5570 // 5571 // class X { 5572 // void X::f(); 5573 // }; 5574 // 5575 // Note, it was once ill-formed to give redundant qualification in all 5576 // contexts, but that rule was removed by DR482. 5577 if (Cur->Equals(DC)) { 5578 if (Cur->isRecord()) { 5579 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 5580 : diag::err_member_extra_qualification) 5581 << Name << FixItHint::CreateRemoval(SS.getRange()); 5582 SS.clear(); 5583 } else { 5584 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 5585 } 5586 return false; 5587 } 5588 5589 // Check whether the qualifying scope encloses the scope of the original 5590 // declaration. For a template-id, we perform the checks in 5591 // CheckTemplateSpecializationScope. 5592 if (!Cur->Encloses(DC) && !IsTemplateId) { 5593 if (Cur->isRecord()) 5594 Diag(Loc, diag::err_member_qualification) 5595 << Name << SS.getRange(); 5596 else if (isa<TranslationUnitDecl>(DC)) 5597 Diag(Loc, diag::err_invalid_declarator_global_scope) 5598 << Name << SS.getRange(); 5599 else if (isa<FunctionDecl>(Cur)) 5600 Diag(Loc, diag::err_invalid_declarator_in_function) 5601 << Name << SS.getRange(); 5602 else if (isa<BlockDecl>(Cur)) 5603 Diag(Loc, diag::err_invalid_declarator_in_block) 5604 << Name << SS.getRange(); 5605 else 5606 Diag(Loc, diag::err_invalid_declarator_scope) 5607 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 5608 5609 return true; 5610 } 5611 5612 if (Cur->isRecord()) { 5613 // Cannot qualify members within a class. 5614 Diag(Loc, diag::err_member_qualification) 5615 << Name << SS.getRange(); 5616 SS.clear(); 5617 5618 // C++ constructors and destructors with incorrect scopes can break 5619 // our AST invariants by having the wrong underlying types. If 5620 // that's the case, then drop this declaration entirely. 5621 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 5622 Name.getNameKind() == DeclarationName::CXXDestructorName) && 5623 !Context.hasSameType(Name.getCXXNameType(), 5624 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 5625 return true; 5626 5627 return false; 5628 } 5629 5630 // C++11 [dcl.meaning]p1: 5631 // [...] "The nested-name-specifier of the qualified declarator-id shall 5632 // not begin with a decltype-specifer" 5633 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 5634 while (SpecLoc.getPrefix()) 5635 SpecLoc = SpecLoc.getPrefix(); 5636 if (dyn_cast_or_null<DecltypeType>( 5637 SpecLoc.getNestedNameSpecifier()->getAsType())) 5638 Diag(Loc, diag::err_decltype_in_declarator) 5639 << SpecLoc.getTypeLoc().getSourceRange(); 5640 5641 return false; 5642 } 5643 5644 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 5645 MultiTemplateParamsArg TemplateParamLists) { 5646 // TODO: consider using NameInfo for diagnostic. 5647 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5648 DeclarationName Name = NameInfo.getName(); 5649 5650 // All of these full declarators require an identifier. If it doesn't have 5651 // one, the ParsedFreeStandingDeclSpec action should be used. 5652 if (D.isDecompositionDeclarator()) { 5653 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 5654 } else if (!Name) { 5655 if (!D.isInvalidType()) // Reject this if we think it is valid. 5656 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident) 5657 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 5658 return nullptr; 5659 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 5660 return nullptr; 5661 5662 // The scope passed in may not be a decl scope. Zip up the scope tree until 5663 // we find one that is. 5664 while ((S->getFlags() & Scope::DeclScope) == 0 || 5665 (S->getFlags() & Scope::TemplateParamScope) != 0) 5666 S = S->getParent(); 5667 5668 DeclContext *DC = CurContext; 5669 if (D.getCXXScopeSpec().isInvalid()) 5670 D.setInvalidType(); 5671 else if (D.getCXXScopeSpec().isSet()) { 5672 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 5673 UPPC_DeclarationQualifier)) 5674 return nullptr; 5675 5676 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 5677 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 5678 if (!DC || isa<EnumDecl>(DC)) { 5679 // If we could not compute the declaration context, it's because the 5680 // declaration context is dependent but does not refer to a class, 5681 // class template, or class template partial specialization. Complain 5682 // and return early, to avoid the coming semantic disaster. 5683 Diag(D.getIdentifierLoc(), 5684 diag::err_template_qualified_declarator_no_match) 5685 << D.getCXXScopeSpec().getScopeRep() 5686 << D.getCXXScopeSpec().getRange(); 5687 return nullptr; 5688 } 5689 bool IsDependentContext = DC->isDependentContext(); 5690 5691 if (!IsDependentContext && 5692 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 5693 return nullptr; 5694 5695 // If a class is incomplete, do not parse entities inside it. 5696 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 5697 Diag(D.getIdentifierLoc(), 5698 diag::err_member_def_undefined_record) 5699 << Name << DC << D.getCXXScopeSpec().getRange(); 5700 return nullptr; 5701 } 5702 if (!D.getDeclSpec().isFriendSpecified()) { 5703 if (diagnoseQualifiedDeclaration( 5704 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(), 5705 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) { 5706 if (DC->isRecord()) 5707 return nullptr; 5708 5709 D.setInvalidType(); 5710 } 5711 } 5712 5713 // Check whether we need to rebuild the type of the given 5714 // declaration in the current instantiation. 5715 if (EnteringContext && IsDependentContext && 5716 TemplateParamLists.size() != 0) { 5717 ContextRAII SavedContext(*this, DC); 5718 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 5719 D.setInvalidType(); 5720 } 5721 } 5722 5723 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5724 QualType R = TInfo->getType(); 5725 5726 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 5727 UPPC_DeclarationType)) 5728 D.setInvalidType(); 5729 5730 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5731 forRedeclarationInCurContext()); 5732 5733 // See if this is a redefinition of a variable in the same scope. 5734 if (!D.getCXXScopeSpec().isSet()) { 5735 bool IsLinkageLookup = false; 5736 bool CreateBuiltins = false; 5737 5738 // If the declaration we're planning to build will be a function 5739 // or object with linkage, then look for another declaration with 5740 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 5741 // 5742 // If the declaration we're planning to build will be declared with 5743 // external linkage in the translation unit, create any builtin with 5744 // the same name. 5745 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5746 /* Do nothing*/; 5747 else if (CurContext->isFunctionOrMethod() && 5748 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 5749 R->isFunctionType())) { 5750 IsLinkageLookup = true; 5751 CreateBuiltins = 5752 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 5753 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 5754 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 5755 CreateBuiltins = true; 5756 5757 if (IsLinkageLookup) { 5758 Previous.clear(LookupRedeclarationWithLinkage); 5759 Previous.setRedeclarationKind(ForExternalRedeclaration); 5760 } 5761 5762 LookupName(Previous, S, CreateBuiltins); 5763 } else { // Something like "int foo::x;" 5764 LookupQualifiedName(Previous, DC); 5765 5766 // C++ [dcl.meaning]p1: 5767 // When the declarator-id is qualified, the declaration shall refer to a 5768 // previously declared member of the class or namespace to which the 5769 // qualifier refers (or, in the case of a namespace, of an element of the 5770 // inline namespace set of that namespace (7.3.1)) or to a specialization 5771 // thereof; [...] 5772 // 5773 // Note that we already checked the context above, and that we do not have 5774 // enough information to make sure that Previous contains the declaration 5775 // we want to match. For example, given: 5776 // 5777 // class X { 5778 // void f(); 5779 // void f(float); 5780 // }; 5781 // 5782 // void X::f(int) { } // ill-formed 5783 // 5784 // In this case, Previous will point to the overload set 5785 // containing the two f's declared in X, but neither of them 5786 // matches. 5787 5788 // C++ [dcl.meaning]p1: 5789 // [...] the member shall not merely have been introduced by a 5790 // using-declaration in the scope of the class or namespace nominated by 5791 // the nested-name-specifier of the declarator-id. 5792 RemoveUsingDecls(Previous); 5793 } 5794 5795 if (Previous.isSingleResult() && 5796 Previous.getFoundDecl()->isTemplateParameter()) { 5797 // Maybe we will complain about the shadowed template parameter. 5798 if (!D.isInvalidType()) 5799 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 5800 Previous.getFoundDecl()); 5801 5802 // Just pretend that we didn't see the previous declaration. 5803 Previous.clear(); 5804 } 5805 5806 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 5807 // Forget that the previous declaration is the injected-class-name. 5808 Previous.clear(); 5809 5810 // In C++, the previous declaration we find might be a tag type 5811 // (class or enum). In this case, the new declaration will hide the 5812 // tag type. Note that this applies to functions, function templates, and 5813 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. 5814 if (Previous.isSingleTagDecl() && 5815 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 5816 (TemplateParamLists.size() == 0 || R->isFunctionType())) 5817 Previous.clear(); 5818 5819 // Check that there are no default arguments other than in the parameters 5820 // of a function declaration (C++ only). 5821 if (getLangOpts().CPlusPlus) 5822 CheckExtraCXXDefaultArguments(D); 5823 5824 NamedDecl *New; 5825 5826 bool AddToScope = true; 5827 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 5828 if (TemplateParamLists.size()) { 5829 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 5830 return nullptr; 5831 } 5832 5833 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 5834 } else if (R->isFunctionType()) { 5835 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 5836 TemplateParamLists, 5837 AddToScope); 5838 } else { 5839 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 5840 AddToScope); 5841 } 5842 5843 if (!New) 5844 return nullptr; 5845 5846 // If this has an identifier and is not a function template specialization, 5847 // add it to the scope stack. 5848 if (New->getDeclName() && AddToScope) 5849 PushOnScopeChains(New, S); 5850 5851 if (isInOpenMPDeclareTargetContext()) 5852 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 5853 5854 return New; 5855 } 5856 5857 /// Helper method to turn variable array types into constant array 5858 /// types in certain situations which would otherwise be errors (for 5859 /// GCC compatibility). 5860 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 5861 ASTContext &Context, 5862 bool &SizeIsNegative, 5863 llvm::APSInt &Oversized) { 5864 // This method tries to turn a variable array into a constant 5865 // array even when the size isn't an ICE. This is necessary 5866 // for compatibility with code that depends on gcc's buggy 5867 // constant expression folding, like struct {char x[(int)(char*)2];} 5868 SizeIsNegative = false; 5869 Oversized = 0; 5870 5871 if (T->isDependentType()) 5872 return QualType(); 5873 5874 QualifierCollector Qs; 5875 const Type *Ty = Qs.strip(T); 5876 5877 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 5878 QualType Pointee = PTy->getPointeeType(); 5879 QualType FixedType = 5880 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 5881 Oversized); 5882 if (FixedType.isNull()) return FixedType; 5883 FixedType = Context.getPointerType(FixedType); 5884 return Qs.apply(Context, FixedType); 5885 } 5886 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 5887 QualType Inner = PTy->getInnerType(); 5888 QualType FixedType = 5889 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 5890 Oversized); 5891 if (FixedType.isNull()) return FixedType; 5892 FixedType = Context.getParenType(FixedType); 5893 return Qs.apply(Context, FixedType); 5894 } 5895 5896 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 5897 if (!VLATy) 5898 return QualType(); 5899 // FIXME: We should probably handle this case 5900 if (VLATy->getElementType()->isVariablyModifiedType()) 5901 return QualType(); 5902 5903 Expr::EvalResult Result; 5904 if (!VLATy->getSizeExpr() || 5905 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context)) 5906 return QualType(); 5907 5908 llvm::APSInt Res = Result.Val.getInt(); 5909 5910 // Check whether the array size is negative. 5911 if (Res.isSigned() && Res.isNegative()) { 5912 SizeIsNegative = true; 5913 return QualType(); 5914 } 5915 5916 // Check whether the array is too large to be addressed. 5917 unsigned ActiveSizeBits 5918 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 5919 Res); 5920 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 5921 Oversized = Res; 5922 return QualType(); 5923 } 5924 5925 return Context.getConstantArrayType( 5926 VLATy->getElementType(), Res, VLATy->getSizeExpr(), ArrayType::Normal, 0); 5927 } 5928 5929 static void 5930 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 5931 SrcTL = SrcTL.getUnqualifiedLoc(); 5932 DstTL = DstTL.getUnqualifiedLoc(); 5933 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 5934 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 5935 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 5936 DstPTL.getPointeeLoc()); 5937 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 5938 return; 5939 } 5940 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 5941 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 5942 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 5943 DstPTL.getInnerLoc()); 5944 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 5945 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 5946 return; 5947 } 5948 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 5949 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 5950 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 5951 TypeLoc DstElemTL = DstATL.getElementLoc(); 5952 DstElemTL.initializeFullCopy(SrcElemTL); 5953 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 5954 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 5955 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 5956 } 5957 5958 /// Helper method to turn variable array types into constant array 5959 /// types in certain situations which would otherwise be errors (for 5960 /// GCC compatibility). 5961 static TypeSourceInfo* 5962 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 5963 ASTContext &Context, 5964 bool &SizeIsNegative, 5965 llvm::APSInt &Oversized) { 5966 QualType FixedTy 5967 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 5968 SizeIsNegative, Oversized); 5969 if (FixedTy.isNull()) 5970 return nullptr; 5971 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 5972 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 5973 FixedTInfo->getTypeLoc()); 5974 return FixedTInfo; 5975 } 5976 5977 /// Register the given locally-scoped extern "C" declaration so 5978 /// that it can be found later for redeclarations. We include any extern "C" 5979 /// declaration that is not visible in the translation unit here, not just 5980 /// function-scope declarations. 5981 void 5982 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 5983 if (!getLangOpts().CPlusPlus && 5984 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 5985 // Don't need to track declarations in the TU in C. 5986 return; 5987 5988 // Note that we have a locally-scoped external with this name. 5989 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 5990 } 5991 5992 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 5993 // FIXME: We can have multiple results via __attribute__((overloadable)). 5994 auto Result = Context.getExternCContextDecl()->lookup(Name); 5995 return Result.empty() ? nullptr : *Result.begin(); 5996 } 5997 5998 /// Diagnose function specifiers on a declaration of an identifier that 5999 /// does not identify a function. 6000 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 6001 // FIXME: We should probably indicate the identifier in question to avoid 6002 // confusion for constructs like "virtual int a(), b;" 6003 if (DS.isVirtualSpecified()) 6004 Diag(DS.getVirtualSpecLoc(), 6005 diag::err_virtual_non_function); 6006 6007 if (DS.hasExplicitSpecifier()) 6008 Diag(DS.getExplicitSpecLoc(), 6009 diag::err_explicit_non_function); 6010 6011 if (DS.isNoreturnSpecified()) 6012 Diag(DS.getNoreturnSpecLoc(), 6013 diag::err_noreturn_non_function); 6014 } 6015 6016 NamedDecl* 6017 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 6018 TypeSourceInfo *TInfo, LookupResult &Previous) { 6019 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 6020 if (D.getCXXScopeSpec().isSet()) { 6021 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 6022 << D.getCXXScopeSpec().getRange(); 6023 D.setInvalidType(); 6024 // Pretend we didn't see the scope specifier. 6025 DC = CurContext; 6026 Previous.clear(); 6027 } 6028 6029 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6030 6031 if (D.getDeclSpec().isInlineSpecified()) 6032 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6033 << getLangOpts().CPlusPlus17; 6034 if (D.getDeclSpec().hasConstexprSpecifier()) 6035 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 6036 << 1 << D.getDeclSpec().getConstexprSpecifier(); 6037 6038 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) { 6039 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName) 6040 Diag(D.getName().StartLocation, 6041 diag::err_deduction_guide_invalid_specifier) 6042 << "typedef"; 6043 else 6044 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 6045 << D.getName().getSourceRange(); 6046 return nullptr; 6047 } 6048 6049 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 6050 if (!NewTD) return nullptr; 6051 6052 // Handle attributes prior to checking for duplicates in MergeVarDecl 6053 ProcessDeclAttributes(S, NewTD, D); 6054 6055 CheckTypedefForVariablyModifiedType(S, NewTD); 6056 6057 bool Redeclaration = D.isRedeclaration(); 6058 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 6059 D.setRedeclaration(Redeclaration); 6060 return ND; 6061 } 6062 6063 void 6064 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 6065 // C99 6.7.7p2: If a typedef name specifies a variably modified type 6066 // then it shall have block scope. 6067 // Note that variably modified types must be fixed before merging the decl so 6068 // that redeclarations will match. 6069 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 6070 QualType T = TInfo->getType(); 6071 if (T->isVariablyModifiedType()) { 6072 setFunctionHasBranchProtectedScope(); 6073 6074 if (S->getFnParent() == nullptr) { 6075 bool SizeIsNegative; 6076 llvm::APSInt Oversized; 6077 TypeSourceInfo *FixedTInfo = 6078 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 6079 SizeIsNegative, 6080 Oversized); 6081 if (FixedTInfo) { 6082 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 6083 NewTD->setTypeSourceInfo(FixedTInfo); 6084 } else { 6085 if (SizeIsNegative) 6086 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 6087 else if (T->isVariableArrayType()) 6088 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 6089 else if (Oversized.getBoolValue()) 6090 Diag(NewTD->getLocation(), diag::err_array_too_large) 6091 << Oversized.toString(10); 6092 else 6093 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 6094 NewTD->setInvalidDecl(); 6095 } 6096 } 6097 } 6098 } 6099 6100 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 6101 /// declares a typedef-name, either using the 'typedef' type specifier or via 6102 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 6103 NamedDecl* 6104 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 6105 LookupResult &Previous, bool &Redeclaration) { 6106 6107 // Find the shadowed declaration before filtering for scope. 6108 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); 6109 6110 // Merge the decl with the existing one if appropriate. If the decl is 6111 // in an outer scope, it isn't the same thing. 6112 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 6113 /*AllowInlineNamespace*/false); 6114 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 6115 if (!Previous.empty()) { 6116 Redeclaration = true; 6117 MergeTypedefNameDecl(S, NewTD, Previous); 6118 } else { 6119 inferGslPointerAttribute(NewTD); 6120 } 6121 6122 if (ShadowedDecl && !Redeclaration) 6123 CheckShadow(NewTD, ShadowedDecl, Previous); 6124 6125 // If this is the C FILE type, notify the AST context. 6126 if (IdentifierInfo *II = NewTD->getIdentifier()) 6127 if (!NewTD->isInvalidDecl() && 6128 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 6129 if (II->isStr("FILE")) 6130 Context.setFILEDecl(NewTD); 6131 else if (II->isStr("jmp_buf")) 6132 Context.setjmp_bufDecl(NewTD); 6133 else if (II->isStr("sigjmp_buf")) 6134 Context.setsigjmp_bufDecl(NewTD); 6135 else if (II->isStr("ucontext_t")) 6136 Context.setucontext_tDecl(NewTD); 6137 } 6138 6139 return NewTD; 6140 } 6141 6142 /// Determines whether the given declaration is an out-of-scope 6143 /// previous declaration. 6144 /// 6145 /// This routine should be invoked when name lookup has found a 6146 /// previous declaration (PrevDecl) that is not in the scope where a 6147 /// new declaration by the same name is being introduced. If the new 6148 /// declaration occurs in a local scope, previous declarations with 6149 /// linkage may still be considered previous declarations (C99 6150 /// 6.2.2p4-5, C++ [basic.link]p6). 6151 /// 6152 /// \param PrevDecl the previous declaration found by name 6153 /// lookup 6154 /// 6155 /// \param DC the context in which the new declaration is being 6156 /// declared. 6157 /// 6158 /// \returns true if PrevDecl is an out-of-scope previous declaration 6159 /// for a new delcaration with the same name. 6160 static bool 6161 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 6162 ASTContext &Context) { 6163 if (!PrevDecl) 6164 return false; 6165 6166 if (!PrevDecl->hasLinkage()) 6167 return false; 6168 6169 if (Context.getLangOpts().CPlusPlus) { 6170 // C++ [basic.link]p6: 6171 // If there is a visible declaration of an entity with linkage 6172 // having the same name and type, ignoring entities declared 6173 // outside the innermost enclosing namespace scope, the block 6174 // scope declaration declares that same entity and receives the 6175 // linkage of the previous declaration. 6176 DeclContext *OuterContext = DC->getRedeclContext(); 6177 if (!OuterContext->isFunctionOrMethod()) 6178 // This rule only applies to block-scope declarations. 6179 return false; 6180 6181 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 6182 if (PrevOuterContext->isRecord()) 6183 // We found a member function: ignore it. 6184 return false; 6185 6186 // Find the innermost enclosing namespace for the new and 6187 // previous declarations. 6188 OuterContext = OuterContext->getEnclosingNamespaceContext(); 6189 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 6190 6191 // The previous declaration is in a different namespace, so it 6192 // isn't the same function. 6193 if (!OuterContext->Equals(PrevOuterContext)) 6194 return false; 6195 } 6196 6197 return true; 6198 } 6199 6200 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) { 6201 CXXScopeSpec &SS = D.getCXXScopeSpec(); 6202 if (!SS.isSet()) return; 6203 DD->setQualifierInfo(SS.getWithLocInContext(S.Context)); 6204 } 6205 6206 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 6207 QualType type = decl->getType(); 6208 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 6209 if (lifetime == Qualifiers::OCL_Autoreleasing) { 6210 // Various kinds of declaration aren't allowed to be __autoreleasing. 6211 unsigned kind = -1U; 6212 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6213 if (var->hasAttr<BlocksAttr>()) 6214 kind = 0; // __block 6215 else if (!var->hasLocalStorage()) 6216 kind = 1; // global 6217 } else if (isa<ObjCIvarDecl>(decl)) { 6218 kind = 3; // ivar 6219 } else if (isa<FieldDecl>(decl)) { 6220 kind = 2; // field 6221 } 6222 6223 if (kind != -1U) { 6224 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 6225 << kind; 6226 } 6227 } else if (lifetime == Qualifiers::OCL_None) { 6228 // Try to infer lifetime. 6229 if (!type->isObjCLifetimeType()) 6230 return false; 6231 6232 lifetime = type->getObjCARCImplicitLifetime(); 6233 type = Context.getLifetimeQualifiedType(type, lifetime); 6234 decl->setType(type); 6235 } 6236 6237 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6238 // Thread-local variables cannot have lifetime. 6239 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 6240 var->getTLSKind()) { 6241 Diag(var->getLocation(), diag::err_arc_thread_ownership) 6242 << var->getType(); 6243 return true; 6244 } 6245 } 6246 6247 return false; 6248 } 6249 6250 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) { 6251 if (Decl->getType().hasAddressSpace()) 6252 return; 6253 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) { 6254 QualType Type = Var->getType(); 6255 if (Type->isSamplerT() || Type->isVoidType()) 6256 return; 6257 LangAS ImplAS = LangAS::opencl_private; 6258 if ((getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) && 6259 Var->hasGlobalStorage()) 6260 ImplAS = LangAS::opencl_global; 6261 // If the original type from a decayed type is an array type and that array 6262 // type has no address space yet, deduce it now. 6263 if (auto DT = dyn_cast<DecayedType>(Type)) { 6264 auto OrigTy = DT->getOriginalType(); 6265 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) { 6266 // Add the address space to the original array type and then propagate 6267 // that to the element type through `getAsArrayType`. 6268 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS); 6269 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0); 6270 // Re-generate the decayed type. 6271 Type = Context.getDecayedType(OrigTy); 6272 } 6273 } 6274 Type = Context.getAddrSpaceQualType(Type, ImplAS); 6275 // Apply any qualifiers (including address space) from the array type to 6276 // the element type. This implements C99 6.7.3p8: "If the specification of 6277 // an array type includes any type qualifiers, the element type is so 6278 // qualified, not the array type." 6279 if (Type->isArrayType()) 6280 Type = QualType(Context.getAsArrayType(Type), 0); 6281 Decl->setType(Type); 6282 } 6283 } 6284 6285 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 6286 // Ensure that an auto decl is deduced otherwise the checks below might cache 6287 // the wrong linkage. 6288 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 6289 6290 // 'weak' only applies to declarations with external linkage. 6291 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 6292 if (!ND.isExternallyVisible()) { 6293 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 6294 ND.dropAttr<WeakAttr>(); 6295 } 6296 } 6297 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 6298 if (ND.isExternallyVisible()) { 6299 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 6300 ND.dropAttr<WeakRefAttr>(); 6301 ND.dropAttr<AliasAttr>(); 6302 } 6303 } 6304 6305 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 6306 if (VD->hasInit()) { 6307 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 6308 assert(VD->isThisDeclarationADefinition() && 6309 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 6310 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 6311 VD->dropAttr<AliasAttr>(); 6312 } 6313 } 6314 } 6315 6316 // 'selectany' only applies to externally visible variable declarations. 6317 // It does not apply to functions. 6318 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 6319 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 6320 S.Diag(Attr->getLocation(), 6321 diag::err_attribute_selectany_non_extern_data); 6322 ND.dropAttr<SelectAnyAttr>(); 6323 } 6324 } 6325 6326 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 6327 auto *VD = dyn_cast<VarDecl>(&ND); 6328 bool IsAnonymousNS = false; 6329 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6330 if (VD) { 6331 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext()); 6332 while (NS && !IsAnonymousNS) { 6333 IsAnonymousNS = NS->isAnonymousNamespace(); 6334 NS = dyn_cast<NamespaceDecl>(NS->getParent()); 6335 } 6336 } 6337 // dll attributes require external linkage. Static locals may have external 6338 // linkage but still cannot be explicitly imported or exported. 6339 // In Microsoft mode, a variable defined in anonymous namespace must have 6340 // external linkage in order to be exported. 6341 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft; 6342 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) || 6343 (!AnonNSInMicrosoftMode && 6344 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) { 6345 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 6346 << &ND << Attr; 6347 ND.setInvalidDecl(); 6348 } 6349 } 6350 6351 // Virtual functions cannot be marked as 'notail'. 6352 if (auto *Attr = ND.getAttr<NotTailCalledAttr>()) 6353 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND)) 6354 if (MD->isVirtual()) { 6355 S.Diag(ND.getLocation(), 6356 diag::err_invalid_attribute_on_virtual_function) 6357 << Attr; 6358 ND.dropAttr<NotTailCalledAttr>(); 6359 } 6360 6361 // Check the attributes on the function type, if any. 6362 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) { 6363 // Don't declare this variable in the second operand of the for-statement; 6364 // GCC miscompiles that by ending its lifetime before evaluating the 6365 // third operand. See gcc.gnu.org/PR86769. 6366 AttributedTypeLoc ATL; 6367 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc(); 6368 (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); 6369 TL = ATL.getModifiedLoc()) { 6370 // The [[lifetimebound]] attribute can be applied to the implicit object 6371 // parameter of a non-static member function (other than a ctor or dtor) 6372 // by applying it to the function type. 6373 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) { 6374 const auto *MD = dyn_cast<CXXMethodDecl>(FD); 6375 if (!MD || MD->isStatic()) { 6376 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param) 6377 << !MD << A->getRange(); 6378 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) { 6379 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor) 6380 << isa<CXXDestructorDecl>(MD) << A->getRange(); 6381 } 6382 } 6383 } 6384 } 6385 } 6386 6387 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 6388 NamedDecl *NewDecl, 6389 bool IsSpecialization, 6390 bool IsDefinition) { 6391 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl()) 6392 return; 6393 6394 bool IsTemplate = false; 6395 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 6396 OldDecl = OldTD->getTemplatedDecl(); 6397 IsTemplate = true; 6398 if (!IsSpecialization) 6399 IsDefinition = false; 6400 } 6401 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { 6402 NewDecl = NewTD->getTemplatedDecl(); 6403 IsTemplate = true; 6404 } 6405 6406 if (!OldDecl || !NewDecl) 6407 return; 6408 6409 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 6410 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 6411 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 6412 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 6413 6414 // dllimport and dllexport are inheritable attributes so we have to exclude 6415 // inherited attribute instances. 6416 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 6417 (NewExportAttr && !NewExportAttr->isInherited()); 6418 6419 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 6420 // the only exception being explicit specializations. 6421 // Implicitly generated declarations are also excluded for now because there 6422 // is no other way to switch these to use dllimport or dllexport. 6423 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 6424 6425 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 6426 // Allow with a warning for free functions and global variables. 6427 bool JustWarn = false; 6428 if (!OldDecl->isCXXClassMember()) { 6429 auto *VD = dyn_cast<VarDecl>(OldDecl); 6430 if (VD && !VD->getDescribedVarTemplate()) 6431 JustWarn = true; 6432 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 6433 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 6434 JustWarn = true; 6435 } 6436 6437 // We cannot change a declaration that's been used because IR has already 6438 // been emitted. Dllimported functions will still work though (modulo 6439 // address equality) as they can use the thunk. 6440 if (OldDecl->isUsed()) 6441 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 6442 JustWarn = false; 6443 6444 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 6445 : diag::err_attribute_dll_redeclaration; 6446 S.Diag(NewDecl->getLocation(), DiagID) 6447 << NewDecl 6448 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 6449 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6450 if (!JustWarn) { 6451 NewDecl->setInvalidDecl(); 6452 return; 6453 } 6454 } 6455 6456 // A redeclaration is not allowed to drop a dllimport attribute, the only 6457 // exceptions being inline function definitions (except for function 6458 // templates), local extern declarations, qualified friend declarations or 6459 // special MSVC extension: in the last case, the declaration is treated as if 6460 // it were marked dllexport. 6461 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 6462 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6463 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 6464 // Ignore static data because out-of-line definitions are diagnosed 6465 // separately. 6466 IsStaticDataMember = VD->isStaticDataMember(); 6467 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 6468 VarDecl::DeclarationOnly; 6469 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 6470 IsInline = FD->isInlined(); 6471 IsQualifiedFriend = FD->getQualifier() && 6472 FD->getFriendObjectKind() == Decl::FOK_Declared; 6473 } 6474 6475 if (OldImportAttr && !HasNewAttr && 6476 (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember && 6477 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 6478 if (IsMicrosoft && IsDefinition) { 6479 S.Diag(NewDecl->getLocation(), 6480 diag::warn_redeclaration_without_import_attribute) 6481 << NewDecl; 6482 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6483 NewDecl->dropAttr<DLLImportAttr>(); 6484 NewDecl->addAttr( 6485 DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange())); 6486 } else { 6487 S.Diag(NewDecl->getLocation(), 6488 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 6489 << NewDecl << OldImportAttr; 6490 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6491 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 6492 OldDecl->dropAttr<DLLImportAttr>(); 6493 NewDecl->dropAttr<DLLImportAttr>(); 6494 } 6495 } else if (IsInline && OldImportAttr && !IsMicrosoft) { 6496 // In MinGW, seeing a function declared inline drops the dllimport 6497 // attribute. 6498 OldDecl->dropAttr<DLLImportAttr>(); 6499 NewDecl->dropAttr<DLLImportAttr>(); 6500 S.Diag(NewDecl->getLocation(), 6501 diag::warn_dllimport_dropped_from_inline_function) 6502 << NewDecl << OldImportAttr; 6503 } 6504 6505 // A specialization of a class template member function is processed here 6506 // since it's a redeclaration. If the parent class is dllexport, the 6507 // specialization inherits that attribute. This doesn't happen automatically 6508 // since the parent class isn't instantiated until later. 6509 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) { 6510 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && 6511 !NewImportAttr && !NewExportAttr) { 6512 if (const DLLExportAttr *ParentExportAttr = 6513 MD->getParent()->getAttr<DLLExportAttr>()) { 6514 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context); 6515 NewAttr->setInherited(true); 6516 NewDecl->addAttr(NewAttr); 6517 } 6518 } 6519 } 6520 } 6521 6522 /// Given that we are within the definition of the given function, 6523 /// will that definition behave like C99's 'inline', where the 6524 /// definition is discarded except for optimization purposes? 6525 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 6526 // Try to avoid calling GetGVALinkageForFunction. 6527 6528 // All cases of this require the 'inline' keyword. 6529 if (!FD->isInlined()) return false; 6530 6531 // This is only possible in C++ with the gnu_inline attribute. 6532 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 6533 return false; 6534 6535 // Okay, go ahead and call the relatively-more-expensive function. 6536 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 6537 } 6538 6539 /// Determine whether a variable is extern "C" prior to attaching 6540 /// an initializer. We can't just call isExternC() here, because that 6541 /// will also compute and cache whether the declaration is externally 6542 /// visible, which might change when we attach the initializer. 6543 /// 6544 /// This can only be used if the declaration is known to not be a 6545 /// redeclaration of an internal linkage declaration. 6546 /// 6547 /// For instance: 6548 /// 6549 /// auto x = []{}; 6550 /// 6551 /// Attaching the initializer here makes this declaration not externally 6552 /// visible, because its type has internal linkage. 6553 /// 6554 /// FIXME: This is a hack. 6555 template<typename T> 6556 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 6557 if (S.getLangOpts().CPlusPlus) { 6558 // In C++, the overloadable attribute negates the effects of extern "C". 6559 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 6560 return false; 6561 6562 // So do CUDA's host/device attributes. 6563 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 6564 D->template hasAttr<CUDAHostAttr>())) 6565 return false; 6566 } 6567 return D->isExternC(); 6568 } 6569 6570 static bool shouldConsiderLinkage(const VarDecl *VD) { 6571 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 6572 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) || 6573 isa<OMPDeclareMapperDecl>(DC)) 6574 return VD->hasExternalStorage(); 6575 if (DC->isFileContext()) 6576 return true; 6577 if (DC->isRecord()) 6578 return false; 6579 if (isa<RequiresExprBodyDecl>(DC)) 6580 return false; 6581 llvm_unreachable("Unexpected context"); 6582 } 6583 6584 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 6585 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 6586 if (DC->isFileContext() || DC->isFunctionOrMethod() || 6587 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC)) 6588 return true; 6589 if (DC->isRecord()) 6590 return false; 6591 llvm_unreachable("Unexpected context"); 6592 } 6593 6594 static bool hasParsedAttr(Scope *S, const Declarator &PD, 6595 ParsedAttr::Kind Kind) { 6596 // Check decl attributes on the DeclSpec. 6597 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind)) 6598 return true; 6599 6600 // Walk the declarator structure, checking decl attributes that were in a type 6601 // position to the decl itself. 6602 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 6603 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind)) 6604 return true; 6605 } 6606 6607 // Finally, check attributes on the decl itself. 6608 return PD.getAttributes().hasAttribute(Kind); 6609 } 6610 6611 /// Adjust the \c DeclContext for a function or variable that might be a 6612 /// function-local external declaration. 6613 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 6614 if (!DC->isFunctionOrMethod()) 6615 return false; 6616 6617 // If this is a local extern function or variable declared within a function 6618 // template, don't add it into the enclosing namespace scope until it is 6619 // instantiated; it might have a dependent type right now. 6620 if (DC->isDependentContext()) 6621 return true; 6622 6623 // C++11 [basic.link]p7: 6624 // When a block scope declaration of an entity with linkage is not found to 6625 // refer to some other declaration, then that entity is a member of the 6626 // innermost enclosing namespace. 6627 // 6628 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 6629 // semantically-enclosing namespace, not a lexically-enclosing one. 6630 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 6631 DC = DC->getParent(); 6632 return true; 6633 } 6634 6635 /// Returns true if given declaration has external C language linkage. 6636 static bool isDeclExternC(const Decl *D) { 6637 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 6638 return FD->isExternC(); 6639 if (const auto *VD = dyn_cast<VarDecl>(D)) 6640 return VD->isExternC(); 6641 6642 llvm_unreachable("Unknown type of decl!"); 6643 } 6644 /// Returns true if there hasn't been any invalid type diagnosed. 6645 static bool diagnoseOpenCLTypes(Scope *S, Sema &Se, Declarator &D, 6646 DeclContext *DC, QualType R) { 6647 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 6648 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 6649 // argument. 6650 if (R->isImageType() || R->isPipeType()) { 6651 Se.Diag(D.getIdentifierLoc(), 6652 diag::err_opencl_type_can_only_be_used_as_function_parameter) 6653 << R; 6654 D.setInvalidType(); 6655 return false; 6656 } 6657 6658 // OpenCL v1.2 s6.9.r: 6659 // The event type cannot be used to declare a program scope variable. 6660 // OpenCL v2.0 s6.9.q: 6661 // The clk_event_t and reserve_id_t types cannot be declared in program 6662 // scope. 6663 if (NULL == S->getParent()) { 6664 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 6665 Se.Diag(D.getIdentifierLoc(), 6666 diag::err_invalid_type_for_program_scope_var) 6667 << R; 6668 D.setInvalidType(); 6669 return false; 6670 } 6671 } 6672 6673 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 6674 QualType NR = R; 6675 while (NR->isPointerType()) { 6676 if (NR->isFunctionPointerType()) { 6677 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer); 6678 D.setInvalidType(); 6679 return false; 6680 } 6681 NR = NR->getPointeeType(); 6682 } 6683 6684 if (!Se.getOpenCLOptions().isEnabled("cl_khr_fp16")) { 6685 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 6686 // half array type (unless the cl_khr_fp16 extension is enabled). 6687 if (Se.Context.getBaseElementType(R)->isHalfType()) { 6688 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 6689 D.setInvalidType(); 6690 return false; 6691 } 6692 } 6693 6694 // OpenCL v1.2 s6.9.r: 6695 // The event type cannot be used with the __local, __constant and __global 6696 // address space qualifiers. 6697 if (R->isEventT()) { 6698 if (R.getAddressSpace() != LangAS::opencl_private) { 6699 Se.Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual); 6700 D.setInvalidType(); 6701 return false; 6702 } 6703 } 6704 6705 // C++ for OpenCL does not allow the thread_local storage qualifier. 6706 // OpenCL C does not support thread_local either, and 6707 // also reject all other thread storage class specifiers. 6708 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec(); 6709 if (TSC != TSCS_unspecified) { 6710 bool IsCXX = Se.getLangOpts().OpenCLCPlusPlus; 6711 Se.Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6712 diag::err_opencl_unknown_type_specifier) 6713 << IsCXX << Se.getLangOpts().getOpenCLVersionTuple().getAsString() 6714 << DeclSpec::getSpecifierName(TSC) << 1; 6715 D.setInvalidType(); 6716 return false; 6717 } 6718 6719 if (R->isSamplerT()) { 6720 // OpenCL v1.2 s6.9.b p4: 6721 // The sampler type cannot be used with the __local and __global address 6722 // space qualifiers. 6723 if (R.getAddressSpace() == LangAS::opencl_local || 6724 R.getAddressSpace() == LangAS::opencl_global) { 6725 Se.Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 6726 D.setInvalidType(); 6727 } 6728 6729 // OpenCL v1.2 s6.12.14.1: 6730 // A global sampler must be declared with either the constant address 6731 // space qualifier or with the const qualifier. 6732 if (DC->isTranslationUnit() && 6733 !(R.getAddressSpace() == LangAS::opencl_constant || 6734 R.isConstQualified())) { 6735 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler); 6736 D.setInvalidType(); 6737 } 6738 if (D.isInvalidType()) 6739 return false; 6740 } 6741 return true; 6742 } 6743 6744 NamedDecl *Sema::ActOnVariableDeclarator( 6745 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 6746 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 6747 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 6748 QualType R = TInfo->getType(); 6749 DeclarationName Name = GetNameForDeclarator(D).getName(); 6750 6751 IdentifierInfo *II = Name.getAsIdentifierInfo(); 6752 6753 if (D.isDecompositionDeclarator()) { 6754 // Take the name of the first declarator as our name for diagnostic 6755 // purposes. 6756 auto &Decomp = D.getDecompositionDeclarator(); 6757 if (!Decomp.bindings().empty()) { 6758 II = Decomp.bindings()[0].Name; 6759 Name = II; 6760 } 6761 } else if (!II) { 6762 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; 6763 return nullptr; 6764 } 6765 6766 6767 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 6768 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 6769 6770 // dllimport globals without explicit storage class are treated as extern. We 6771 // have to change the storage class this early to get the right DeclContext. 6772 if (SC == SC_None && !DC->isRecord() && 6773 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) && 6774 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport)) 6775 SC = SC_Extern; 6776 6777 DeclContext *OriginalDC = DC; 6778 bool IsLocalExternDecl = SC == SC_Extern && 6779 adjustContextForLocalExternDecl(DC); 6780 6781 if (SCSpec == DeclSpec::SCS_mutable) { 6782 // mutable can only appear on non-static class members, so it's always 6783 // an error here 6784 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 6785 D.setInvalidType(); 6786 SC = SC_None; 6787 } 6788 6789 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 6790 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 6791 D.getDeclSpec().getStorageClassSpecLoc())) { 6792 // In C++11, the 'register' storage class specifier is deprecated. 6793 // Suppress the warning in system macros, it's used in macros in some 6794 // popular C system headers, such as in glibc's htonl() macro. 6795 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6796 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 6797 : diag::warn_deprecated_register) 6798 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6799 } 6800 6801 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6802 6803 if (!DC->isRecord() && S->getFnParent() == nullptr) { 6804 // C99 6.9p2: The storage-class specifiers auto and register shall not 6805 // appear in the declaration specifiers in an external declaration. 6806 // Global Register+Asm is a GNU extension we support. 6807 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 6808 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 6809 D.setInvalidType(); 6810 } 6811 } 6812 6813 bool IsMemberSpecialization = false; 6814 bool IsVariableTemplateSpecialization = false; 6815 bool IsPartialSpecialization = false; 6816 bool IsVariableTemplate = false; 6817 VarDecl *NewVD = nullptr; 6818 VarTemplateDecl *NewTemplate = nullptr; 6819 TemplateParameterList *TemplateParams = nullptr; 6820 if (!getLangOpts().CPlusPlus) { 6821 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), 6822 II, R, TInfo, SC); 6823 6824 if (R->getContainedDeducedType()) 6825 ParsingInitForAutoVars.insert(NewVD); 6826 6827 if (D.isInvalidType()) 6828 NewVD->setInvalidDecl(); 6829 6830 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() && 6831 NewVD->hasLocalStorage()) 6832 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(), 6833 NTCUC_AutoVar, NTCUK_Destruct); 6834 } else { 6835 bool Invalid = false; 6836 6837 if (DC->isRecord() && !CurContext->isRecord()) { 6838 // This is an out-of-line definition of a static data member. 6839 switch (SC) { 6840 case SC_None: 6841 break; 6842 case SC_Static: 6843 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6844 diag::err_static_out_of_line) 6845 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6846 break; 6847 case SC_Auto: 6848 case SC_Register: 6849 case SC_Extern: 6850 // [dcl.stc] p2: The auto or register specifiers shall be applied only 6851 // to names of variables declared in a block or to function parameters. 6852 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 6853 // of class members 6854 6855 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6856 diag::err_storage_class_for_static_member) 6857 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6858 break; 6859 case SC_PrivateExtern: 6860 llvm_unreachable("C storage class in c++!"); 6861 } 6862 } 6863 6864 if (SC == SC_Static && CurContext->isRecord()) { 6865 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 6866 // C++ [class.static.data]p2: 6867 // A static data member shall not be a direct member of an unnamed 6868 // or local class 6869 // FIXME: or of a (possibly indirectly) nested class thereof. 6870 if (RD->isLocalClass()) { 6871 Diag(D.getIdentifierLoc(), 6872 diag::err_static_data_member_not_allowed_in_local_class) 6873 << Name << RD->getDeclName() << RD->getTagKind(); 6874 } else if (!RD->getDeclName()) { 6875 Diag(D.getIdentifierLoc(), 6876 diag::err_static_data_member_not_allowed_in_anon_struct) 6877 << Name << RD->getTagKind(); 6878 Invalid = true; 6879 } else if (RD->isUnion()) { 6880 // C++98 [class.union]p1: If a union contains a static data member, 6881 // the program is ill-formed. C++11 drops this restriction. 6882 Diag(D.getIdentifierLoc(), 6883 getLangOpts().CPlusPlus11 6884 ? diag::warn_cxx98_compat_static_data_member_in_union 6885 : diag::ext_static_data_member_in_union) << Name; 6886 } 6887 } 6888 } 6889 6890 // Match up the template parameter lists with the scope specifier, then 6891 // determine whether we have a template or a template specialization. 6892 bool InvalidScope = false; 6893 TemplateParams = MatchTemplateParametersToScopeSpecifier( 6894 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 6895 D.getCXXScopeSpec(), 6896 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 6897 ? D.getName().TemplateId 6898 : nullptr, 6899 TemplateParamLists, 6900 /*never a friend*/ false, IsMemberSpecialization, InvalidScope); 6901 Invalid |= InvalidScope; 6902 6903 if (TemplateParams) { 6904 if (!TemplateParams->size() && 6905 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 6906 // There is an extraneous 'template<>' for this variable. Complain 6907 // about it, but allow the declaration of the variable. 6908 Diag(TemplateParams->getTemplateLoc(), 6909 diag::err_template_variable_noparams) 6910 << II 6911 << SourceRange(TemplateParams->getTemplateLoc(), 6912 TemplateParams->getRAngleLoc()); 6913 TemplateParams = nullptr; 6914 } else { 6915 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 6916 // This is an explicit specialization or a partial specialization. 6917 // FIXME: Check that we can declare a specialization here. 6918 IsVariableTemplateSpecialization = true; 6919 IsPartialSpecialization = TemplateParams->size() > 0; 6920 } else { // if (TemplateParams->size() > 0) 6921 // This is a template declaration. 6922 IsVariableTemplate = true; 6923 6924 // Check that we can declare a template here. 6925 if (CheckTemplateDeclScope(S, TemplateParams)) 6926 return nullptr; 6927 6928 // Only C++1y supports variable templates (N3651). 6929 Diag(D.getIdentifierLoc(), 6930 getLangOpts().CPlusPlus14 6931 ? diag::warn_cxx11_compat_variable_template 6932 : diag::ext_variable_template); 6933 } 6934 } 6935 } else { 6936 assert((Invalid || 6937 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && 6938 "should have a 'template<>' for this decl"); 6939 } 6940 6941 if (IsVariableTemplateSpecialization) { 6942 SourceLocation TemplateKWLoc = 6943 TemplateParamLists.size() > 0 6944 ? TemplateParamLists[0]->getTemplateLoc() 6945 : SourceLocation(); 6946 DeclResult Res = ActOnVarTemplateSpecialization( 6947 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 6948 IsPartialSpecialization); 6949 if (Res.isInvalid()) 6950 return nullptr; 6951 NewVD = cast<VarDecl>(Res.get()); 6952 AddToScope = false; 6953 } else if (D.isDecompositionDeclarator()) { 6954 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(), 6955 D.getIdentifierLoc(), R, TInfo, SC, 6956 Bindings); 6957 } else 6958 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), 6959 D.getIdentifierLoc(), II, R, TInfo, SC); 6960 6961 // If this is supposed to be a variable template, create it as such. 6962 if (IsVariableTemplate) { 6963 NewTemplate = 6964 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 6965 TemplateParams, NewVD); 6966 NewVD->setDescribedVarTemplate(NewTemplate); 6967 } 6968 6969 // If this decl has an auto type in need of deduction, make a note of the 6970 // Decl so we can diagnose uses of it in its own initializer. 6971 if (R->getContainedDeducedType()) 6972 ParsingInitForAutoVars.insert(NewVD); 6973 6974 if (D.isInvalidType() || Invalid) { 6975 NewVD->setInvalidDecl(); 6976 if (NewTemplate) 6977 NewTemplate->setInvalidDecl(); 6978 } 6979 6980 SetNestedNameSpecifier(*this, NewVD, D); 6981 6982 // If we have any template parameter lists that don't directly belong to 6983 // the variable (matching the scope specifier), store them. 6984 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 6985 if (TemplateParamLists.size() > VDTemplateParamLists) 6986 NewVD->setTemplateParameterListsInfo( 6987 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 6988 } 6989 6990 if (D.getDeclSpec().isInlineSpecified()) { 6991 if (!getLangOpts().CPlusPlus) { 6992 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6993 << 0; 6994 } else if (CurContext->isFunctionOrMethod()) { 6995 // 'inline' is not allowed on block scope variable declaration. 6996 Diag(D.getDeclSpec().getInlineSpecLoc(), 6997 diag::err_inline_declaration_block_scope) << Name 6998 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 6999 } else { 7000 Diag(D.getDeclSpec().getInlineSpecLoc(), 7001 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable 7002 : diag::ext_inline_variable); 7003 NewVD->setInlineSpecified(); 7004 } 7005 } 7006 7007 // Set the lexical context. If the declarator has a C++ scope specifier, the 7008 // lexical context will be different from the semantic context. 7009 NewVD->setLexicalDeclContext(CurContext); 7010 if (NewTemplate) 7011 NewTemplate->setLexicalDeclContext(CurContext); 7012 7013 if (IsLocalExternDecl) { 7014 if (D.isDecompositionDeclarator()) 7015 for (auto *B : Bindings) 7016 B->setLocalExternDecl(); 7017 else 7018 NewVD->setLocalExternDecl(); 7019 } 7020 7021 bool EmitTLSUnsupportedError = false; 7022 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 7023 // C++11 [dcl.stc]p4: 7024 // When thread_local is applied to a variable of block scope the 7025 // storage-class-specifier static is implied if it does not appear 7026 // explicitly. 7027 // Core issue: 'static' is not implied if the variable is declared 7028 // 'extern'. 7029 if (NewVD->hasLocalStorage() && 7030 (SCSpec != DeclSpec::SCS_unspecified || 7031 TSCS != DeclSpec::TSCS_thread_local || 7032 !DC->isFunctionOrMethod())) 7033 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7034 diag::err_thread_non_global) 7035 << DeclSpec::getSpecifierName(TSCS); 7036 else if (!Context.getTargetInfo().isTLSSupported()) { 7037 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { 7038 // Postpone error emission until we've collected attributes required to 7039 // figure out whether it's a host or device variable and whether the 7040 // error should be ignored. 7041 EmitTLSUnsupportedError = true; 7042 // We still need to mark the variable as TLS so it shows up in AST with 7043 // proper storage class for other tools to use even if we're not going 7044 // to emit any code for it. 7045 NewVD->setTSCSpec(TSCS); 7046 } else 7047 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7048 diag::err_thread_unsupported); 7049 } else 7050 NewVD->setTSCSpec(TSCS); 7051 } 7052 7053 switch (D.getDeclSpec().getConstexprSpecifier()) { 7054 case CSK_unspecified: 7055 break; 7056 7057 case CSK_consteval: 7058 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7059 diag::err_constexpr_wrong_decl_kind) 7060 << D.getDeclSpec().getConstexprSpecifier(); 7061 LLVM_FALLTHROUGH; 7062 7063 case CSK_constexpr: 7064 NewVD->setConstexpr(true); 7065 // C++1z [dcl.spec.constexpr]p1: 7066 // A static data member declared with the constexpr specifier is 7067 // implicitly an inline variable. 7068 if (NewVD->isStaticDataMember() && 7069 (getLangOpts().CPlusPlus17 || 7070 Context.getTargetInfo().getCXXABI().isMicrosoft())) 7071 NewVD->setImplicitlyInline(); 7072 break; 7073 7074 case CSK_constinit: 7075 if (!NewVD->hasGlobalStorage()) 7076 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7077 diag::err_constinit_local_variable); 7078 else 7079 NewVD->addAttr(ConstInitAttr::Create( 7080 Context, D.getDeclSpec().getConstexprSpecLoc(), 7081 AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit)); 7082 break; 7083 } 7084 7085 // C99 6.7.4p3 7086 // An inline definition of a function with external linkage shall 7087 // not contain a definition of a modifiable object with static or 7088 // thread storage duration... 7089 // We only apply this when the function is required to be defined 7090 // elsewhere, i.e. when the function is not 'extern inline'. Note 7091 // that a local variable with thread storage duration still has to 7092 // be marked 'static'. Also note that it's possible to get these 7093 // semantics in C++ using __attribute__((gnu_inline)). 7094 if (SC == SC_Static && S->getFnParent() != nullptr && 7095 !NewVD->getType().isConstQualified()) { 7096 FunctionDecl *CurFD = getCurFunctionDecl(); 7097 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 7098 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7099 diag::warn_static_local_in_extern_inline); 7100 MaybeSuggestAddingStaticToDecl(CurFD); 7101 } 7102 } 7103 7104 if (D.getDeclSpec().isModulePrivateSpecified()) { 7105 if (IsVariableTemplateSpecialization) 7106 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7107 << (IsPartialSpecialization ? 1 : 0) 7108 << FixItHint::CreateRemoval( 7109 D.getDeclSpec().getModulePrivateSpecLoc()); 7110 else if (IsMemberSpecialization) 7111 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7112 << 2 7113 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 7114 else if (NewVD->hasLocalStorage()) 7115 Diag(NewVD->getLocation(), diag::err_module_private_local) 7116 << 0 << NewVD->getDeclName() 7117 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 7118 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 7119 else { 7120 NewVD->setModulePrivate(); 7121 if (NewTemplate) 7122 NewTemplate->setModulePrivate(); 7123 for (auto *B : Bindings) 7124 B->setModulePrivate(); 7125 } 7126 } 7127 7128 if (getLangOpts().OpenCL) { 7129 7130 deduceOpenCLAddressSpace(NewVD); 7131 7132 diagnoseOpenCLTypes(S, *this, D, DC, NewVD->getType()); 7133 } 7134 7135 // Handle attributes prior to checking for duplicates in MergeVarDecl 7136 ProcessDeclAttributes(S, NewVD, D); 7137 7138 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { 7139 if (EmitTLSUnsupportedError && 7140 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || 7141 (getLangOpts().OpenMPIsDevice && 7142 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD)))) 7143 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7144 diag::err_thread_unsupported); 7145 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 7146 // storage [duration]." 7147 if (SC == SC_None && S->getFnParent() != nullptr && 7148 (NewVD->hasAttr<CUDASharedAttr>() || 7149 NewVD->hasAttr<CUDAConstantAttr>())) { 7150 NewVD->setStorageClass(SC_Static); 7151 } 7152 } 7153 7154 // Ensure that dllimport globals without explicit storage class are treated as 7155 // extern. The storage class is set above using parsed attributes. Now we can 7156 // check the VarDecl itself. 7157 assert(!NewVD->hasAttr<DLLImportAttr>() || 7158 NewVD->getAttr<DLLImportAttr>()->isInherited() || 7159 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 7160 7161 // In auto-retain/release, infer strong retension for variables of 7162 // retainable type. 7163 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 7164 NewVD->setInvalidDecl(); 7165 7166 // Handle GNU asm-label extension (encoded as an attribute). 7167 if (Expr *E = (Expr*)D.getAsmLabel()) { 7168 // The parser guarantees this is a string. 7169 StringLiteral *SE = cast<StringLiteral>(E); 7170 StringRef Label = SE->getString(); 7171 if (S->getFnParent() != nullptr) { 7172 switch (SC) { 7173 case SC_None: 7174 case SC_Auto: 7175 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 7176 break; 7177 case SC_Register: 7178 // Local Named register 7179 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 7180 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 7181 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7182 break; 7183 case SC_Static: 7184 case SC_Extern: 7185 case SC_PrivateExtern: 7186 break; 7187 } 7188 } else if (SC == SC_Register) { 7189 // Global Named register 7190 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 7191 const auto &TI = Context.getTargetInfo(); 7192 bool HasSizeMismatch; 7193 7194 if (!TI.isValidGCCRegisterName(Label)) 7195 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7196 else if (!TI.validateGlobalRegisterVariable(Label, 7197 Context.getTypeSize(R), 7198 HasSizeMismatch)) 7199 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 7200 else if (HasSizeMismatch) 7201 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 7202 } 7203 7204 if (!R->isIntegralType(Context) && !R->isPointerType()) { 7205 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type); 7206 NewVD->setInvalidDecl(true); 7207 } 7208 } 7209 7210 NewVD->addAttr(AsmLabelAttr::Create(Context, Label, 7211 /*IsLiteralLabel=*/true, 7212 SE->getStrTokenLoc(0))); 7213 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 7214 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 7215 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 7216 if (I != ExtnameUndeclaredIdentifiers.end()) { 7217 if (isDeclExternC(NewVD)) { 7218 NewVD->addAttr(I->second); 7219 ExtnameUndeclaredIdentifiers.erase(I); 7220 } else 7221 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 7222 << /*Variable*/1 << NewVD; 7223 } 7224 } 7225 7226 // Find the shadowed declaration before filtering for scope. 7227 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 7228 ? getShadowedDeclaration(NewVD, Previous) 7229 : nullptr; 7230 7231 // Don't consider existing declarations that are in a different 7232 // scope and are out-of-semantic-context declarations (if the new 7233 // declaration has linkage). 7234 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 7235 D.getCXXScopeSpec().isNotEmpty() || 7236 IsMemberSpecialization || 7237 IsVariableTemplateSpecialization); 7238 7239 // Check whether the previous declaration is in the same block scope. This 7240 // affects whether we merge types with it, per C++11 [dcl.array]p3. 7241 if (getLangOpts().CPlusPlus && 7242 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 7243 NewVD->setPreviousDeclInSameBlockScope( 7244 Previous.isSingleResult() && !Previous.isShadowed() && 7245 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 7246 7247 if (!getLangOpts().CPlusPlus) { 7248 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7249 } else { 7250 // If this is an explicit specialization of a static data member, check it. 7251 if (IsMemberSpecialization && !NewVD->isInvalidDecl() && 7252 CheckMemberSpecialization(NewVD, Previous)) 7253 NewVD->setInvalidDecl(); 7254 7255 // Merge the decl with the existing one if appropriate. 7256 if (!Previous.empty()) { 7257 if (Previous.isSingleResult() && 7258 isa<FieldDecl>(Previous.getFoundDecl()) && 7259 D.getCXXScopeSpec().isSet()) { 7260 // The user tried to define a non-static data member 7261 // out-of-line (C++ [dcl.meaning]p1). 7262 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 7263 << D.getCXXScopeSpec().getRange(); 7264 Previous.clear(); 7265 NewVD->setInvalidDecl(); 7266 } 7267 } else if (D.getCXXScopeSpec().isSet()) { 7268 // No previous declaration in the qualifying scope. 7269 Diag(D.getIdentifierLoc(), diag::err_no_member) 7270 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 7271 << D.getCXXScopeSpec().getRange(); 7272 NewVD->setInvalidDecl(); 7273 } 7274 7275 if (!IsVariableTemplateSpecialization) 7276 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7277 7278 if (NewTemplate) { 7279 VarTemplateDecl *PrevVarTemplate = 7280 NewVD->getPreviousDecl() 7281 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 7282 : nullptr; 7283 7284 // Check the template parameter list of this declaration, possibly 7285 // merging in the template parameter list from the previous variable 7286 // template declaration. 7287 if (CheckTemplateParameterList( 7288 TemplateParams, 7289 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 7290 : nullptr, 7291 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 7292 DC->isDependentContext()) 7293 ? TPC_ClassTemplateMember 7294 : TPC_VarTemplate)) 7295 NewVD->setInvalidDecl(); 7296 7297 // If we are providing an explicit specialization of a static variable 7298 // template, make a note of that. 7299 if (PrevVarTemplate && 7300 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 7301 PrevVarTemplate->setMemberSpecialization(); 7302 } 7303 } 7304 7305 // Diagnose shadowed variables iff this isn't a redeclaration. 7306 if (ShadowedDecl && !D.isRedeclaration()) 7307 CheckShadow(NewVD, ShadowedDecl, Previous); 7308 7309 ProcessPragmaWeak(S, NewVD); 7310 7311 // If this is the first declaration of an extern C variable, update 7312 // the map of such variables. 7313 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 7314 isIncompleteDeclExternC(*this, NewVD)) 7315 RegisterLocallyScopedExternCDecl(NewVD, S); 7316 7317 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 7318 MangleNumberingContext *MCtx; 7319 Decl *ManglingContextDecl; 7320 std::tie(MCtx, ManglingContextDecl) = 7321 getCurrentMangleNumberContext(NewVD->getDeclContext()); 7322 if (MCtx) { 7323 Context.setManglingNumber( 7324 NewVD, MCtx->getManglingNumber( 7325 NewVD, getMSManglingNumber(getLangOpts(), S))); 7326 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 7327 } 7328 } 7329 7330 // Special handling of variable named 'main'. 7331 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 7332 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 7333 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 7334 7335 // C++ [basic.start.main]p3 7336 // A program that declares a variable main at global scope is ill-formed. 7337 if (getLangOpts().CPlusPlus) 7338 Diag(D.getBeginLoc(), diag::err_main_global_variable); 7339 7340 // In C, and external-linkage variable named main results in undefined 7341 // behavior. 7342 else if (NewVD->hasExternalFormalLinkage()) 7343 Diag(D.getBeginLoc(), diag::warn_main_redefined); 7344 } 7345 7346 if (D.isRedeclaration() && !Previous.empty()) { 7347 NamedDecl *Prev = Previous.getRepresentativeDecl(); 7348 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization, 7349 D.isFunctionDefinition()); 7350 } 7351 7352 if (NewTemplate) { 7353 if (NewVD->isInvalidDecl()) 7354 NewTemplate->setInvalidDecl(); 7355 ActOnDocumentableDecl(NewTemplate); 7356 return NewTemplate; 7357 } 7358 7359 if (IsMemberSpecialization && !NewVD->isInvalidDecl()) 7360 CompleteMemberSpecialization(NewVD, Previous); 7361 7362 return NewVD; 7363 } 7364 7365 /// Enum describing the %select options in diag::warn_decl_shadow. 7366 enum ShadowedDeclKind { 7367 SDK_Local, 7368 SDK_Global, 7369 SDK_StaticMember, 7370 SDK_Field, 7371 SDK_Typedef, 7372 SDK_Using 7373 }; 7374 7375 /// Determine what kind of declaration we're shadowing. 7376 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 7377 const DeclContext *OldDC) { 7378 if (isa<TypeAliasDecl>(ShadowedDecl)) 7379 return SDK_Using; 7380 else if (isa<TypedefDecl>(ShadowedDecl)) 7381 return SDK_Typedef; 7382 else if (isa<RecordDecl>(OldDC)) 7383 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 7384 7385 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 7386 } 7387 7388 /// Return the location of the capture if the given lambda captures the given 7389 /// variable \p VD, or an invalid source location otherwise. 7390 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 7391 const VarDecl *VD) { 7392 for (const Capture &Capture : LSI->Captures) { 7393 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 7394 return Capture.getLocation(); 7395 } 7396 return SourceLocation(); 7397 } 7398 7399 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, 7400 const LookupResult &R) { 7401 // Only diagnose if we're shadowing an unambiguous field or variable. 7402 if (R.getResultKind() != LookupResult::Found) 7403 return false; 7404 7405 // Return false if warning is ignored. 7406 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); 7407 } 7408 7409 /// Return the declaration shadowed by the given variable \p D, or null 7410 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7411 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 7412 const LookupResult &R) { 7413 if (!shouldWarnIfShadowedDecl(Diags, R)) 7414 return nullptr; 7415 7416 // Don't diagnose declarations at file scope. 7417 if (D->hasGlobalStorage()) 7418 return nullptr; 7419 7420 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7421 return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl) 7422 ? ShadowedDecl 7423 : nullptr; 7424 } 7425 7426 /// Return the declaration shadowed by the given typedef \p D, or null 7427 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7428 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, 7429 const LookupResult &R) { 7430 // Don't warn if typedef declaration is part of a class 7431 if (D->getDeclContext()->isRecord()) 7432 return nullptr; 7433 7434 if (!shouldWarnIfShadowedDecl(Diags, R)) 7435 return nullptr; 7436 7437 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7438 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; 7439 } 7440 7441 /// Diagnose variable or built-in function shadowing. Implements 7442 /// -Wshadow. 7443 /// 7444 /// This method is called whenever a VarDecl is added to a "useful" 7445 /// scope. 7446 /// 7447 /// \param ShadowedDecl the declaration that is shadowed by the given variable 7448 /// \param R the lookup of the name 7449 /// 7450 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 7451 const LookupResult &R) { 7452 DeclContext *NewDC = D->getDeclContext(); 7453 7454 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 7455 // Fields are not shadowed by variables in C++ static methods. 7456 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 7457 if (MD->isStatic()) 7458 return; 7459 7460 // Fields shadowed by constructor parameters are a special case. Usually 7461 // the constructor initializes the field with the parameter. 7462 if (isa<CXXConstructorDecl>(NewDC)) 7463 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { 7464 // Remember that this was shadowed so we can either warn about its 7465 // modification or its existence depending on warning settings. 7466 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); 7467 return; 7468 } 7469 } 7470 7471 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 7472 if (shadowedVar->isExternC()) { 7473 // For shadowing external vars, make sure that we point to the global 7474 // declaration, not a locally scoped extern declaration. 7475 for (auto I : shadowedVar->redecls()) 7476 if (I->isFileVarDecl()) { 7477 ShadowedDecl = I; 7478 break; 7479 } 7480 } 7481 7482 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); 7483 7484 unsigned WarningDiag = diag::warn_decl_shadow; 7485 SourceLocation CaptureLoc; 7486 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && 7487 isa<CXXMethodDecl>(NewDC)) { 7488 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 7489 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 7490 if (RD->getLambdaCaptureDefault() == LCD_None) { 7491 // Try to avoid warnings for lambdas with an explicit capture list. 7492 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 7493 // Warn only when the lambda captures the shadowed decl explicitly. 7494 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 7495 if (CaptureLoc.isInvalid()) 7496 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 7497 } else { 7498 // Remember that this was shadowed so we can avoid the warning if the 7499 // shadowed decl isn't captured and the warning settings allow it. 7500 cast<LambdaScopeInfo>(getCurFunction()) 7501 ->ShadowingDecls.push_back( 7502 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); 7503 return; 7504 } 7505 } 7506 7507 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { 7508 // A variable can't shadow a local variable in an enclosing scope, if 7509 // they are separated by a non-capturing declaration context. 7510 for (DeclContext *ParentDC = NewDC; 7511 ParentDC && !ParentDC->Equals(OldDC); 7512 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { 7513 // Only block literals, captured statements, and lambda expressions 7514 // can capture; other scopes don't. 7515 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && 7516 !isLambdaCallOperator(ParentDC)) { 7517 return; 7518 } 7519 } 7520 } 7521 } 7522 } 7523 7524 // Only warn about certain kinds of shadowing for class members. 7525 if (NewDC && NewDC->isRecord()) { 7526 // In particular, don't warn about shadowing non-class members. 7527 if (!OldDC->isRecord()) 7528 return; 7529 7530 // TODO: should we warn about static data members shadowing 7531 // static data members from base classes? 7532 7533 // TODO: don't diagnose for inaccessible shadowed members. 7534 // This is hard to do perfectly because we might friend the 7535 // shadowing context, but that's just a false negative. 7536 } 7537 7538 7539 DeclarationName Name = R.getLookupName(); 7540 7541 // Emit warning and note. 7542 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 7543 return; 7544 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 7545 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 7546 if (!CaptureLoc.isInvalid()) 7547 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7548 << Name << /*explicitly*/ 1; 7549 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7550 } 7551 7552 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 7553 /// when these variables are captured by the lambda. 7554 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 7555 for (const auto &Shadow : LSI->ShadowingDecls) { 7556 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 7557 // Try to avoid the warning when the shadowed decl isn't captured. 7558 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 7559 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7560 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 7561 ? diag::warn_decl_shadow_uncaptured_local 7562 : diag::warn_decl_shadow) 7563 << Shadow.VD->getDeclName() 7564 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 7565 if (!CaptureLoc.isInvalid()) 7566 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7567 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 7568 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7569 } 7570 } 7571 7572 /// Check -Wshadow without the advantage of a previous lookup. 7573 void Sema::CheckShadow(Scope *S, VarDecl *D) { 7574 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 7575 return; 7576 7577 LookupResult R(*this, D->getDeclName(), D->getLocation(), 7578 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); 7579 LookupName(R, S); 7580 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 7581 CheckShadow(D, ShadowedDecl, R); 7582 } 7583 7584 /// Check if 'E', which is an expression that is about to be modified, refers 7585 /// to a constructor parameter that shadows a field. 7586 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 7587 // Quickly ignore expressions that can't be shadowing ctor parameters. 7588 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 7589 return; 7590 E = E->IgnoreParenImpCasts(); 7591 auto *DRE = dyn_cast<DeclRefExpr>(E); 7592 if (!DRE) 7593 return; 7594 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 7595 auto I = ShadowingDecls.find(D); 7596 if (I == ShadowingDecls.end()) 7597 return; 7598 const NamedDecl *ShadowedDecl = I->second; 7599 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7600 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 7601 Diag(D->getLocation(), diag::note_var_declared_here) << D; 7602 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7603 7604 // Avoid issuing multiple warnings about the same decl. 7605 ShadowingDecls.erase(I); 7606 } 7607 7608 /// Check for conflict between this global or extern "C" declaration and 7609 /// previous global or extern "C" declarations. This is only used in C++. 7610 template<typename T> 7611 static bool checkGlobalOrExternCConflict( 7612 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 7613 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 7614 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 7615 7616 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 7617 // The common case: this global doesn't conflict with any extern "C" 7618 // declaration. 7619 return false; 7620 } 7621 7622 if (Prev) { 7623 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 7624 // Both the old and new declarations have C language linkage. This is a 7625 // redeclaration. 7626 Previous.clear(); 7627 Previous.addDecl(Prev); 7628 return true; 7629 } 7630 7631 // This is a global, non-extern "C" declaration, and there is a previous 7632 // non-global extern "C" declaration. Diagnose if this is a variable 7633 // declaration. 7634 if (!isa<VarDecl>(ND)) 7635 return false; 7636 } else { 7637 // The declaration is extern "C". Check for any declaration in the 7638 // translation unit which might conflict. 7639 if (IsGlobal) { 7640 // We have already performed the lookup into the translation unit. 7641 IsGlobal = false; 7642 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7643 I != E; ++I) { 7644 if (isa<VarDecl>(*I)) { 7645 Prev = *I; 7646 break; 7647 } 7648 } 7649 } else { 7650 DeclContext::lookup_result R = 7651 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 7652 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 7653 I != E; ++I) { 7654 if (isa<VarDecl>(*I)) { 7655 Prev = *I; 7656 break; 7657 } 7658 // FIXME: If we have any other entity with this name in global scope, 7659 // the declaration is ill-formed, but that is a defect: it breaks the 7660 // 'stat' hack, for instance. Only variables can have mangled name 7661 // clashes with extern "C" declarations, so only they deserve a 7662 // diagnostic. 7663 } 7664 } 7665 7666 if (!Prev) 7667 return false; 7668 } 7669 7670 // Use the first declaration's location to ensure we point at something which 7671 // is lexically inside an extern "C" linkage-spec. 7672 assert(Prev && "should have found a previous declaration to diagnose"); 7673 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 7674 Prev = FD->getFirstDecl(); 7675 else 7676 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 7677 7678 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 7679 << IsGlobal << ND; 7680 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 7681 << IsGlobal; 7682 return false; 7683 } 7684 7685 /// Apply special rules for handling extern "C" declarations. Returns \c true 7686 /// if we have found that this is a redeclaration of some prior entity. 7687 /// 7688 /// Per C++ [dcl.link]p6: 7689 /// Two declarations [for a function or variable] with C language linkage 7690 /// with the same name that appear in different scopes refer to the same 7691 /// [entity]. An entity with C language linkage shall not be declared with 7692 /// the same name as an entity in global scope. 7693 template<typename T> 7694 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 7695 LookupResult &Previous) { 7696 if (!S.getLangOpts().CPlusPlus) { 7697 // In C, when declaring a global variable, look for a corresponding 'extern' 7698 // variable declared in function scope. We don't need this in C++, because 7699 // we find local extern decls in the surrounding file-scope DeclContext. 7700 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7701 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 7702 Previous.clear(); 7703 Previous.addDecl(Prev); 7704 return true; 7705 } 7706 } 7707 return false; 7708 } 7709 7710 // A declaration in the translation unit can conflict with an extern "C" 7711 // declaration. 7712 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 7713 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 7714 7715 // An extern "C" declaration can conflict with a declaration in the 7716 // translation unit or can be a redeclaration of an extern "C" declaration 7717 // in another scope. 7718 if (isIncompleteDeclExternC(S,ND)) 7719 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 7720 7721 // Neither global nor extern "C": nothing to do. 7722 return false; 7723 } 7724 7725 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 7726 // If the decl is already known invalid, don't check it. 7727 if (NewVD->isInvalidDecl()) 7728 return; 7729 7730 QualType T = NewVD->getType(); 7731 7732 // Defer checking an 'auto' type until its initializer is attached. 7733 if (T->isUndeducedType()) 7734 return; 7735 7736 if (NewVD->hasAttrs()) 7737 CheckAlignasUnderalignment(NewVD); 7738 7739 if (T->isObjCObjectType()) { 7740 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 7741 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 7742 T = Context.getObjCObjectPointerType(T); 7743 NewVD->setType(T); 7744 } 7745 7746 // Emit an error if an address space was applied to decl with local storage. 7747 // This includes arrays of objects with address space qualifiers, but not 7748 // automatic variables that point to other address spaces. 7749 // ISO/IEC TR 18037 S5.1.2 7750 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && 7751 T.getAddressSpace() != LangAS::Default) { 7752 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; 7753 NewVD->setInvalidDecl(); 7754 return; 7755 } 7756 7757 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 7758 // scope. 7759 if (getLangOpts().OpenCLVersion == 120 && 7760 !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") && 7761 NewVD->isStaticLocal()) { 7762 Diag(NewVD->getLocation(), diag::err_static_function_scope); 7763 NewVD->setInvalidDecl(); 7764 return; 7765 } 7766 7767 if (getLangOpts().OpenCL) { 7768 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 7769 if (NewVD->hasAttr<BlocksAttr>()) { 7770 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 7771 return; 7772 } 7773 7774 if (T->isBlockPointerType()) { 7775 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 7776 // can't use 'extern' storage class. 7777 if (!T.isConstQualified()) { 7778 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 7779 << 0 /*const*/; 7780 NewVD->setInvalidDecl(); 7781 return; 7782 } 7783 if (NewVD->hasExternalStorage()) { 7784 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 7785 NewVD->setInvalidDecl(); 7786 return; 7787 } 7788 } 7789 // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the 7790 // __constant address space. 7791 // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static 7792 // variables inside a function can also be declared in the global 7793 // address space. 7794 // C++ for OpenCL inherits rule from OpenCL C v2.0. 7795 // FIXME: Adding local AS in C++ for OpenCL might make sense. 7796 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 7797 NewVD->hasExternalStorage()) { 7798 if (!T->isSamplerT() && 7799 !(T.getAddressSpace() == LangAS::opencl_constant || 7800 (T.getAddressSpace() == LangAS::opencl_global && 7801 (getLangOpts().OpenCLVersion == 200 || 7802 getLangOpts().OpenCLCPlusPlus)))) { 7803 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 7804 if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus) 7805 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7806 << Scope << "global or constant"; 7807 else 7808 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7809 << Scope << "constant"; 7810 NewVD->setInvalidDecl(); 7811 return; 7812 } 7813 } else { 7814 if (T.getAddressSpace() == LangAS::opencl_global) { 7815 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7816 << 1 /*is any function*/ << "global"; 7817 NewVD->setInvalidDecl(); 7818 return; 7819 } 7820 if (T.getAddressSpace() == LangAS::opencl_constant || 7821 T.getAddressSpace() == LangAS::opencl_local) { 7822 FunctionDecl *FD = getCurFunctionDecl(); 7823 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables 7824 // in functions. 7825 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 7826 if (T.getAddressSpace() == LangAS::opencl_constant) 7827 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7828 << 0 /*non-kernel only*/ << "constant"; 7829 else 7830 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7831 << 0 /*non-kernel only*/ << "local"; 7832 NewVD->setInvalidDecl(); 7833 return; 7834 } 7835 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be 7836 // in the outermost scope of a kernel function. 7837 if (FD && FD->hasAttr<OpenCLKernelAttr>()) { 7838 if (!getCurScope()->isFunctionScope()) { 7839 if (T.getAddressSpace() == LangAS::opencl_constant) 7840 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7841 << "constant"; 7842 else 7843 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7844 << "local"; 7845 NewVD->setInvalidDecl(); 7846 return; 7847 } 7848 } 7849 } else if (T.getAddressSpace() != LangAS::opencl_private && 7850 // If we are parsing a template we didn't deduce an addr 7851 // space yet. 7852 T.getAddressSpace() != LangAS::Default) { 7853 // Do not allow other address spaces on automatic variable. 7854 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; 7855 NewVD->setInvalidDecl(); 7856 return; 7857 } 7858 } 7859 } 7860 7861 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 7862 && !NewVD->hasAttr<BlocksAttr>()) { 7863 if (getLangOpts().getGC() != LangOptions::NonGC) 7864 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 7865 else { 7866 assert(!getLangOpts().ObjCAutoRefCount); 7867 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 7868 } 7869 } 7870 7871 bool isVM = T->isVariablyModifiedType(); 7872 if (isVM || NewVD->hasAttr<CleanupAttr>() || 7873 NewVD->hasAttr<BlocksAttr>()) 7874 setFunctionHasBranchProtectedScope(); 7875 7876 if ((isVM && NewVD->hasLinkage()) || 7877 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 7878 bool SizeIsNegative; 7879 llvm::APSInt Oversized; 7880 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 7881 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized); 7882 QualType FixedT; 7883 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType()) 7884 FixedT = FixedTInfo->getType(); 7885 else if (FixedTInfo) { 7886 // Type and type-as-written are canonically different. We need to fix up 7887 // both types separately. 7888 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 7889 Oversized); 7890 } 7891 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) { 7892 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 7893 // FIXME: This won't give the correct result for 7894 // int a[10][n]; 7895 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 7896 7897 if (NewVD->isFileVarDecl()) 7898 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 7899 << SizeRange; 7900 else if (NewVD->isStaticLocal()) 7901 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 7902 << SizeRange; 7903 else 7904 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 7905 << SizeRange; 7906 NewVD->setInvalidDecl(); 7907 return; 7908 } 7909 7910 if (!FixedTInfo) { 7911 if (NewVD->isFileVarDecl()) 7912 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 7913 else 7914 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 7915 NewVD->setInvalidDecl(); 7916 return; 7917 } 7918 7919 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 7920 NewVD->setType(FixedT); 7921 NewVD->setTypeSourceInfo(FixedTInfo); 7922 } 7923 7924 if (T->isVoidType()) { 7925 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 7926 // of objects and functions. 7927 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 7928 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 7929 << T; 7930 NewVD->setInvalidDecl(); 7931 return; 7932 } 7933 } 7934 7935 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 7936 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 7937 NewVD->setInvalidDecl(); 7938 return; 7939 } 7940 7941 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 7942 Diag(NewVD->getLocation(), diag::err_block_on_vm); 7943 NewVD->setInvalidDecl(); 7944 return; 7945 } 7946 7947 if (NewVD->isConstexpr() && !T->isDependentType() && 7948 RequireLiteralType(NewVD->getLocation(), T, 7949 diag::err_constexpr_var_non_literal)) { 7950 NewVD->setInvalidDecl(); 7951 return; 7952 } 7953 } 7954 7955 /// Perform semantic checking on a newly-created variable 7956 /// declaration. 7957 /// 7958 /// This routine performs all of the type-checking required for a 7959 /// variable declaration once it has been built. It is used both to 7960 /// check variables after they have been parsed and their declarators 7961 /// have been translated into a declaration, and to check variables 7962 /// that have been instantiated from a template. 7963 /// 7964 /// Sets NewVD->isInvalidDecl() if an error was encountered. 7965 /// 7966 /// Returns true if the variable declaration is a redeclaration. 7967 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 7968 CheckVariableDeclarationType(NewVD); 7969 7970 // If the decl is already known invalid, don't check it. 7971 if (NewVD->isInvalidDecl()) 7972 return false; 7973 7974 // If we did not find anything by this name, look for a non-visible 7975 // extern "C" declaration with the same name. 7976 if (Previous.empty() && 7977 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 7978 Previous.setShadowed(); 7979 7980 if (!Previous.empty()) { 7981 MergeVarDecl(NewVD, Previous); 7982 return true; 7983 } 7984 return false; 7985 } 7986 7987 namespace { 7988 struct FindOverriddenMethod { 7989 Sema *S; 7990 CXXMethodDecl *Method; 7991 7992 /// Member lookup function that determines whether a given C++ 7993 /// method overrides a method in a base class, to be used with 7994 /// CXXRecordDecl::lookupInBases(). 7995 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 7996 RecordDecl *BaseRecord = 7997 Specifier->getType()->castAs<RecordType>()->getDecl(); 7998 7999 DeclarationName Name = Method->getDeclName(); 8000 8001 // FIXME: Do we care about other names here too? 8002 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8003 // We really want to find the base class destructor here. 8004 QualType T = S->Context.getTypeDeclType(BaseRecord); 8005 CanQualType CT = S->Context.getCanonicalType(T); 8006 8007 Name = S->Context.DeclarationNames.getCXXDestructorName(CT); 8008 } 8009 8010 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 8011 Path.Decls = Path.Decls.slice(1)) { 8012 NamedDecl *D = Path.Decls.front(); 8013 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 8014 if (MD->isVirtual() && 8015 !S->IsOverload( 8016 Method, MD, /*UseMemberUsingDeclRules=*/false, 8017 /*ConsiderCudaAttrs=*/true, 8018 // C++2a [class.virtual]p2 does not consider requires clauses 8019 // when overriding. 8020 /*ConsiderRequiresClauses=*/false)) 8021 return true; 8022 } 8023 } 8024 8025 return false; 8026 } 8027 }; 8028 8029 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 8030 } // end anonymous namespace 8031 8032 /// Report an error regarding overriding, along with any relevant 8033 /// overridden methods. 8034 /// 8035 /// \param DiagID the primary error to report. 8036 /// \param MD the overriding method. 8037 /// \param OEK which overrides to include as notes. 8038 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 8039 OverrideErrorKind OEK = OEK_All) { 8040 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 8041 for (const CXXMethodDecl *O : MD->overridden_methods()) { 8042 // This check (& the OEK parameter) could be replaced by a predicate, but 8043 // without lambdas that would be overkill. This is still nicer than writing 8044 // out the diag loop 3 times. 8045 if ((OEK == OEK_All) || 8046 (OEK == OEK_NonDeleted && !O->isDeleted()) || 8047 (OEK == OEK_Deleted && O->isDeleted())) 8048 S.Diag(O->getLocation(), diag::note_overridden_virtual_function); 8049 } 8050 } 8051 8052 /// AddOverriddenMethods - See if a method overrides any in the base classes, 8053 /// and if so, check that it's a valid override and remember it. 8054 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 8055 // Look for methods in base classes that this method might override. 8056 CXXBasePaths Paths; 8057 FindOverriddenMethod FOM; 8058 FOM.Method = MD; 8059 FOM.S = this; 8060 bool hasDeletedOverridenMethods = false; 8061 bool hasNonDeletedOverridenMethods = false; 8062 bool AddedAny = false; 8063 if (DC->lookupInBases(FOM, Paths)) { 8064 for (auto *I : Paths.found_decls()) { 8065 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { 8066 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 8067 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 8068 !CheckOverridingFunctionAttributes(MD, OldMD) && 8069 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 8070 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 8071 hasDeletedOverridenMethods |= OldMD->isDeleted(); 8072 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 8073 AddedAny = true; 8074 } 8075 } 8076 } 8077 } 8078 8079 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 8080 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 8081 } 8082 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 8083 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 8084 } 8085 8086 return AddedAny; 8087 } 8088 8089 namespace { 8090 // Struct for holding all of the extra arguments needed by 8091 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 8092 struct ActOnFDArgs { 8093 Scope *S; 8094 Declarator &D; 8095 MultiTemplateParamsArg TemplateParamLists; 8096 bool AddToScope; 8097 }; 8098 } // end anonymous namespace 8099 8100 namespace { 8101 8102 // Callback to only accept typo corrections that have a non-zero edit distance. 8103 // Also only accept corrections that have the same parent decl. 8104 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback { 8105 public: 8106 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 8107 CXXRecordDecl *Parent) 8108 : Context(Context), OriginalFD(TypoFD), 8109 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 8110 8111 bool ValidateCandidate(const TypoCorrection &candidate) override { 8112 if (candidate.getEditDistance() == 0) 8113 return false; 8114 8115 SmallVector<unsigned, 1> MismatchedParams; 8116 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 8117 CDeclEnd = candidate.end(); 8118 CDecl != CDeclEnd; ++CDecl) { 8119 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8120 8121 if (FD && !FD->hasBody() && 8122 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 8123 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 8124 CXXRecordDecl *Parent = MD->getParent(); 8125 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 8126 return true; 8127 } else if (!ExpectedParent) { 8128 return true; 8129 } 8130 } 8131 } 8132 8133 return false; 8134 } 8135 8136 std::unique_ptr<CorrectionCandidateCallback> clone() override { 8137 return std::make_unique<DifferentNameValidatorCCC>(*this); 8138 } 8139 8140 private: 8141 ASTContext &Context; 8142 FunctionDecl *OriginalFD; 8143 CXXRecordDecl *ExpectedParent; 8144 }; 8145 8146 } // end anonymous namespace 8147 8148 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { 8149 TypoCorrectedFunctionDefinitions.insert(F); 8150 } 8151 8152 /// Generate diagnostics for an invalid function redeclaration. 8153 /// 8154 /// This routine handles generating the diagnostic messages for an invalid 8155 /// function redeclaration, including finding possible similar declarations 8156 /// or performing typo correction if there are no previous declarations with 8157 /// the same name. 8158 /// 8159 /// Returns a NamedDecl iff typo correction was performed and substituting in 8160 /// the new declaration name does not cause new errors. 8161 static NamedDecl *DiagnoseInvalidRedeclaration( 8162 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 8163 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 8164 DeclarationName Name = NewFD->getDeclName(); 8165 DeclContext *NewDC = NewFD->getDeclContext(); 8166 SmallVector<unsigned, 1> MismatchedParams; 8167 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 8168 TypoCorrection Correction; 8169 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 8170 unsigned DiagMsg = 8171 IsLocalFriend ? diag::err_no_matching_local_friend : 8172 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match : 8173 diag::err_member_decl_does_not_match; 8174 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 8175 IsLocalFriend ? Sema::LookupLocalFriendName 8176 : Sema::LookupOrdinaryName, 8177 Sema::ForVisibleRedeclaration); 8178 8179 NewFD->setInvalidDecl(); 8180 if (IsLocalFriend) 8181 SemaRef.LookupName(Prev, S); 8182 else 8183 SemaRef.LookupQualifiedName(Prev, NewDC); 8184 assert(!Prev.isAmbiguous() && 8185 "Cannot have an ambiguity in previous-declaration lookup"); 8186 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 8187 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD, 8188 MD ? MD->getParent() : nullptr); 8189 if (!Prev.empty()) { 8190 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 8191 Func != FuncEnd; ++Func) { 8192 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 8193 if (FD && 8194 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8195 // Add 1 to the index so that 0 can mean the mismatch didn't 8196 // involve a parameter 8197 unsigned ParamNum = 8198 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 8199 NearMatches.push_back(std::make_pair(FD, ParamNum)); 8200 } 8201 } 8202 // If the qualified name lookup yielded nothing, try typo correction 8203 } else if ((Correction = SemaRef.CorrectTypo( 8204 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 8205 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery, 8206 IsLocalFriend ? nullptr : NewDC))) { 8207 // Set up everything for the call to ActOnFunctionDeclarator 8208 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 8209 ExtraArgs.D.getIdentifierLoc()); 8210 Previous.clear(); 8211 Previous.setLookupName(Correction.getCorrection()); 8212 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 8213 CDeclEnd = Correction.end(); 8214 CDecl != CDeclEnd; ++CDecl) { 8215 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8216 if (FD && !FD->hasBody() && 8217 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8218 Previous.addDecl(FD); 8219 } 8220 } 8221 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 8222 8223 NamedDecl *Result; 8224 // Retry building the function declaration with the new previous 8225 // declarations, and with errors suppressed. 8226 { 8227 // Trap errors. 8228 Sema::SFINAETrap Trap(SemaRef); 8229 8230 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 8231 // pieces need to verify the typo-corrected C++ declaration and hopefully 8232 // eliminate the need for the parameter pack ExtraArgs. 8233 Result = SemaRef.ActOnFunctionDeclarator( 8234 ExtraArgs.S, ExtraArgs.D, 8235 Correction.getCorrectionDecl()->getDeclContext(), 8236 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 8237 ExtraArgs.AddToScope); 8238 8239 if (Trap.hasErrorOccurred()) 8240 Result = nullptr; 8241 } 8242 8243 if (Result) { 8244 // Determine which correction we picked. 8245 Decl *Canonical = Result->getCanonicalDecl(); 8246 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 8247 I != E; ++I) 8248 if ((*I)->getCanonicalDecl() == Canonical) 8249 Correction.setCorrectionDecl(*I); 8250 8251 // Let Sema know about the correction. 8252 SemaRef.MarkTypoCorrectedFunctionDefinition(Result); 8253 SemaRef.diagnoseTypo( 8254 Correction, 8255 SemaRef.PDiag(IsLocalFriend 8256 ? diag::err_no_matching_local_friend_suggest 8257 : diag::err_member_decl_does_not_match_suggest) 8258 << Name << NewDC << IsDefinition); 8259 return Result; 8260 } 8261 8262 // Pretend the typo correction never occurred 8263 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 8264 ExtraArgs.D.getIdentifierLoc()); 8265 ExtraArgs.D.setRedeclaration(wasRedeclaration); 8266 Previous.clear(); 8267 Previous.setLookupName(Name); 8268 } 8269 8270 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 8271 << Name << NewDC << IsDefinition << NewFD->getLocation(); 8272 8273 bool NewFDisConst = false; 8274 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 8275 NewFDisConst = NewMD->isConst(); 8276 8277 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 8278 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 8279 NearMatch != NearMatchEnd; ++NearMatch) { 8280 FunctionDecl *FD = NearMatch->first; 8281 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 8282 bool FDisConst = MD && MD->isConst(); 8283 bool IsMember = MD || !IsLocalFriend; 8284 8285 // FIXME: These notes are poorly worded for the local friend case. 8286 if (unsigned Idx = NearMatch->second) { 8287 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 8288 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 8289 if (Loc.isInvalid()) Loc = FD->getLocation(); 8290 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 8291 : diag::note_local_decl_close_param_match) 8292 << Idx << FDParam->getType() 8293 << NewFD->getParamDecl(Idx - 1)->getType(); 8294 } else if (FDisConst != NewFDisConst) { 8295 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 8296 << NewFDisConst << FD->getSourceRange().getEnd(); 8297 } else 8298 SemaRef.Diag(FD->getLocation(), 8299 IsMember ? diag::note_member_def_close_match 8300 : diag::note_local_decl_close_match); 8301 } 8302 return nullptr; 8303 } 8304 8305 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 8306 switch (D.getDeclSpec().getStorageClassSpec()) { 8307 default: llvm_unreachable("Unknown storage class!"); 8308 case DeclSpec::SCS_auto: 8309 case DeclSpec::SCS_register: 8310 case DeclSpec::SCS_mutable: 8311 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8312 diag::err_typecheck_sclass_func); 8313 D.getMutableDeclSpec().ClearStorageClassSpecs(); 8314 D.setInvalidType(); 8315 break; 8316 case DeclSpec::SCS_unspecified: break; 8317 case DeclSpec::SCS_extern: 8318 if (D.getDeclSpec().isExternInLinkageSpec()) 8319 return SC_None; 8320 return SC_Extern; 8321 case DeclSpec::SCS_static: { 8322 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 8323 // C99 6.7.1p5: 8324 // The declaration of an identifier for a function that has 8325 // block scope shall have no explicit storage-class specifier 8326 // other than extern 8327 // See also (C++ [dcl.stc]p4). 8328 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8329 diag::err_static_block_func); 8330 break; 8331 } else 8332 return SC_Static; 8333 } 8334 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 8335 } 8336 8337 // No explicit storage class has already been returned 8338 return SC_None; 8339 } 8340 8341 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 8342 DeclContext *DC, QualType &R, 8343 TypeSourceInfo *TInfo, 8344 StorageClass SC, 8345 bool &IsVirtualOkay) { 8346 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 8347 DeclarationName Name = NameInfo.getName(); 8348 8349 FunctionDecl *NewFD = nullptr; 8350 bool isInline = D.getDeclSpec().isInlineSpecified(); 8351 8352 if (!SemaRef.getLangOpts().CPlusPlus) { 8353 // Determine whether the function was written with a 8354 // prototype. This true when: 8355 // - there is a prototype in the declarator, or 8356 // - the type R of the function is some kind of typedef or other non- 8357 // attributed reference to a type name (which eventually refers to a 8358 // function type). 8359 bool HasPrototype = 8360 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 8361 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 8362 8363 NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, 8364 R, TInfo, SC, isInline, HasPrototype, 8365 CSK_unspecified, 8366 /*TrailingRequiresClause=*/nullptr); 8367 if (D.isInvalidType()) 8368 NewFD->setInvalidDecl(); 8369 8370 return NewFD; 8371 } 8372 8373 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier(); 8374 8375 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 8376 if (ConstexprKind == CSK_constinit) { 8377 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(), 8378 diag::err_constexpr_wrong_decl_kind) 8379 << ConstexprKind; 8380 ConstexprKind = CSK_unspecified; 8381 D.getMutableDeclSpec().ClearConstexprSpec(); 8382 } 8383 Expr *TrailingRequiresClause = D.getTrailingRequiresClause(); 8384 8385 // Check that the return type is not an abstract class type. 8386 // For record types, this is done by the AbstractClassUsageDiagnoser once 8387 // the class has been completely parsed. 8388 if (!DC->isRecord() && 8389 SemaRef.RequireNonAbstractType( 8390 D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(), 8391 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 8392 D.setInvalidType(); 8393 8394 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 8395 // This is a C++ constructor declaration. 8396 assert(DC->isRecord() && 8397 "Constructors can only be declared in a member context"); 8398 8399 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 8400 return CXXConstructorDecl::Create( 8401 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8402 TInfo, ExplicitSpecifier, isInline, 8403 /*isImplicitlyDeclared=*/false, ConstexprKind, InheritedConstructor(), 8404 TrailingRequiresClause); 8405 8406 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8407 // This is a C++ destructor declaration. 8408 if (DC->isRecord()) { 8409 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 8410 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 8411 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 8412 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo, 8413 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind, 8414 TrailingRequiresClause); 8415 8416 // If the destructor needs an implicit exception specification, set it 8417 // now. FIXME: It'd be nice to be able to create the right type to start 8418 // with, but the type needs to reference the destructor declaration. 8419 if (SemaRef.getLangOpts().CPlusPlus11) 8420 SemaRef.AdjustDestructorExceptionSpec(NewDD); 8421 8422 IsVirtualOkay = true; 8423 return NewDD; 8424 8425 } else { 8426 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 8427 D.setInvalidType(); 8428 8429 // Create a FunctionDecl to satisfy the function definition parsing 8430 // code path. 8431 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8432 D.getIdentifierLoc(), Name, R, TInfo, SC, 8433 isInline, 8434 /*hasPrototype=*/true, ConstexprKind, 8435 TrailingRequiresClause); 8436 } 8437 8438 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 8439 if (!DC->isRecord()) { 8440 SemaRef.Diag(D.getIdentifierLoc(), 8441 diag::err_conv_function_not_member); 8442 return nullptr; 8443 } 8444 8445 SemaRef.CheckConversionDeclarator(D, R, SC); 8446 if (D.isInvalidType()) 8447 return nullptr; 8448 8449 IsVirtualOkay = true; 8450 return CXXConversionDecl::Create( 8451 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8452 TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation(), 8453 TrailingRequiresClause); 8454 8455 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 8456 if (TrailingRequiresClause) 8457 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(), 8458 diag::err_trailing_requires_clause_on_deduction_guide) 8459 << TrailingRequiresClause->getSourceRange(); 8460 SemaRef.CheckDeductionGuideDeclarator(D, R, SC); 8461 8462 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8463 ExplicitSpecifier, NameInfo, R, TInfo, 8464 D.getEndLoc()); 8465 } else if (DC->isRecord()) { 8466 // If the name of the function is the same as the name of the record, 8467 // then this must be an invalid constructor that has a return type. 8468 // (The parser checks for a return type and makes the declarator a 8469 // constructor if it has no return type). 8470 if (Name.getAsIdentifierInfo() && 8471 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 8472 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 8473 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8474 << SourceRange(D.getIdentifierLoc()); 8475 return nullptr; 8476 } 8477 8478 // This is a C++ method declaration. 8479 CXXMethodDecl *Ret = CXXMethodDecl::Create( 8480 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8481 TInfo, SC, isInline, ConstexprKind, SourceLocation(), 8482 TrailingRequiresClause); 8483 IsVirtualOkay = !Ret->isStatic(); 8484 return Ret; 8485 } else { 8486 bool isFriend = 8487 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 8488 if (!isFriend && SemaRef.CurContext->isRecord()) 8489 return nullptr; 8490 8491 // Determine whether the function was written with a 8492 // prototype. This true when: 8493 // - we're in C++ (where every function has a prototype), 8494 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, 8495 R, TInfo, SC, isInline, true /*HasPrototype*/, 8496 ConstexprKind, TrailingRequiresClause); 8497 } 8498 } 8499 8500 enum OpenCLParamType { 8501 ValidKernelParam, 8502 PtrPtrKernelParam, 8503 PtrKernelParam, 8504 InvalidAddrSpacePtrKernelParam, 8505 InvalidKernelParam, 8506 RecordKernelParam 8507 }; 8508 8509 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) { 8510 // Size dependent types are just typedefs to normal integer types 8511 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to 8512 // integers other than by their names. 8513 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"}; 8514 8515 // Remove typedefs one by one until we reach a typedef 8516 // for a size dependent type. 8517 QualType DesugaredTy = Ty; 8518 do { 8519 ArrayRef<StringRef> Names(SizeTypeNames); 8520 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString()); 8521 if (Names.end() != Match) 8522 return true; 8523 8524 Ty = DesugaredTy; 8525 DesugaredTy = Ty.getSingleStepDesugaredType(C); 8526 } while (DesugaredTy != Ty); 8527 8528 return false; 8529 } 8530 8531 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 8532 if (PT->isPointerType()) { 8533 QualType PointeeType = PT->getPointeeType(); 8534 if (PointeeType->isPointerType()) 8535 return PtrPtrKernelParam; 8536 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 8537 PointeeType.getAddressSpace() == LangAS::opencl_private || 8538 PointeeType.getAddressSpace() == LangAS::Default) 8539 return InvalidAddrSpacePtrKernelParam; 8540 return PtrKernelParam; 8541 } 8542 8543 // OpenCL v1.2 s6.9.k: 8544 // Arguments to kernel functions in a program cannot be declared with the 8545 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8546 // uintptr_t or a struct and/or union that contain fields declared to be one 8547 // of these built-in scalar types. 8548 if (isOpenCLSizeDependentType(S.getASTContext(), PT)) 8549 return InvalidKernelParam; 8550 8551 if (PT->isImageType()) 8552 return PtrKernelParam; 8553 8554 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) 8555 return InvalidKernelParam; 8556 8557 // OpenCL extension spec v1.2 s9.5: 8558 // This extension adds support for half scalar and vector types as built-in 8559 // types that can be used for arithmetic operations, conversions etc. 8560 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType()) 8561 return InvalidKernelParam; 8562 8563 if (PT->isRecordType()) 8564 return RecordKernelParam; 8565 8566 // Look into an array argument to check if it has a forbidden type. 8567 if (PT->isArrayType()) { 8568 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType(); 8569 // Call ourself to check an underlying type of an array. Since the 8570 // getPointeeOrArrayElementType returns an innermost type which is not an 8571 // array, this recursive call only happens once. 8572 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0)); 8573 } 8574 8575 return ValidKernelParam; 8576 } 8577 8578 static void checkIsValidOpenCLKernelParameter( 8579 Sema &S, 8580 Declarator &D, 8581 ParmVarDecl *Param, 8582 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 8583 QualType PT = Param->getType(); 8584 8585 // Cache the valid types we encounter to avoid rechecking structs that are 8586 // used again 8587 if (ValidTypes.count(PT.getTypePtr())) 8588 return; 8589 8590 switch (getOpenCLKernelParameterType(S, PT)) { 8591 case PtrPtrKernelParam: 8592 // OpenCL v1.2 s6.9.a: 8593 // A kernel function argument cannot be declared as a 8594 // pointer to a pointer type. 8595 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 8596 D.setInvalidType(); 8597 return; 8598 8599 case InvalidAddrSpacePtrKernelParam: 8600 // OpenCL v1.0 s6.5: 8601 // __kernel function arguments declared to be a pointer of a type can point 8602 // to one of the following address spaces only : __global, __local or 8603 // __constant. 8604 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 8605 D.setInvalidType(); 8606 return; 8607 8608 // OpenCL v1.2 s6.9.k: 8609 // Arguments to kernel functions in a program cannot be declared with the 8610 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8611 // uintptr_t or a struct and/or union that contain fields declared to be 8612 // one of these built-in scalar types. 8613 8614 case InvalidKernelParam: 8615 // OpenCL v1.2 s6.8 n: 8616 // A kernel function argument cannot be declared 8617 // of event_t type. 8618 // Do not diagnose half type since it is diagnosed as invalid argument 8619 // type for any function elsewhere. 8620 if (!PT->isHalfType()) { 8621 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8622 8623 // Explain what typedefs are involved. 8624 const TypedefType *Typedef = nullptr; 8625 while ((Typedef = PT->getAs<TypedefType>())) { 8626 SourceLocation Loc = Typedef->getDecl()->getLocation(); 8627 // SourceLocation may be invalid for a built-in type. 8628 if (Loc.isValid()) 8629 S.Diag(Loc, diag::note_entity_declared_at) << PT; 8630 PT = Typedef->desugar(); 8631 } 8632 } 8633 8634 D.setInvalidType(); 8635 return; 8636 8637 case PtrKernelParam: 8638 case ValidKernelParam: 8639 ValidTypes.insert(PT.getTypePtr()); 8640 return; 8641 8642 case RecordKernelParam: 8643 break; 8644 } 8645 8646 // Track nested structs we will inspect 8647 SmallVector<const Decl *, 4> VisitStack; 8648 8649 // Track where we are in the nested structs. Items will migrate from 8650 // VisitStack to HistoryStack as we do the DFS for bad field. 8651 SmallVector<const FieldDecl *, 4> HistoryStack; 8652 HistoryStack.push_back(nullptr); 8653 8654 // At this point we already handled everything except of a RecordType or 8655 // an ArrayType of a RecordType. 8656 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type."); 8657 const RecordType *RecTy = 8658 PT->getPointeeOrArrayElementType()->getAs<RecordType>(); 8659 const RecordDecl *OrigRecDecl = RecTy->getDecl(); 8660 8661 VisitStack.push_back(RecTy->getDecl()); 8662 assert(VisitStack.back() && "First decl null?"); 8663 8664 do { 8665 const Decl *Next = VisitStack.pop_back_val(); 8666 if (!Next) { 8667 assert(!HistoryStack.empty()); 8668 // Found a marker, we have gone up a level 8669 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 8670 ValidTypes.insert(Hist->getType().getTypePtr()); 8671 8672 continue; 8673 } 8674 8675 // Adds everything except the original parameter declaration (which is not a 8676 // field itself) to the history stack. 8677 const RecordDecl *RD; 8678 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 8679 HistoryStack.push_back(Field); 8680 8681 QualType FieldTy = Field->getType(); 8682 // Other field types (known to be valid or invalid) are handled while we 8683 // walk around RecordDecl::fields(). 8684 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) && 8685 "Unexpected type."); 8686 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType(); 8687 8688 RD = FieldRecTy->castAs<RecordType>()->getDecl(); 8689 } else { 8690 RD = cast<RecordDecl>(Next); 8691 } 8692 8693 // Add a null marker so we know when we've gone back up a level 8694 VisitStack.push_back(nullptr); 8695 8696 for (const auto *FD : RD->fields()) { 8697 QualType QT = FD->getType(); 8698 8699 if (ValidTypes.count(QT.getTypePtr())) 8700 continue; 8701 8702 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 8703 if (ParamType == ValidKernelParam) 8704 continue; 8705 8706 if (ParamType == RecordKernelParam) { 8707 VisitStack.push_back(FD); 8708 continue; 8709 } 8710 8711 // OpenCL v1.2 s6.9.p: 8712 // Arguments to kernel functions that are declared to be a struct or union 8713 // do not allow OpenCL objects to be passed as elements of the struct or 8714 // union. 8715 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 8716 ParamType == InvalidAddrSpacePtrKernelParam) { 8717 S.Diag(Param->getLocation(), 8718 diag::err_record_with_pointers_kernel_param) 8719 << PT->isUnionType() 8720 << PT; 8721 } else { 8722 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8723 } 8724 8725 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type) 8726 << OrigRecDecl->getDeclName(); 8727 8728 // We have an error, now let's go back up through history and show where 8729 // the offending field came from 8730 for (ArrayRef<const FieldDecl *>::const_iterator 8731 I = HistoryStack.begin() + 1, 8732 E = HistoryStack.end(); 8733 I != E; ++I) { 8734 const FieldDecl *OuterField = *I; 8735 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 8736 << OuterField->getType(); 8737 } 8738 8739 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 8740 << QT->isPointerType() 8741 << QT; 8742 D.setInvalidType(); 8743 return; 8744 } 8745 } while (!VisitStack.empty()); 8746 } 8747 8748 /// Find the DeclContext in which a tag is implicitly declared if we see an 8749 /// elaborated type specifier in the specified context, and lookup finds 8750 /// nothing. 8751 static DeclContext *getTagInjectionContext(DeclContext *DC) { 8752 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 8753 DC = DC->getParent(); 8754 return DC; 8755 } 8756 8757 /// Find the Scope in which a tag is implicitly declared if we see an 8758 /// elaborated type specifier in the specified context, and lookup finds 8759 /// nothing. 8760 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 8761 while (S->isClassScope() || 8762 (LangOpts.CPlusPlus && 8763 S->isFunctionPrototypeScope()) || 8764 ((S->getFlags() & Scope::DeclScope) == 0) || 8765 (S->getEntity() && S->getEntity()->isTransparentContext())) 8766 S = S->getParent(); 8767 return S; 8768 } 8769 8770 NamedDecl* 8771 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 8772 TypeSourceInfo *TInfo, LookupResult &Previous, 8773 MultiTemplateParamsArg TemplateParamListsRef, 8774 bool &AddToScope) { 8775 QualType R = TInfo->getType(); 8776 8777 assert(R->isFunctionType()); 8778 SmallVector<TemplateParameterList *, 4> TemplateParamLists; 8779 for (TemplateParameterList *TPL : TemplateParamListsRef) 8780 TemplateParamLists.push_back(TPL); 8781 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) { 8782 if (!TemplateParamLists.empty() && 8783 Invented->getDepth() == TemplateParamLists.back()->getDepth()) 8784 TemplateParamLists.back() = Invented; 8785 else 8786 TemplateParamLists.push_back(Invented); 8787 } 8788 8789 // TODO: consider using NameInfo for diagnostic. 8790 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 8791 DeclarationName Name = NameInfo.getName(); 8792 StorageClass SC = getFunctionStorageClass(*this, D); 8793 8794 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 8795 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 8796 diag::err_invalid_thread) 8797 << DeclSpec::getSpecifierName(TSCS); 8798 8799 if (D.isFirstDeclarationOfMember()) 8800 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 8801 D.getIdentifierLoc()); 8802 8803 bool isFriend = false; 8804 FunctionTemplateDecl *FunctionTemplate = nullptr; 8805 bool isMemberSpecialization = false; 8806 bool isFunctionTemplateSpecialization = false; 8807 8808 bool isDependentClassScopeExplicitSpecialization = false; 8809 bool HasExplicitTemplateArgs = false; 8810 TemplateArgumentListInfo TemplateArgs; 8811 8812 bool isVirtualOkay = false; 8813 8814 DeclContext *OriginalDC = DC; 8815 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 8816 8817 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 8818 isVirtualOkay); 8819 if (!NewFD) return nullptr; 8820 8821 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 8822 NewFD->setTopLevelDeclInObjCContainer(); 8823 8824 // Set the lexical context. If this is a function-scope declaration, or has a 8825 // C++ scope specifier, or is the object of a friend declaration, the lexical 8826 // context will be different from the semantic context. 8827 NewFD->setLexicalDeclContext(CurContext); 8828 8829 if (IsLocalExternDecl) 8830 NewFD->setLocalExternDecl(); 8831 8832 if (getLangOpts().CPlusPlus) { 8833 bool isInline = D.getDeclSpec().isInlineSpecified(); 8834 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 8835 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier(); 8836 isFriend = D.getDeclSpec().isFriendSpecified(); 8837 if (isFriend && !isInline && D.isFunctionDefinition()) { 8838 // C++ [class.friend]p5 8839 // A function can be defined in a friend declaration of a 8840 // class . . . . Such a function is implicitly inline. 8841 NewFD->setImplicitlyInline(); 8842 } 8843 8844 // If this is a method defined in an __interface, and is not a constructor 8845 // or an overloaded operator, then set the pure flag (isVirtual will already 8846 // return true). 8847 if (const CXXRecordDecl *Parent = 8848 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 8849 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 8850 NewFD->setPure(true); 8851 8852 // C++ [class.union]p2 8853 // A union can have member functions, but not virtual functions. 8854 if (isVirtual && Parent->isUnion()) 8855 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 8856 } 8857 8858 SetNestedNameSpecifier(*this, NewFD, D); 8859 isMemberSpecialization = false; 8860 isFunctionTemplateSpecialization = false; 8861 if (D.isInvalidType()) 8862 NewFD->setInvalidDecl(); 8863 8864 // Match up the template parameter lists with the scope specifier, then 8865 // determine whether we have a template or a template specialization. 8866 bool Invalid = false; 8867 TemplateParameterList *TemplateParams = 8868 MatchTemplateParametersToScopeSpecifier( 8869 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 8870 D.getCXXScopeSpec(), 8871 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 8872 ? D.getName().TemplateId 8873 : nullptr, 8874 TemplateParamLists, isFriend, isMemberSpecialization, 8875 Invalid); 8876 if (TemplateParams) { 8877 if (TemplateParams->size() > 0) { 8878 // This is a function template 8879 8880 // Check that we can declare a template here. 8881 if (CheckTemplateDeclScope(S, TemplateParams)) 8882 NewFD->setInvalidDecl(); 8883 8884 // A destructor cannot be a template. 8885 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8886 Diag(NewFD->getLocation(), diag::err_destructor_template); 8887 NewFD->setInvalidDecl(); 8888 } 8889 8890 // If we're adding a template to a dependent context, we may need to 8891 // rebuilding some of the types used within the template parameter list, 8892 // now that we know what the current instantiation is. 8893 if (DC->isDependentContext()) { 8894 ContextRAII SavedContext(*this, DC); 8895 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 8896 Invalid = true; 8897 } 8898 8899 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 8900 NewFD->getLocation(), 8901 Name, TemplateParams, 8902 NewFD); 8903 FunctionTemplate->setLexicalDeclContext(CurContext); 8904 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 8905 8906 // For source fidelity, store the other template param lists. 8907 if (TemplateParamLists.size() > 1) { 8908 NewFD->setTemplateParameterListsInfo(Context, 8909 ArrayRef<TemplateParameterList *>(TemplateParamLists) 8910 .drop_back(1)); 8911 } 8912 } else { 8913 // This is a function template specialization. 8914 isFunctionTemplateSpecialization = true; 8915 // For source fidelity, store all the template param lists. 8916 if (TemplateParamLists.size() > 0) 8917 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8918 8919 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 8920 if (isFriend) { 8921 // We want to remove the "template<>", found here. 8922 SourceRange RemoveRange = TemplateParams->getSourceRange(); 8923 8924 // If we remove the template<> and the name is not a 8925 // template-id, we're actually silently creating a problem: 8926 // the friend declaration will refer to an untemplated decl, 8927 // and clearly the user wants a template specialization. So 8928 // we need to insert '<>' after the name. 8929 SourceLocation InsertLoc; 8930 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 8931 InsertLoc = D.getName().getSourceRange().getEnd(); 8932 InsertLoc = getLocForEndOfToken(InsertLoc); 8933 } 8934 8935 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 8936 << Name << RemoveRange 8937 << FixItHint::CreateRemoval(RemoveRange) 8938 << FixItHint::CreateInsertion(InsertLoc, "<>"); 8939 } 8940 } 8941 } else { 8942 // All template param lists were matched against the scope specifier: 8943 // this is NOT (an explicit specialization of) a template. 8944 if (TemplateParamLists.size() > 0) 8945 // For source fidelity, store all the template param lists. 8946 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8947 } 8948 8949 if (Invalid) { 8950 NewFD->setInvalidDecl(); 8951 if (FunctionTemplate) 8952 FunctionTemplate->setInvalidDecl(); 8953 } 8954 8955 // C++ [dcl.fct.spec]p5: 8956 // The virtual specifier shall only be used in declarations of 8957 // nonstatic class member functions that appear within a 8958 // member-specification of a class declaration; see 10.3. 8959 // 8960 if (isVirtual && !NewFD->isInvalidDecl()) { 8961 if (!isVirtualOkay) { 8962 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8963 diag::err_virtual_non_function); 8964 } else if (!CurContext->isRecord()) { 8965 // 'virtual' was specified outside of the class. 8966 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8967 diag::err_virtual_out_of_class) 8968 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8969 } else if (NewFD->getDescribedFunctionTemplate()) { 8970 // C++ [temp.mem]p3: 8971 // A member function template shall not be virtual. 8972 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8973 diag::err_virtual_member_function_template) 8974 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8975 } else { 8976 // Okay: Add virtual to the method. 8977 NewFD->setVirtualAsWritten(true); 8978 } 8979 8980 if (getLangOpts().CPlusPlus14 && 8981 NewFD->getReturnType()->isUndeducedType()) 8982 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 8983 } 8984 8985 if (getLangOpts().CPlusPlus14 && 8986 (NewFD->isDependentContext() || 8987 (isFriend && CurContext->isDependentContext())) && 8988 NewFD->getReturnType()->isUndeducedType()) { 8989 // If the function template is referenced directly (for instance, as a 8990 // member of the current instantiation), pretend it has a dependent type. 8991 // This is not really justified by the standard, but is the only sane 8992 // thing to do. 8993 // FIXME: For a friend function, we have not marked the function as being 8994 // a friend yet, so 'isDependentContext' on the FD doesn't work. 8995 const FunctionProtoType *FPT = 8996 NewFD->getType()->castAs<FunctionProtoType>(); 8997 QualType Result = 8998 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 8999 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 9000 FPT->getExtProtoInfo())); 9001 } 9002 9003 // C++ [dcl.fct.spec]p3: 9004 // The inline specifier shall not appear on a block scope function 9005 // declaration. 9006 if (isInline && !NewFD->isInvalidDecl()) { 9007 if (CurContext->isFunctionOrMethod()) { 9008 // 'inline' is not allowed on block scope function declaration. 9009 Diag(D.getDeclSpec().getInlineSpecLoc(), 9010 diag::err_inline_declaration_block_scope) << Name 9011 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 9012 } 9013 } 9014 9015 // C++ [dcl.fct.spec]p6: 9016 // The explicit specifier shall be used only in the declaration of a 9017 // constructor or conversion function within its class definition; 9018 // see 12.3.1 and 12.3.2. 9019 if (hasExplicit && !NewFD->isInvalidDecl() && 9020 !isa<CXXDeductionGuideDecl>(NewFD)) { 9021 if (!CurContext->isRecord()) { 9022 // 'explicit' was specified outside of the class. 9023 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9024 diag::err_explicit_out_of_class) 9025 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9026 } else if (!isa<CXXConstructorDecl>(NewFD) && 9027 !isa<CXXConversionDecl>(NewFD)) { 9028 // 'explicit' was specified on a function that wasn't a constructor 9029 // or conversion function. 9030 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9031 diag::err_explicit_non_ctor_or_conv_function) 9032 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9033 } 9034 } 9035 9036 if (ConstexprSpecKind ConstexprKind = 9037 D.getDeclSpec().getConstexprSpecifier()) { 9038 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 9039 // are implicitly inline. 9040 NewFD->setImplicitlyInline(); 9041 9042 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 9043 // be either constructors or to return a literal type. Therefore, 9044 // destructors cannot be declared constexpr. 9045 if (isa<CXXDestructorDecl>(NewFD) && 9046 (!getLangOpts().CPlusPlus2a || ConstexprKind == CSK_consteval)) { 9047 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor) 9048 << ConstexprKind; 9049 NewFD->setConstexprKind(getLangOpts().CPlusPlus2a ? CSK_unspecified : CSK_constexpr); 9050 } 9051 // C++20 [dcl.constexpr]p2: An allocation function, or a 9052 // deallocation function shall not be declared with the consteval 9053 // specifier. 9054 if (ConstexprKind == CSK_consteval && 9055 (NewFD->getOverloadedOperator() == OO_New || 9056 NewFD->getOverloadedOperator() == OO_Array_New || 9057 NewFD->getOverloadedOperator() == OO_Delete || 9058 NewFD->getOverloadedOperator() == OO_Array_Delete)) { 9059 Diag(D.getDeclSpec().getConstexprSpecLoc(), 9060 diag::err_invalid_consteval_decl_kind) 9061 << NewFD; 9062 NewFD->setConstexprKind(CSK_constexpr); 9063 } 9064 } 9065 9066 // If __module_private__ was specified, mark the function accordingly. 9067 if (D.getDeclSpec().isModulePrivateSpecified()) { 9068 if (isFunctionTemplateSpecialization) { 9069 SourceLocation ModulePrivateLoc 9070 = D.getDeclSpec().getModulePrivateSpecLoc(); 9071 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 9072 << 0 9073 << FixItHint::CreateRemoval(ModulePrivateLoc); 9074 } else { 9075 NewFD->setModulePrivate(); 9076 if (FunctionTemplate) 9077 FunctionTemplate->setModulePrivate(); 9078 } 9079 } 9080 9081 if (isFriend) { 9082 if (FunctionTemplate) { 9083 FunctionTemplate->setObjectOfFriendDecl(); 9084 FunctionTemplate->setAccess(AS_public); 9085 } 9086 NewFD->setObjectOfFriendDecl(); 9087 NewFD->setAccess(AS_public); 9088 } 9089 9090 // If a function is defined as defaulted or deleted, mark it as such now. 9091 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function 9092 // definition kind to FDK_Definition. 9093 switch (D.getFunctionDefinitionKind()) { 9094 case FDK_Declaration: 9095 case FDK_Definition: 9096 break; 9097 9098 case FDK_Defaulted: 9099 NewFD->setDefaulted(); 9100 break; 9101 9102 case FDK_Deleted: 9103 NewFD->setDeletedAsWritten(); 9104 break; 9105 } 9106 9107 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 9108 D.isFunctionDefinition()) { 9109 // C++ [class.mfct]p2: 9110 // A member function may be defined (8.4) in its class definition, in 9111 // which case it is an inline member function (7.1.2) 9112 NewFD->setImplicitlyInline(); 9113 } 9114 9115 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 9116 !CurContext->isRecord()) { 9117 // C++ [class.static]p1: 9118 // A data or function member of a class may be declared static 9119 // in a class definition, in which case it is a static member of 9120 // the class. 9121 9122 // Complain about the 'static' specifier if it's on an out-of-line 9123 // member function definition. 9124 9125 // MSVC permits the use of a 'static' storage specifier on an out-of-line 9126 // member function template declaration and class member template 9127 // declaration (MSVC versions before 2015), warn about this. 9128 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 9129 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 9130 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) || 9131 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate())) 9132 ? diag::ext_static_out_of_line : diag::err_static_out_of_line) 9133 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 9134 } 9135 9136 // C++11 [except.spec]p15: 9137 // A deallocation function with no exception-specification is treated 9138 // as if it were specified with noexcept(true). 9139 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 9140 if ((Name.getCXXOverloadedOperator() == OO_Delete || 9141 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 9142 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 9143 NewFD->setType(Context.getFunctionType( 9144 FPT->getReturnType(), FPT->getParamTypes(), 9145 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 9146 } 9147 9148 // Filter out previous declarations that don't match the scope. 9149 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 9150 D.getCXXScopeSpec().isNotEmpty() || 9151 isMemberSpecialization || 9152 isFunctionTemplateSpecialization); 9153 9154 // Handle GNU asm-label extension (encoded as an attribute). 9155 if (Expr *E = (Expr*) D.getAsmLabel()) { 9156 // The parser guarantees this is a string. 9157 StringLiteral *SE = cast<StringLiteral>(E); 9158 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(), 9159 /*IsLiteralLabel=*/true, 9160 SE->getStrTokenLoc(0))); 9161 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 9162 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 9163 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 9164 if (I != ExtnameUndeclaredIdentifiers.end()) { 9165 if (isDeclExternC(NewFD)) { 9166 NewFD->addAttr(I->second); 9167 ExtnameUndeclaredIdentifiers.erase(I); 9168 } else 9169 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 9170 << /*Variable*/0 << NewFD; 9171 } 9172 } 9173 9174 // Copy the parameter declarations from the declarator D to the function 9175 // declaration NewFD, if they are available. First scavenge them into Params. 9176 SmallVector<ParmVarDecl*, 16> Params; 9177 unsigned FTIIdx; 9178 if (D.isFunctionDeclarator(FTIIdx)) { 9179 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 9180 9181 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 9182 // function that takes no arguments, not a function that takes a 9183 // single void argument. 9184 // We let through "const void" here because Sema::GetTypeForDeclarator 9185 // already checks for that case. 9186 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 9187 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 9188 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 9189 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 9190 Param->setDeclContext(NewFD); 9191 Params.push_back(Param); 9192 9193 if (Param->isInvalidDecl()) 9194 NewFD->setInvalidDecl(); 9195 } 9196 } 9197 9198 if (!getLangOpts().CPlusPlus) { 9199 // In C, find all the tag declarations from the prototype and move them 9200 // into the function DeclContext. Remove them from the surrounding tag 9201 // injection context of the function, which is typically but not always 9202 // the TU. 9203 DeclContext *PrototypeTagContext = 9204 getTagInjectionContext(NewFD->getLexicalDeclContext()); 9205 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 9206 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 9207 9208 // We don't want to reparent enumerators. Look at their parent enum 9209 // instead. 9210 if (!TD) { 9211 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 9212 TD = cast<EnumDecl>(ECD->getDeclContext()); 9213 } 9214 if (!TD) 9215 continue; 9216 DeclContext *TagDC = TD->getLexicalDeclContext(); 9217 if (!TagDC->containsDecl(TD)) 9218 continue; 9219 TagDC->removeDecl(TD); 9220 TD->setDeclContext(NewFD); 9221 NewFD->addDecl(TD); 9222 9223 // Preserve the lexical DeclContext if it is not the surrounding tag 9224 // injection context of the FD. In this example, the semantic context of 9225 // E will be f and the lexical context will be S, while both the 9226 // semantic and lexical contexts of S will be f: 9227 // void f(struct S { enum E { a } f; } s); 9228 if (TagDC != PrototypeTagContext) 9229 TD->setLexicalDeclContext(TagDC); 9230 } 9231 } 9232 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 9233 // When we're declaring a function with a typedef, typeof, etc as in the 9234 // following example, we'll need to synthesize (unnamed) 9235 // parameters for use in the declaration. 9236 // 9237 // @code 9238 // typedef void fn(int); 9239 // fn f; 9240 // @endcode 9241 9242 // Synthesize a parameter for each argument type. 9243 for (const auto &AI : FT->param_types()) { 9244 ParmVarDecl *Param = 9245 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 9246 Param->setScopeInfo(0, Params.size()); 9247 Params.push_back(Param); 9248 } 9249 } else { 9250 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 9251 "Should not need args for typedef of non-prototype fn"); 9252 } 9253 9254 // Finally, we know we have the right number of parameters, install them. 9255 NewFD->setParams(Params); 9256 9257 if (D.getDeclSpec().isNoreturnSpecified()) 9258 NewFD->addAttr(C11NoReturnAttr::Create(Context, 9259 D.getDeclSpec().getNoreturnSpecLoc(), 9260 AttributeCommonInfo::AS_Keyword)); 9261 9262 // Functions returning a variably modified type violate C99 6.7.5.2p2 9263 // because all functions have linkage. 9264 if (!NewFD->isInvalidDecl() && 9265 NewFD->getReturnType()->isVariablyModifiedType()) { 9266 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 9267 NewFD->setInvalidDecl(); 9268 } 9269 9270 // Apply an implicit SectionAttr if '#pragma clang section text' is active 9271 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && 9272 !NewFD->hasAttr<SectionAttr>()) 9273 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit( 9274 Context, PragmaClangTextSection.SectionName, 9275 PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma)); 9276 9277 // Apply an implicit SectionAttr if #pragma code_seg is active. 9278 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 9279 !NewFD->hasAttr<SectionAttr>()) { 9280 NewFD->addAttr(SectionAttr::CreateImplicit( 9281 Context, CodeSegStack.CurrentValue->getString(), 9282 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 9283 SectionAttr::Declspec_allocate)); 9284 if (UnifySection(CodeSegStack.CurrentValue->getString(), 9285 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 9286 ASTContext::PSF_Read, 9287 NewFD)) 9288 NewFD->dropAttr<SectionAttr>(); 9289 } 9290 9291 // Apply an implicit CodeSegAttr from class declspec or 9292 // apply an implicit SectionAttr from #pragma code_seg if active. 9293 if (!NewFD->hasAttr<CodeSegAttr>()) { 9294 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD, 9295 D.isFunctionDefinition())) { 9296 NewFD->addAttr(SAttr); 9297 } 9298 } 9299 9300 // Handle attributes. 9301 ProcessDeclAttributes(S, NewFD, D); 9302 9303 if (getLangOpts().OpenCL) { 9304 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 9305 // type declaration will generate a compilation error. 9306 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); 9307 if (AddressSpace != LangAS::Default) { 9308 Diag(NewFD->getLocation(), 9309 diag::err_opencl_return_value_with_address_space); 9310 NewFD->setInvalidDecl(); 9311 } 9312 } 9313 9314 if (!getLangOpts().CPlusPlus) { 9315 // Perform semantic checking on the function declaration. 9316 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9317 CheckMain(NewFD, D.getDeclSpec()); 9318 9319 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9320 CheckMSVCRTEntryPoint(NewFD); 9321 9322 if (!NewFD->isInvalidDecl()) 9323 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9324 isMemberSpecialization)); 9325 else if (!Previous.empty()) 9326 // Recover gracefully from an invalid redeclaration. 9327 D.setRedeclaration(true); 9328 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9329 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9330 "previous declaration set still overloaded"); 9331 9332 // Diagnose no-prototype function declarations with calling conventions that 9333 // don't support variadic calls. Only do this in C and do it after merging 9334 // possibly prototyped redeclarations. 9335 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 9336 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 9337 CallingConv CC = FT->getExtInfo().getCC(); 9338 if (!supportsVariadicCall(CC)) { 9339 // Windows system headers sometimes accidentally use stdcall without 9340 // (void) parameters, so we relax this to a warning. 9341 int DiagID = 9342 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 9343 Diag(NewFD->getLocation(), DiagID) 9344 << FunctionType::getNameForCallConv(CC); 9345 } 9346 } 9347 9348 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() || 9349 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion()) 9350 checkNonTrivialCUnion(NewFD->getReturnType(), 9351 NewFD->getReturnTypeSourceRange().getBegin(), 9352 NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy); 9353 } else { 9354 // C++11 [replacement.functions]p3: 9355 // The program's definitions shall not be specified as inline. 9356 // 9357 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 9358 // 9359 // Suppress the diagnostic if the function is __attribute__((used)), since 9360 // that forces an external definition to be emitted. 9361 if (D.getDeclSpec().isInlineSpecified() && 9362 NewFD->isReplaceableGlobalAllocationFunction() && 9363 !NewFD->hasAttr<UsedAttr>()) 9364 Diag(D.getDeclSpec().getInlineSpecLoc(), 9365 diag::ext_operator_new_delete_declared_inline) 9366 << NewFD->getDeclName(); 9367 9368 // If the declarator is a template-id, translate the parser's template 9369 // argument list into our AST format. 9370 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 9371 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 9372 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 9373 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 9374 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 9375 TemplateId->NumArgs); 9376 translateTemplateArguments(TemplateArgsPtr, 9377 TemplateArgs); 9378 9379 HasExplicitTemplateArgs = true; 9380 9381 if (NewFD->isInvalidDecl()) { 9382 HasExplicitTemplateArgs = false; 9383 } else if (FunctionTemplate) { 9384 // Function template with explicit template arguments. 9385 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 9386 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 9387 9388 HasExplicitTemplateArgs = false; 9389 } else { 9390 assert((isFunctionTemplateSpecialization || 9391 D.getDeclSpec().isFriendSpecified()) && 9392 "should have a 'template<>' for this decl"); 9393 // "friend void foo<>(int);" is an implicit specialization decl. 9394 isFunctionTemplateSpecialization = true; 9395 } 9396 } else if (isFriend && isFunctionTemplateSpecialization) { 9397 // This combination is only possible in a recovery case; the user 9398 // wrote something like: 9399 // template <> friend void foo(int); 9400 // which we're recovering from as if the user had written: 9401 // friend void foo<>(int); 9402 // Go ahead and fake up a template id. 9403 HasExplicitTemplateArgs = true; 9404 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 9405 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 9406 } 9407 9408 // We do not add HD attributes to specializations here because 9409 // they may have different constexpr-ness compared to their 9410 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 9411 // may end up with different effective targets. Instead, a 9412 // specialization inherits its target attributes from its template 9413 // in the CheckFunctionTemplateSpecialization() call below. 9414 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization) 9415 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 9416 9417 // If it's a friend (and only if it's a friend), it's possible 9418 // that either the specialized function type or the specialized 9419 // template is dependent, and therefore matching will fail. In 9420 // this case, don't check the specialization yet. 9421 bool InstantiationDependent = false; 9422 if (isFunctionTemplateSpecialization && isFriend && 9423 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 9424 TemplateSpecializationType::anyDependentTemplateArguments( 9425 TemplateArgs, 9426 InstantiationDependent))) { 9427 assert(HasExplicitTemplateArgs && 9428 "friend function specialization without template args"); 9429 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 9430 Previous)) 9431 NewFD->setInvalidDecl(); 9432 } else if (isFunctionTemplateSpecialization) { 9433 if (CurContext->isDependentContext() && CurContext->isRecord() 9434 && !isFriend) { 9435 isDependentClassScopeExplicitSpecialization = true; 9436 } else if (!NewFD->isInvalidDecl() && 9437 CheckFunctionTemplateSpecialization( 9438 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), 9439 Previous)) 9440 NewFD->setInvalidDecl(); 9441 9442 // C++ [dcl.stc]p1: 9443 // A storage-class-specifier shall not be specified in an explicit 9444 // specialization (14.7.3) 9445 FunctionTemplateSpecializationInfo *Info = 9446 NewFD->getTemplateSpecializationInfo(); 9447 if (Info && SC != SC_None) { 9448 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 9449 Diag(NewFD->getLocation(), 9450 diag::err_explicit_specialization_inconsistent_storage_class) 9451 << SC 9452 << FixItHint::CreateRemoval( 9453 D.getDeclSpec().getStorageClassSpecLoc()); 9454 9455 else 9456 Diag(NewFD->getLocation(), 9457 diag::ext_explicit_specialization_storage_class) 9458 << FixItHint::CreateRemoval( 9459 D.getDeclSpec().getStorageClassSpecLoc()); 9460 } 9461 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 9462 if (CheckMemberSpecialization(NewFD, Previous)) 9463 NewFD->setInvalidDecl(); 9464 } 9465 9466 // Perform semantic checking on the function declaration. 9467 if (!isDependentClassScopeExplicitSpecialization) { 9468 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9469 CheckMain(NewFD, D.getDeclSpec()); 9470 9471 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9472 CheckMSVCRTEntryPoint(NewFD); 9473 9474 if (!NewFD->isInvalidDecl()) 9475 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9476 isMemberSpecialization)); 9477 else if (!Previous.empty()) 9478 // Recover gracefully from an invalid redeclaration. 9479 D.setRedeclaration(true); 9480 } 9481 9482 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9483 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9484 "previous declaration set still overloaded"); 9485 9486 NamedDecl *PrincipalDecl = (FunctionTemplate 9487 ? cast<NamedDecl>(FunctionTemplate) 9488 : NewFD); 9489 9490 if (isFriend && NewFD->getPreviousDecl()) { 9491 AccessSpecifier Access = AS_public; 9492 if (!NewFD->isInvalidDecl()) 9493 Access = NewFD->getPreviousDecl()->getAccess(); 9494 9495 NewFD->setAccess(Access); 9496 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 9497 } 9498 9499 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 9500 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 9501 PrincipalDecl->setNonMemberOperator(); 9502 9503 // If we have a function template, check the template parameter 9504 // list. This will check and merge default template arguments. 9505 if (FunctionTemplate) { 9506 FunctionTemplateDecl *PrevTemplate = 9507 FunctionTemplate->getPreviousDecl(); 9508 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 9509 PrevTemplate ? PrevTemplate->getTemplateParameters() 9510 : nullptr, 9511 D.getDeclSpec().isFriendSpecified() 9512 ? (D.isFunctionDefinition() 9513 ? TPC_FriendFunctionTemplateDefinition 9514 : TPC_FriendFunctionTemplate) 9515 : (D.getCXXScopeSpec().isSet() && 9516 DC && DC->isRecord() && 9517 DC->isDependentContext()) 9518 ? TPC_ClassTemplateMember 9519 : TPC_FunctionTemplate); 9520 } 9521 9522 if (NewFD->isInvalidDecl()) { 9523 // Ignore all the rest of this. 9524 } else if (!D.isRedeclaration()) { 9525 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 9526 AddToScope }; 9527 // Fake up an access specifier if it's supposed to be a class member. 9528 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 9529 NewFD->setAccess(AS_public); 9530 9531 // Qualified decls generally require a previous declaration. 9532 if (D.getCXXScopeSpec().isSet()) { 9533 // ...with the major exception of templated-scope or 9534 // dependent-scope friend declarations. 9535 9536 // TODO: we currently also suppress this check in dependent 9537 // contexts because (1) the parameter depth will be off when 9538 // matching friend templates and (2) we might actually be 9539 // selecting a friend based on a dependent factor. But there 9540 // are situations where these conditions don't apply and we 9541 // can actually do this check immediately. 9542 // 9543 // Unless the scope is dependent, it's always an error if qualified 9544 // redeclaration lookup found nothing at all. Diagnose that now; 9545 // nothing will diagnose that error later. 9546 if (isFriend && 9547 (D.getCXXScopeSpec().getScopeRep()->isDependent() || 9548 (!Previous.empty() && CurContext->isDependentContext()))) { 9549 // ignore these 9550 } else { 9551 // The user tried to provide an out-of-line definition for a 9552 // function that is a member of a class or namespace, but there 9553 // was no such member function declared (C++ [class.mfct]p2, 9554 // C++ [namespace.memdef]p2). For example: 9555 // 9556 // class X { 9557 // void f() const; 9558 // }; 9559 // 9560 // void X::f() { } // ill-formed 9561 // 9562 // Complain about this problem, and attempt to suggest close 9563 // matches (e.g., those that differ only in cv-qualifiers and 9564 // whether the parameter types are references). 9565 9566 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9567 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 9568 AddToScope = ExtraArgs.AddToScope; 9569 return Result; 9570 } 9571 } 9572 9573 // Unqualified local friend declarations are required to resolve 9574 // to something. 9575 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 9576 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9577 *this, Previous, NewFD, ExtraArgs, true, S)) { 9578 AddToScope = ExtraArgs.AddToScope; 9579 return Result; 9580 } 9581 } 9582 } else if (!D.isFunctionDefinition() && 9583 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 9584 !isFriend && !isFunctionTemplateSpecialization && 9585 !isMemberSpecialization) { 9586 // An out-of-line member function declaration must also be a 9587 // definition (C++ [class.mfct]p2). 9588 // Note that this is not the case for explicit specializations of 9589 // function templates or member functions of class templates, per 9590 // C++ [temp.expl.spec]p2. We also allow these declarations as an 9591 // extension for compatibility with old SWIG code which likes to 9592 // generate them. 9593 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 9594 << D.getCXXScopeSpec().getRange(); 9595 } 9596 } 9597 9598 ProcessPragmaWeak(S, NewFD); 9599 checkAttributesAfterMerging(*this, *NewFD); 9600 9601 AddKnownFunctionAttributes(NewFD); 9602 9603 if (NewFD->hasAttr<OverloadableAttr>() && 9604 !NewFD->getType()->getAs<FunctionProtoType>()) { 9605 Diag(NewFD->getLocation(), 9606 diag::err_attribute_overloadable_no_prototype) 9607 << NewFD; 9608 9609 // Turn this into a variadic function with no parameters. 9610 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 9611 FunctionProtoType::ExtProtoInfo EPI( 9612 Context.getDefaultCallingConvention(true, false)); 9613 EPI.Variadic = true; 9614 EPI.ExtInfo = FT->getExtInfo(); 9615 9616 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 9617 NewFD->setType(R); 9618 } 9619 9620 // If there's a #pragma GCC visibility in scope, and this isn't a class 9621 // member, set the visibility of this function. 9622 if (!DC->isRecord() && NewFD->isExternallyVisible()) 9623 AddPushedVisibilityAttribute(NewFD); 9624 9625 // If there's a #pragma clang arc_cf_code_audited in scope, consider 9626 // marking the function. 9627 AddCFAuditedAttribute(NewFD); 9628 9629 // If this is a function definition, check if we have to apply optnone due to 9630 // a pragma. 9631 if(D.isFunctionDefinition()) 9632 AddRangeBasedOptnone(NewFD); 9633 9634 // If this is the first declaration of an extern C variable, update 9635 // the map of such variables. 9636 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 9637 isIncompleteDeclExternC(*this, NewFD)) 9638 RegisterLocallyScopedExternCDecl(NewFD, S); 9639 9640 // Set this FunctionDecl's range up to the right paren. 9641 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 9642 9643 if (D.isRedeclaration() && !Previous.empty()) { 9644 NamedDecl *Prev = Previous.getRepresentativeDecl(); 9645 checkDLLAttributeRedeclaration(*this, Prev, NewFD, 9646 isMemberSpecialization || 9647 isFunctionTemplateSpecialization, 9648 D.isFunctionDefinition()); 9649 } 9650 9651 if (getLangOpts().CUDA) { 9652 IdentifierInfo *II = NewFD->getIdentifier(); 9653 if (II && II->isStr(getCudaConfigureFuncName()) && 9654 !NewFD->isInvalidDecl() && 9655 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 9656 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 9657 Diag(NewFD->getLocation(), diag::err_config_scalar_return) 9658 << getCudaConfigureFuncName(); 9659 Context.setcudaConfigureCallDecl(NewFD); 9660 } 9661 9662 // Variadic functions, other than a *declaration* of printf, are not allowed 9663 // in device-side CUDA code, unless someone passed 9664 // -fcuda-allow-variadic-functions. 9665 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 9666 (NewFD->hasAttr<CUDADeviceAttr>() || 9667 NewFD->hasAttr<CUDAGlobalAttr>()) && 9668 !(II && II->isStr("printf") && NewFD->isExternC() && 9669 !D.isFunctionDefinition())) { 9670 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 9671 } 9672 } 9673 9674 MarkUnusedFileScopedDecl(NewFD); 9675 9676 9677 9678 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) { 9679 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 9680 if ((getLangOpts().OpenCLVersion >= 120) 9681 && (SC == SC_Static)) { 9682 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 9683 D.setInvalidType(); 9684 } 9685 9686 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 9687 if (!NewFD->getReturnType()->isVoidType()) { 9688 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 9689 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 9690 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 9691 : FixItHint()); 9692 D.setInvalidType(); 9693 } 9694 9695 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 9696 for (auto Param : NewFD->parameters()) 9697 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 9698 9699 if (getLangOpts().OpenCLCPlusPlus) { 9700 if (DC->isRecord()) { 9701 Diag(D.getIdentifierLoc(), diag::err_method_kernel); 9702 D.setInvalidType(); 9703 } 9704 if (FunctionTemplate) { 9705 Diag(D.getIdentifierLoc(), diag::err_template_kernel); 9706 D.setInvalidType(); 9707 } 9708 } 9709 } 9710 9711 if (getLangOpts().CPlusPlus) { 9712 if (FunctionTemplate) { 9713 if (NewFD->isInvalidDecl()) 9714 FunctionTemplate->setInvalidDecl(); 9715 return FunctionTemplate; 9716 } 9717 9718 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 9719 CompleteMemberSpecialization(NewFD, Previous); 9720 } 9721 9722 for (const ParmVarDecl *Param : NewFD->parameters()) { 9723 QualType PT = Param->getType(); 9724 9725 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 9726 // types. 9727 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 9728 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 9729 QualType ElemTy = PipeTy->getElementType(); 9730 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 9731 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 9732 D.setInvalidType(); 9733 } 9734 } 9735 } 9736 } 9737 9738 // Here we have an function template explicit specialization at class scope. 9739 // The actual specialization will be postponed to template instatiation 9740 // time via the ClassScopeFunctionSpecializationDecl node. 9741 if (isDependentClassScopeExplicitSpecialization) { 9742 ClassScopeFunctionSpecializationDecl *NewSpec = 9743 ClassScopeFunctionSpecializationDecl::Create( 9744 Context, CurContext, NewFD->getLocation(), 9745 cast<CXXMethodDecl>(NewFD), 9746 HasExplicitTemplateArgs, TemplateArgs); 9747 CurContext->addDecl(NewSpec); 9748 AddToScope = false; 9749 } 9750 9751 // Diagnose availability attributes. Availability cannot be used on functions 9752 // that are run during load/unload. 9753 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { 9754 if (NewFD->hasAttr<ConstructorAttr>()) { 9755 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9756 << 1; 9757 NewFD->dropAttr<AvailabilityAttr>(); 9758 } 9759 if (NewFD->hasAttr<DestructorAttr>()) { 9760 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9761 << 2; 9762 NewFD->dropAttr<AvailabilityAttr>(); 9763 } 9764 } 9765 9766 // Diagnose no_builtin attribute on function declaration that are not a 9767 // definition. 9768 // FIXME: We should really be doing this in 9769 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to 9770 // the FunctionDecl and at this point of the code 9771 // FunctionDecl::isThisDeclarationADefinition() which always returns `false` 9772 // because Sema::ActOnStartOfFunctionDef has not been called yet. 9773 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>()) 9774 switch (D.getFunctionDefinitionKind()) { 9775 case FDK_Defaulted: 9776 case FDK_Deleted: 9777 Diag(NBA->getLocation(), 9778 diag::err_attribute_no_builtin_on_defaulted_deleted_function) 9779 << NBA->getSpelling(); 9780 break; 9781 case FDK_Declaration: 9782 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition) 9783 << NBA->getSpelling(); 9784 break; 9785 case FDK_Definition: 9786 break; 9787 } 9788 9789 return NewFD; 9790 } 9791 9792 /// Return a CodeSegAttr from a containing class. The Microsoft docs say 9793 /// when __declspec(code_seg) "is applied to a class, all member functions of 9794 /// the class and nested classes -- this includes compiler-generated special 9795 /// member functions -- are put in the specified segment." 9796 /// The actual behavior is a little more complicated. The Microsoft compiler 9797 /// won't check outer classes if there is an active value from #pragma code_seg. 9798 /// The CodeSeg is always applied from the direct parent but only from outer 9799 /// classes when the #pragma code_seg stack is empty. See: 9800 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer 9801 /// available since MS has removed the page. 9802 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) { 9803 const auto *Method = dyn_cast<CXXMethodDecl>(FD); 9804 if (!Method) 9805 return nullptr; 9806 const CXXRecordDecl *Parent = Method->getParent(); 9807 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 9808 Attr *NewAttr = SAttr->clone(S.getASTContext()); 9809 NewAttr->setImplicit(true); 9810 return NewAttr; 9811 } 9812 9813 // The Microsoft compiler won't check outer classes for the CodeSeg 9814 // when the #pragma code_seg stack is active. 9815 if (S.CodeSegStack.CurrentValue) 9816 return nullptr; 9817 9818 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) { 9819 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 9820 Attr *NewAttr = SAttr->clone(S.getASTContext()); 9821 NewAttr->setImplicit(true); 9822 return NewAttr; 9823 } 9824 } 9825 return nullptr; 9826 } 9827 9828 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a 9829 /// containing class. Otherwise it will return implicit SectionAttr if the 9830 /// function is a definition and there is an active value on CodeSegStack 9831 /// (from the current #pragma code-seg value). 9832 /// 9833 /// \param FD Function being declared. 9834 /// \param IsDefinition Whether it is a definition or just a declarartion. 9835 /// \returns A CodeSegAttr or SectionAttr to apply to the function or 9836 /// nullptr if no attribute should be added. 9837 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, 9838 bool IsDefinition) { 9839 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD)) 9840 return A; 9841 if (!FD->hasAttr<SectionAttr>() && IsDefinition && 9842 CodeSegStack.CurrentValue) 9843 return SectionAttr::CreateImplicit( 9844 getASTContext(), CodeSegStack.CurrentValue->getString(), 9845 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 9846 SectionAttr::Declspec_allocate); 9847 return nullptr; 9848 } 9849 9850 /// Determines if we can perform a correct type check for \p D as a 9851 /// redeclaration of \p PrevDecl. If not, we can generally still perform a 9852 /// best-effort check. 9853 /// 9854 /// \param NewD The new declaration. 9855 /// \param OldD The old declaration. 9856 /// \param NewT The portion of the type of the new declaration to check. 9857 /// \param OldT The portion of the type of the old declaration to check. 9858 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, 9859 QualType NewT, QualType OldT) { 9860 if (!NewD->getLexicalDeclContext()->isDependentContext()) 9861 return true; 9862 9863 // For dependently-typed local extern declarations and friends, we can't 9864 // perform a correct type check in general until instantiation: 9865 // 9866 // int f(); 9867 // template<typename T> void g() { T f(); } 9868 // 9869 // (valid if g() is only instantiated with T = int). 9870 if (NewT->isDependentType() && 9871 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind())) 9872 return false; 9873 9874 // Similarly, if the previous declaration was a dependent local extern 9875 // declaration, we don't really know its type yet. 9876 if (OldT->isDependentType() && OldD->isLocalExternDecl()) 9877 return false; 9878 9879 return true; 9880 } 9881 9882 /// Checks if the new declaration declared in dependent context must be 9883 /// put in the same redeclaration chain as the specified declaration. 9884 /// 9885 /// \param D Declaration that is checked. 9886 /// \param PrevDecl Previous declaration found with proper lookup method for the 9887 /// same declaration name. 9888 /// \returns True if D must be added to the redeclaration chain which PrevDecl 9889 /// belongs to. 9890 /// 9891 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 9892 if (!D->getLexicalDeclContext()->isDependentContext()) 9893 return true; 9894 9895 // Don't chain dependent friend function definitions until instantiation, to 9896 // permit cases like 9897 // 9898 // void func(); 9899 // template<typename T> class C1 { friend void func() {} }; 9900 // template<typename T> class C2 { friend void func() {} }; 9901 // 9902 // ... which is valid if only one of C1 and C2 is ever instantiated. 9903 // 9904 // FIXME: This need only apply to function definitions. For now, we proxy 9905 // this by checking for a file-scope function. We do not want this to apply 9906 // to friend declarations nominating member functions, because that gets in 9907 // the way of access checks. 9908 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext()) 9909 return false; 9910 9911 auto *VD = dyn_cast<ValueDecl>(D); 9912 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl); 9913 return !VD || !PrevVD || 9914 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(), 9915 PrevVD->getType()); 9916 } 9917 9918 /// Check the target attribute of the function for MultiVersion 9919 /// validity. 9920 /// 9921 /// Returns true if there was an error, false otherwise. 9922 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { 9923 const auto *TA = FD->getAttr<TargetAttr>(); 9924 assert(TA && "MultiVersion Candidate requires a target attribute"); 9925 ParsedTargetAttr ParseInfo = TA->parse(); 9926 const TargetInfo &TargetInfo = S.Context.getTargetInfo(); 9927 enum ErrType { Feature = 0, Architecture = 1 }; 9928 9929 if (!ParseInfo.Architecture.empty() && 9930 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) { 9931 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9932 << Architecture << ParseInfo.Architecture; 9933 return true; 9934 } 9935 9936 for (const auto &Feat : ParseInfo.Features) { 9937 auto BareFeat = StringRef{Feat}.substr(1); 9938 if (Feat[0] == '-') { 9939 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9940 << Feature << ("no-" + BareFeat).str(); 9941 return true; 9942 } 9943 9944 if (!TargetInfo.validateCpuSupports(BareFeat) || 9945 !TargetInfo.isValidFeatureName(BareFeat)) { 9946 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9947 << Feature << BareFeat; 9948 return true; 9949 } 9950 } 9951 return false; 9952 } 9953 9954 static bool HasNonMultiVersionAttributes(const FunctionDecl *FD, 9955 MultiVersionKind MVType) { 9956 for (const Attr *A : FD->attrs()) { 9957 switch (A->getKind()) { 9958 case attr::CPUDispatch: 9959 case attr::CPUSpecific: 9960 if (MVType != MultiVersionKind::CPUDispatch && 9961 MVType != MultiVersionKind::CPUSpecific) 9962 return true; 9963 break; 9964 case attr::Target: 9965 if (MVType != MultiVersionKind::Target) 9966 return true; 9967 break; 9968 default: 9969 return true; 9970 } 9971 } 9972 return false; 9973 } 9974 9975 bool Sema::areMultiversionVariantFunctionsCompatible( 9976 const FunctionDecl *OldFD, const FunctionDecl *NewFD, 9977 const PartialDiagnostic &NoProtoDiagID, 9978 const PartialDiagnosticAt &NoteCausedDiagIDAt, 9979 const PartialDiagnosticAt &NoSupportDiagIDAt, 9980 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, 9981 bool ConstexprSupported, bool CLinkageMayDiffer) { 9982 enum DoesntSupport { 9983 FuncTemplates = 0, 9984 VirtFuncs = 1, 9985 DeducedReturn = 2, 9986 Constructors = 3, 9987 Destructors = 4, 9988 DeletedFuncs = 5, 9989 DefaultedFuncs = 6, 9990 ConstexprFuncs = 7, 9991 ConstevalFuncs = 8, 9992 }; 9993 enum Different { 9994 CallingConv = 0, 9995 ReturnType = 1, 9996 ConstexprSpec = 2, 9997 InlineSpec = 3, 9998 StorageClass = 4, 9999 Linkage = 5, 10000 }; 10001 10002 if (NoProtoDiagID.getDiagID() != 0 && OldFD && 10003 !OldFD->getType()->getAs<FunctionProtoType>()) { 10004 Diag(OldFD->getLocation(), NoProtoDiagID); 10005 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second); 10006 return true; 10007 } 10008 10009 if (NoProtoDiagID.getDiagID() != 0 && 10010 !NewFD->getType()->getAs<FunctionProtoType>()) 10011 return Diag(NewFD->getLocation(), NoProtoDiagID); 10012 10013 if (!TemplatesSupported && 10014 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 10015 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10016 << FuncTemplates; 10017 10018 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { 10019 if (NewCXXFD->isVirtual()) 10020 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10021 << VirtFuncs; 10022 10023 if (isa<CXXConstructorDecl>(NewCXXFD)) 10024 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10025 << Constructors; 10026 10027 if (isa<CXXDestructorDecl>(NewCXXFD)) 10028 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10029 << Destructors; 10030 } 10031 10032 if (NewFD->isDeleted()) 10033 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10034 << DeletedFuncs; 10035 10036 if (NewFD->isDefaulted()) 10037 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10038 << DefaultedFuncs; 10039 10040 if (!ConstexprSupported && NewFD->isConstexpr()) 10041 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10042 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs); 10043 10044 QualType NewQType = Context.getCanonicalType(NewFD->getType()); 10045 const auto *NewType = cast<FunctionType>(NewQType); 10046 QualType NewReturnType = NewType->getReturnType(); 10047 10048 if (NewReturnType->isUndeducedType()) 10049 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10050 << DeducedReturn; 10051 10052 // Ensure the return type is identical. 10053 if (OldFD) { 10054 QualType OldQType = Context.getCanonicalType(OldFD->getType()); 10055 const auto *OldType = cast<FunctionType>(OldQType); 10056 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 10057 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 10058 10059 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) 10060 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv; 10061 10062 QualType OldReturnType = OldType->getReturnType(); 10063 10064 if (OldReturnType != NewReturnType) 10065 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType; 10066 10067 if (OldFD->getConstexprKind() != NewFD->getConstexprKind()) 10068 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec; 10069 10070 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) 10071 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec; 10072 10073 if (OldFD->getStorageClass() != NewFD->getStorageClass()) 10074 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass; 10075 10076 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC()) 10077 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage; 10078 10079 if (CheckEquivalentExceptionSpec( 10080 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), 10081 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) 10082 return true; 10083 } 10084 return false; 10085 } 10086 10087 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, 10088 const FunctionDecl *NewFD, 10089 bool CausesMV, 10090 MultiVersionKind MVType) { 10091 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10092 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10093 if (OldFD) 10094 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10095 return true; 10096 } 10097 10098 bool IsCPUSpecificCPUDispatchMVType = 10099 MVType == MultiVersionKind::CPUDispatch || 10100 MVType == MultiVersionKind::CPUSpecific; 10101 10102 // For now, disallow all other attributes. These should be opt-in, but 10103 // an analysis of all of them is a future FIXME. 10104 if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) { 10105 S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs) 10106 << IsCPUSpecificCPUDispatchMVType; 10107 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10108 return true; 10109 } 10110 10111 if (HasNonMultiVersionAttributes(NewFD, MVType)) 10112 return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs) 10113 << IsCPUSpecificCPUDispatchMVType; 10114 10115 // Only allow transition to MultiVersion if it hasn't been used. 10116 if (OldFD && CausesMV && OldFD->isUsed(false)) 10117 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 10118 10119 return S.areMultiversionVariantFunctionsCompatible( 10120 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto), 10121 PartialDiagnosticAt(NewFD->getLocation(), 10122 S.PDiag(diag::note_multiversioning_caused_here)), 10123 PartialDiagnosticAt(NewFD->getLocation(), 10124 S.PDiag(diag::err_multiversion_doesnt_support) 10125 << IsCPUSpecificCPUDispatchMVType), 10126 PartialDiagnosticAt(NewFD->getLocation(), 10127 S.PDiag(diag::err_multiversion_diff)), 10128 /*TemplatesSupported=*/false, 10129 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType, 10130 /*CLinkageMayDiffer=*/false); 10131 } 10132 10133 /// Check the validity of a multiversion function declaration that is the 10134 /// first of its kind. Also sets the multiversion'ness' of the function itself. 10135 /// 10136 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10137 /// 10138 /// Returns true if there was an error, false otherwise. 10139 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD, 10140 MultiVersionKind MVType, 10141 const TargetAttr *TA) { 10142 assert(MVType != MultiVersionKind::None && 10143 "Function lacks multiversion attribute"); 10144 10145 // Target only causes MV if it is default, otherwise this is a normal 10146 // function. 10147 if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion()) 10148 return false; 10149 10150 if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) { 10151 FD->setInvalidDecl(); 10152 return true; 10153 } 10154 10155 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) { 10156 FD->setInvalidDecl(); 10157 return true; 10158 } 10159 10160 FD->setIsMultiVersion(); 10161 return false; 10162 } 10163 10164 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) { 10165 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) { 10166 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None) 10167 return true; 10168 } 10169 10170 return false; 10171 } 10172 10173 static bool CheckTargetCausesMultiVersioning( 10174 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA, 10175 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 10176 LookupResult &Previous) { 10177 const auto *OldTA = OldFD->getAttr<TargetAttr>(); 10178 ParsedTargetAttr NewParsed = NewTA->parse(); 10179 // Sort order doesn't matter, it just needs to be consistent. 10180 llvm::sort(NewParsed.Features); 10181 10182 // If the old decl is NOT MultiVersioned yet, and we don't cause that 10183 // to change, this is a simple redeclaration. 10184 if (!NewTA->isDefaultVersion() && 10185 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) 10186 return false; 10187 10188 // Otherwise, this decl causes MultiVersioning. 10189 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10190 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10191 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10192 NewFD->setInvalidDecl(); 10193 return true; 10194 } 10195 10196 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true, 10197 MultiVersionKind::Target)) { 10198 NewFD->setInvalidDecl(); 10199 return true; 10200 } 10201 10202 if (CheckMultiVersionValue(S, NewFD)) { 10203 NewFD->setInvalidDecl(); 10204 return true; 10205 } 10206 10207 // If this is 'default', permit the forward declaration. 10208 if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) { 10209 Redeclaration = true; 10210 OldDecl = OldFD; 10211 OldFD->setIsMultiVersion(); 10212 NewFD->setIsMultiVersion(); 10213 return false; 10214 } 10215 10216 if (CheckMultiVersionValue(S, OldFD)) { 10217 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10218 NewFD->setInvalidDecl(); 10219 return true; 10220 } 10221 10222 ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>()); 10223 10224 if (OldParsed == NewParsed) { 10225 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10226 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10227 NewFD->setInvalidDecl(); 10228 return true; 10229 } 10230 10231 for (const auto *FD : OldFD->redecls()) { 10232 const auto *CurTA = FD->getAttr<TargetAttr>(); 10233 // We allow forward declarations before ANY multiversioning attributes, but 10234 // nothing after the fact. 10235 if (PreviousDeclsHaveMultiVersionAttribute(FD) && 10236 (!CurTA || CurTA->isInherited())) { 10237 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl) 10238 << 0; 10239 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10240 NewFD->setInvalidDecl(); 10241 return true; 10242 } 10243 } 10244 10245 OldFD->setIsMultiVersion(); 10246 NewFD->setIsMultiVersion(); 10247 Redeclaration = false; 10248 MergeTypeWithPrevious = false; 10249 OldDecl = nullptr; 10250 Previous.clear(); 10251 return false; 10252 } 10253 10254 /// Check the validity of a new function declaration being added to an existing 10255 /// multiversioned declaration collection. 10256 static bool CheckMultiVersionAdditionalDecl( 10257 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, 10258 MultiVersionKind NewMVType, const TargetAttr *NewTA, 10259 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, 10260 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 10261 LookupResult &Previous) { 10262 10263 MultiVersionKind OldMVType = OldFD->getMultiVersionKind(); 10264 // Disallow mixing of multiversioning types. 10265 if ((OldMVType == MultiVersionKind::Target && 10266 NewMVType != MultiVersionKind::Target) || 10267 (NewMVType == MultiVersionKind::Target && 10268 OldMVType != MultiVersionKind::Target)) { 10269 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10270 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10271 NewFD->setInvalidDecl(); 10272 return true; 10273 } 10274 10275 ParsedTargetAttr NewParsed; 10276 if (NewTA) { 10277 NewParsed = NewTA->parse(); 10278 llvm::sort(NewParsed.Features); 10279 } 10280 10281 bool UseMemberUsingDeclRules = 10282 S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); 10283 10284 // Next, check ALL non-overloads to see if this is a redeclaration of a 10285 // previous member of the MultiVersion set. 10286 for (NamedDecl *ND : Previous) { 10287 FunctionDecl *CurFD = ND->getAsFunction(); 10288 if (!CurFD) 10289 continue; 10290 if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) 10291 continue; 10292 10293 if (NewMVType == MultiVersionKind::Target) { 10294 const auto *CurTA = CurFD->getAttr<TargetAttr>(); 10295 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { 10296 NewFD->setIsMultiVersion(); 10297 Redeclaration = true; 10298 OldDecl = ND; 10299 return false; 10300 } 10301 10302 ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>()); 10303 if (CurParsed == NewParsed) { 10304 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10305 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10306 NewFD->setInvalidDecl(); 10307 return true; 10308 } 10309 } else { 10310 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>(); 10311 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>(); 10312 // Handle CPUDispatch/CPUSpecific versions. 10313 // Only 1 CPUDispatch function is allowed, this will make it go through 10314 // the redeclaration errors. 10315 if (NewMVType == MultiVersionKind::CPUDispatch && 10316 CurFD->hasAttr<CPUDispatchAttr>()) { 10317 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() && 10318 std::equal( 10319 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(), 10320 NewCPUDisp->cpus_begin(), 10321 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10322 return Cur->getName() == New->getName(); 10323 })) { 10324 NewFD->setIsMultiVersion(); 10325 Redeclaration = true; 10326 OldDecl = ND; 10327 return false; 10328 } 10329 10330 // If the declarations don't match, this is an error condition. 10331 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch); 10332 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10333 NewFD->setInvalidDecl(); 10334 return true; 10335 } 10336 if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) { 10337 10338 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() && 10339 std::equal( 10340 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(), 10341 NewCPUSpec->cpus_begin(), 10342 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10343 return Cur->getName() == New->getName(); 10344 })) { 10345 NewFD->setIsMultiVersion(); 10346 Redeclaration = true; 10347 OldDecl = ND; 10348 return false; 10349 } 10350 10351 // Only 1 version of CPUSpecific is allowed for each CPU. 10352 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) { 10353 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) { 10354 if (CurII == NewII) { 10355 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs) 10356 << NewII; 10357 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10358 NewFD->setInvalidDecl(); 10359 return true; 10360 } 10361 } 10362 } 10363 } 10364 // If the two decls aren't the same MVType, there is no possible error 10365 // condition. 10366 } 10367 } 10368 10369 // Else, this is simply a non-redecl case. Checking the 'value' is only 10370 // necessary in the Target case, since The CPUSpecific/Dispatch cases are 10371 // handled in the attribute adding step. 10372 if (NewMVType == MultiVersionKind::Target && 10373 CheckMultiVersionValue(S, NewFD)) { 10374 NewFD->setInvalidDecl(); 10375 return true; 10376 } 10377 10378 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, 10379 !OldFD->isMultiVersion(), NewMVType)) { 10380 NewFD->setInvalidDecl(); 10381 return true; 10382 } 10383 10384 // Permit forward declarations in the case where these two are compatible. 10385 if (!OldFD->isMultiVersion()) { 10386 OldFD->setIsMultiVersion(); 10387 NewFD->setIsMultiVersion(); 10388 Redeclaration = true; 10389 OldDecl = OldFD; 10390 return false; 10391 } 10392 10393 NewFD->setIsMultiVersion(); 10394 Redeclaration = false; 10395 MergeTypeWithPrevious = false; 10396 OldDecl = nullptr; 10397 Previous.clear(); 10398 return false; 10399 } 10400 10401 10402 /// Check the validity of a mulitversion function declaration. 10403 /// Also sets the multiversion'ness' of the function itself. 10404 /// 10405 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10406 /// 10407 /// Returns true if there was an error, false otherwise. 10408 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, 10409 bool &Redeclaration, NamedDecl *&OldDecl, 10410 bool &MergeTypeWithPrevious, 10411 LookupResult &Previous) { 10412 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 10413 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>(); 10414 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>(); 10415 10416 // Mixing Multiversioning types is prohibited. 10417 if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) || 10418 (NewCPUDisp && NewCPUSpec)) { 10419 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10420 NewFD->setInvalidDecl(); 10421 return true; 10422 } 10423 10424 MultiVersionKind MVType = NewFD->getMultiVersionKind(); 10425 10426 // Main isn't allowed to become a multiversion function, however it IS 10427 // permitted to have 'main' be marked with the 'target' optimization hint. 10428 if (NewFD->isMain()) { 10429 if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) || 10430 MVType == MultiVersionKind::CPUDispatch || 10431 MVType == MultiVersionKind::CPUSpecific) { 10432 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); 10433 NewFD->setInvalidDecl(); 10434 return true; 10435 } 10436 return false; 10437 } 10438 10439 if (!OldDecl || !OldDecl->getAsFunction() || 10440 OldDecl->getDeclContext()->getRedeclContext() != 10441 NewFD->getDeclContext()->getRedeclContext()) { 10442 // If there's no previous declaration, AND this isn't attempting to cause 10443 // multiversioning, this isn't an error condition. 10444 if (MVType == MultiVersionKind::None) 10445 return false; 10446 return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA); 10447 } 10448 10449 FunctionDecl *OldFD = OldDecl->getAsFunction(); 10450 10451 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None) 10452 return false; 10453 10454 if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) { 10455 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl) 10456 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target); 10457 NewFD->setInvalidDecl(); 10458 return true; 10459 } 10460 10461 // Handle the target potentially causes multiversioning case. 10462 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target) 10463 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA, 10464 Redeclaration, OldDecl, 10465 MergeTypeWithPrevious, Previous); 10466 10467 // At this point, we have a multiversion function decl (in OldFD) AND an 10468 // appropriate attribute in the current function decl. Resolve that these are 10469 // still compatible with previous declarations. 10470 return CheckMultiVersionAdditionalDecl( 10471 S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration, 10472 OldDecl, MergeTypeWithPrevious, Previous); 10473 } 10474 10475 /// Perform semantic checking of a new function declaration. 10476 /// 10477 /// Performs semantic analysis of the new function declaration 10478 /// NewFD. This routine performs all semantic checking that does not 10479 /// require the actual declarator involved in the declaration, and is 10480 /// used both for the declaration of functions as they are parsed 10481 /// (called via ActOnDeclarator) and for the declaration of functions 10482 /// that have been instantiated via C++ template instantiation (called 10483 /// via InstantiateDecl). 10484 /// 10485 /// \param IsMemberSpecialization whether this new function declaration is 10486 /// a member specialization (that replaces any definition provided by the 10487 /// previous declaration). 10488 /// 10489 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10490 /// 10491 /// \returns true if the function declaration is a redeclaration. 10492 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 10493 LookupResult &Previous, 10494 bool IsMemberSpecialization) { 10495 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 10496 "Variably modified return types are not handled here"); 10497 10498 // Determine whether the type of this function should be merged with 10499 // a previous visible declaration. This never happens for functions in C++, 10500 // and always happens in C if the previous declaration was visible. 10501 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 10502 !Previous.isShadowed(); 10503 10504 bool Redeclaration = false; 10505 NamedDecl *OldDecl = nullptr; 10506 bool MayNeedOverloadableChecks = false; 10507 10508 // Merge or overload the declaration with an existing declaration of 10509 // the same name, if appropriate. 10510 if (!Previous.empty()) { 10511 // Determine whether NewFD is an overload of PrevDecl or 10512 // a declaration that requires merging. If it's an overload, 10513 // there's no more work to do here; we'll just add the new 10514 // function to the scope. 10515 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { 10516 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 10517 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 10518 Redeclaration = true; 10519 OldDecl = Candidate; 10520 } 10521 } else { 10522 MayNeedOverloadableChecks = true; 10523 switch (CheckOverload(S, NewFD, Previous, OldDecl, 10524 /*NewIsUsingDecl*/ false)) { 10525 case Ovl_Match: 10526 Redeclaration = true; 10527 break; 10528 10529 case Ovl_NonFunction: 10530 Redeclaration = true; 10531 break; 10532 10533 case Ovl_Overload: 10534 Redeclaration = false; 10535 break; 10536 } 10537 } 10538 } 10539 10540 // Check for a previous extern "C" declaration with this name. 10541 if (!Redeclaration && 10542 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 10543 if (!Previous.empty()) { 10544 // This is an extern "C" declaration with the same name as a previous 10545 // declaration, and thus redeclares that entity... 10546 Redeclaration = true; 10547 OldDecl = Previous.getFoundDecl(); 10548 MergeTypeWithPrevious = false; 10549 10550 // ... except in the presence of __attribute__((overloadable)). 10551 if (OldDecl->hasAttr<OverloadableAttr>() || 10552 NewFD->hasAttr<OverloadableAttr>()) { 10553 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 10554 MayNeedOverloadableChecks = true; 10555 Redeclaration = false; 10556 OldDecl = nullptr; 10557 } 10558 } 10559 } 10560 } 10561 10562 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, 10563 MergeTypeWithPrevious, Previous)) 10564 return Redeclaration; 10565 10566 // C++11 [dcl.constexpr]p8: 10567 // A constexpr specifier for a non-static member function that is not 10568 // a constructor declares that member function to be const. 10569 // 10570 // This needs to be delayed until we know whether this is an out-of-line 10571 // definition of a static member function. 10572 // 10573 // This rule is not present in C++1y, so we produce a backwards 10574 // compatibility warning whenever it happens in C++11. 10575 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 10576 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 10577 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 10578 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) { 10579 CXXMethodDecl *OldMD = nullptr; 10580 if (OldDecl) 10581 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 10582 if (!OldMD || !OldMD->isStatic()) { 10583 const FunctionProtoType *FPT = 10584 MD->getType()->castAs<FunctionProtoType>(); 10585 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10586 EPI.TypeQuals.addConst(); 10587 MD->setType(Context.getFunctionType(FPT->getReturnType(), 10588 FPT->getParamTypes(), EPI)); 10589 10590 // Warn that we did this, if we're not performing template instantiation. 10591 // In that case, we'll have warned already when the template was defined. 10592 if (!inTemplateInstantiation()) { 10593 SourceLocation AddConstLoc; 10594 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 10595 .IgnoreParens().getAs<FunctionTypeLoc>()) 10596 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 10597 10598 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 10599 << FixItHint::CreateInsertion(AddConstLoc, " const"); 10600 } 10601 } 10602 } 10603 10604 if (Redeclaration) { 10605 // NewFD and OldDecl represent declarations that need to be 10606 // merged. 10607 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 10608 NewFD->setInvalidDecl(); 10609 return Redeclaration; 10610 } 10611 10612 Previous.clear(); 10613 Previous.addDecl(OldDecl); 10614 10615 if (FunctionTemplateDecl *OldTemplateDecl = 10616 dyn_cast<FunctionTemplateDecl>(OldDecl)) { 10617 auto *OldFD = OldTemplateDecl->getTemplatedDecl(); 10618 FunctionTemplateDecl *NewTemplateDecl 10619 = NewFD->getDescribedFunctionTemplate(); 10620 assert(NewTemplateDecl && "Template/non-template mismatch"); 10621 10622 // The call to MergeFunctionDecl above may have created some state in 10623 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we 10624 // can add it as a redeclaration. 10625 NewTemplateDecl->mergePrevDecl(OldTemplateDecl); 10626 10627 NewFD->setPreviousDeclaration(OldFD); 10628 adjustDeclContextForDeclaratorDecl(NewFD, OldFD); 10629 if (NewFD->isCXXClassMember()) { 10630 NewFD->setAccess(OldTemplateDecl->getAccess()); 10631 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 10632 } 10633 10634 // If this is an explicit specialization of a member that is a function 10635 // template, mark it as a member specialization. 10636 if (IsMemberSpecialization && 10637 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 10638 NewTemplateDecl->setMemberSpecialization(); 10639 assert(OldTemplateDecl->isMemberSpecialization()); 10640 // Explicit specializations of a member template do not inherit deleted 10641 // status from the parent member template that they are specializing. 10642 if (OldFD->isDeleted()) { 10643 // FIXME: This assert will not hold in the presence of modules. 10644 assert(OldFD->getCanonicalDecl() == OldFD); 10645 // FIXME: We need an update record for this AST mutation. 10646 OldFD->setDeletedAsWritten(false); 10647 } 10648 } 10649 10650 } else { 10651 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 10652 auto *OldFD = cast<FunctionDecl>(OldDecl); 10653 // This needs to happen first so that 'inline' propagates. 10654 NewFD->setPreviousDeclaration(OldFD); 10655 adjustDeclContextForDeclaratorDecl(NewFD, OldFD); 10656 if (NewFD->isCXXClassMember()) 10657 NewFD->setAccess(OldFD->getAccess()); 10658 } 10659 } 10660 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && 10661 !NewFD->getAttr<OverloadableAttr>()) { 10662 assert((Previous.empty() || 10663 llvm::any_of(Previous, 10664 [](const NamedDecl *ND) { 10665 return ND->hasAttr<OverloadableAttr>(); 10666 })) && 10667 "Non-redecls shouldn't happen without overloadable present"); 10668 10669 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { 10670 const auto *FD = dyn_cast<FunctionDecl>(ND); 10671 return FD && !FD->hasAttr<OverloadableAttr>(); 10672 }); 10673 10674 if (OtherUnmarkedIter != Previous.end()) { 10675 Diag(NewFD->getLocation(), 10676 diag::err_attribute_overloadable_multiple_unmarked_overloads); 10677 Diag((*OtherUnmarkedIter)->getLocation(), 10678 diag::note_attribute_overloadable_prev_overload) 10679 << false; 10680 10681 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 10682 } 10683 } 10684 10685 // Semantic checking for this function declaration (in isolation). 10686 10687 if (getLangOpts().CPlusPlus) { 10688 // C++-specific checks. 10689 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 10690 CheckConstructor(Constructor); 10691 } else if (CXXDestructorDecl *Destructor = 10692 dyn_cast<CXXDestructorDecl>(NewFD)) { 10693 CXXRecordDecl *Record = Destructor->getParent(); 10694 QualType ClassType = Context.getTypeDeclType(Record); 10695 10696 // FIXME: Shouldn't we be able to perform this check even when the class 10697 // type is dependent? Both gcc and edg can handle that. 10698 if (!ClassType->isDependentType()) { 10699 DeclarationName Name 10700 = Context.DeclarationNames.getCXXDestructorName( 10701 Context.getCanonicalType(ClassType)); 10702 if (NewFD->getDeclName() != Name) { 10703 Diag(NewFD->getLocation(), diag::err_destructor_name); 10704 NewFD->setInvalidDecl(); 10705 return Redeclaration; 10706 } 10707 } 10708 } else if (CXXConversionDecl *Conversion 10709 = dyn_cast<CXXConversionDecl>(NewFD)) { 10710 ActOnConversionDeclarator(Conversion); 10711 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 10712 if (auto *TD = Guide->getDescribedFunctionTemplate()) 10713 CheckDeductionGuideTemplate(TD); 10714 10715 // A deduction guide is not on the list of entities that can be 10716 // explicitly specialized. 10717 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 10718 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized) 10719 << /*explicit specialization*/ 1; 10720 } 10721 10722 // Find any virtual functions that this function overrides. 10723 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 10724 if (!Method->isFunctionTemplateSpecialization() && 10725 !Method->getDescribedFunctionTemplate() && 10726 Method->isCanonicalDecl()) { 10727 if (AddOverriddenMethods(Method->getParent(), Method)) { 10728 // If the function was marked as "static", we have a problem. 10729 if (NewFD->getStorageClass() == SC_Static) { 10730 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 10731 } 10732 } 10733 } 10734 if (Method->isVirtual() && NewFD->getTrailingRequiresClause()) 10735 // C++2a [class.virtual]p6 10736 // A virtual method shall not have a requires-clause. 10737 Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(), 10738 diag::err_constrained_virtual_method); 10739 10740 if (Method->isStatic()) 10741 checkThisInStaticMemberFunctionType(Method); 10742 } 10743 10744 // Extra checking for C++ overloaded operators (C++ [over.oper]). 10745 if (NewFD->isOverloadedOperator() && 10746 CheckOverloadedOperatorDeclaration(NewFD)) { 10747 NewFD->setInvalidDecl(); 10748 return Redeclaration; 10749 } 10750 10751 // Extra checking for C++0x literal operators (C++0x [over.literal]). 10752 if (NewFD->getLiteralIdentifier() && 10753 CheckLiteralOperatorDeclaration(NewFD)) { 10754 NewFD->setInvalidDecl(); 10755 return Redeclaration; 10756 } 10757 10758 // In C++, check default arguments now that we have merged decls. Unless 10759 // the lexical context is the class, because in this case this is done 10760 // during delayed parsing anyway. 10761 if (!CurContext->isRecord()) 10762 CheckCXXDefaultArguments(NewFD); 10763 10764 // If this function declares a builtin function, check the type of this 10765 // declaration against the expected type for the builtin. 10766 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 10767 ASTContext::GetBuiltinTypeError Error; 10768 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 10769 QualType T = Context.GetBuiltinType(BuiltinID, Error); 10770 // If the type of the builtin differs only in its exception 10771 // specification, that's OK. 10772 // FIXME: If the types do differ in this way, it would be better to 10773 // retain the 'noexcept' form of the type. 10774 if (!T.isNull() && 10775 !Context.hasSameFunctionTypeIgnoringExceptionSpec(T, 10776 NewFD->getType())) 10777 // The type of this function differs from the type of the builtin, 10778 // so forget about the builtin entirely. 10779 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); 10780 } 10781 10782 // If this function is declared as being extern "C", then check to see if 10783 // the function returns a UDT (class, struct, or union type) that is not C 10784 // compatible, and if it does, warn the user. 10785 // But, issue any diagnostic on the first declaration only. 10786 if (Previous.empty() && NewFD->isExternC()) { 10787 QualType R = NewFD->getReturnType(); 10788 if (R->isIncompleteType() && !R->isVoidType()) 10789 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 10790 << NewFD << R; 10791 else if (!R.isPODType(Context) && !R->isVoidType() && 10792 !R->isObjCObjectPointerType()) 10793 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 10794 } 10795 10796 // C++1z [dcl.fct]p6: 10797 // [...] whether the function has a non-throwing exception-specification 10798 // [is] part of the function type 10799 // 10800 // This results in an ABI break between C++14 and C++17 for functions whose 10801 // declared type includes an exception-specification in a parameter or 10802 // return type. (Exception specifications on the function itself are OK in 10803 // most cases, and exception specifications are not permitted in most other 10804 // contexts where they could make it into a mangling.) 10805 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { 10806 auto HasNoexcept = [&](QualType T) -> bool { 10807 // Strip off declarator chunks that could be between us and a function 10808 // type. We don't need to look far, exception specifications are very 10809 // restricted prior to C++17. 10810 if (auto *RT = T->getAs<ReferenceType>()) 10811 T = RT->getPointeeType(); 10812 else if (T->isAnyPointerType()) 10813 T = T->getPointeeType(); 10814 else if (auto *MPT = T->getAs<MemberPointerType>()) 10815 T = MPT->getPointeeType(); 10816 if (auto *FPT = T->getAs<FunctionProtoType>()) 10817 if (FPT->isNothrow()) 10818 return true; 10819 return false; 10820 }; 10821 10822 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 10823 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 10824 for (QualType T : FPT->param_types()) 10825 AnyNoexcept |= HasNoexcept(T); 10826 if (AnyNoexcept) 10827 Diag(NewFD->getLocation(), 10828 diag::warn_cxx17_compat_exception_spec_in_signature) 10829 << NewFD; 10830 } 10831 10832 if (!Redeclaration && LangOpts.CUDA) 10833 checkCUDATargetOverload(NewFD, Previous); 10834 } 10835 return Redeclaration; 10836 } 10837 10838 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 10839 // C++11 [basic.start.main]p3: 10840 // A program that [...] declares main to be inline, static or 10841 // constexpr is ill-formed. 10842 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 10843 // appear in a declaration of main. 10844 // static main is not an error under C99, but we should warn about it. 10845 // We accept _Noreturn main as an extension. 10846 if (FD->getStorageClass() == SC_Static) 10847 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 10848 ? diag::err_static_main : diag::warn_static_main) 10849 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 10850 if (FD->isInlineSpecified()) 10851 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 10852 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 10853 if (DS.isNoreturnSpecified()) { 10854 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 10855 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 10856 Diag(NoreturnLoc, diag::ext_noreturn_main); 10857 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 10858 << FixItHint::CreateRemoval(NoreturnRange); 10859 } 10860 if (FD->isConstexpr()) { 10861 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 10862 << FD->isConsteval() 10863 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 10864 FD->setConstexprKind(CSK_unspecified); 10865 } 10866 10867 if (getLangOpts().OpenCL) { 10868 Diag(FD->getLocation(), diag::err_opencl_no_main) 10869 << FD->hasAttr<OpenCLKernelAttr>(); 10870 FD->setInvalidDecl(); 10871 return; 10872 } 10873 10874 QualType T = FD->getType(); 10875 assert(T->isFunctionType() && "function decl is not of function type"); 10876 const FunctionType* FT = T->castAs<FunctionType>(); 10877 10878 // Set default calling convention for main() 10879 if (FT->getCallConv() != CC_C) { 10880 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); 10881 FD->setType(QualType(FT, 0)); 10882 T = Context.getCanonicalType(FD->getType()); 10883 } 10884 10885 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 10886 // In C with GNU extensions we allow main() to have non-integer return 10887 // type, but we should warn about the extension, and we disable the 10888 // implicit-return-zero rule. 10889 10890 // GCC in C mode accepts qualified 'int'. 10891 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 10892 FD->setHasImplicitReturnZero(true); 10893 else { 10894 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 10895 SourceRange RTRange = FD->getReturnTypeSourceRange(); 10896 if (RTRange.isValid()) 10897 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 10898 << FixItHint::CreateReplacement(RTRange, "int"); 10899 } 10900 } else { 10901 // In C and C++, main magically returns 0 if you fall off the end; 10902 // set the flag which tells us that. 10903 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 10904 10905 // All the standards say that main() should return 'int'. 10906 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 10907 FD->setHasImplicitReturnZero(true); 10908 else { 10909 // Otherwise, this is just a flat-out error. 10910 SourceRange RTRange = FD->getReturnTypeSourceRange(); 10911 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 10912 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 10913 : FixItHint()); 10914 FD->setInvalidDecl(true); 10915 } 10916 } 10917 10918 // Treat protoless main() as nullary. 10919 if (isa<FunctionNoProtoType>(FT)) return; 10920 10921 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 10922 unsigned nparams = FTP->getNumParams(); 10923 assert(FD->getNumParams() == nparams); 10924 10925 bool HasExtraParameters = (nparams > 3); 10926 10927 if (FTP->isVariadic()) { 10928 Diag(FD->getLocation(), diag::ext_variadic_main); 10929 // FIXME: if we had information about the location of the ellipsis, we 10930 // could add a FixIt hint to remove it as a parameter. 10931 } 10932 10933 // Darwin passes an undocumented fourth argument of type char**. If 10934 // other platforms start sprouting these, the logic below will start 10935 // getting shifty. 10936 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 10937 HasExtraParameters = false; 10938 10939 if (HasExtraParameters) { 10940 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 10941 FD->setInvalidDecl(true); 10942 nparams = 3; 10943 } 10944 10945 // FIXME: a lot of the following diagnostics would be improved 10946 // if we had some location information about types. 10947 10948 QualType CharPP = 10949 Context.getPointerType(Context.getPointerType(Context.CharTy)); 10950 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 10951 10952 for (unsigned i = 0; i < nparams; ++i) { 10953 QualType AT = FTP->getParamType(i); 10954 10955 bool mismatch = true; 10956 10957 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 10958 mismatch = false; 10959 else if (Expected[i] == CharPP) { 10960 // As an extension, the following forms are okay: 10961 // char const ** 10962 // char const * const * 10963 // char * const * 10964 10965 QualifierCollector qs; 10966 const PointerType* PT; 10967 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 10968 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 10969 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 10970 Context.CharTy)) { 10971 qs.removeConst(); 10972 mismatch = !qs.empty(); 10973 } 10974 } 10975 10976 if (mismatch) { 10977 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 10978 // TODO: suggest replacing given type with expected type 10979 FD->setInvalidDecl(true); 10980 } 10981 } 10982 10983 if (nparams == 1 && !FD->isInvalidDecl()) { 10984 Diag(FD->getLocation(), diag::warn_main_one_arg); 10985 } 10986 10987 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 10988 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 10989 FD->setInvalidDecl(); 10990 } 10991 } 10992 10993 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 10994 QualType T = FD->getType(); 10995 assert(T->isFunctionType() && "function decl is not of function type"); 10996 const FunctionType *FT = T->castAs<FunctionType>(); 10997 10998 // Set an implicit return of 'zero' if the function can return some integral, 10999 // enumeration, pointer or nullptr type. 11000 if (FT->getReturnType()->isIntegralOrEnumerationType() || 11001 FT->getReturnType()->isAnyPointerType() || 11002 FT->getReturnType()->isNullPtrType()) 11003 // DllMain is exempt because a return value of zero means it failed. 11004 if (FD->getName() != "DllMain") 11005 FD->setHasImplicitReturnZero(true); 11006 11007 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11008 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11009 FD->setInvalidDecl(); 11010 } 11011 } 11012 11013 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 11014 // FIXME: Need strict checking. In C89, we need to check for 11015 // any assignment, increment, decrement, function-calls, or 11016 // commas outside of a sizeof. In C99, it's the same list, 11017 // except that the aforementioned are allowed in unevaluated 11018 // expressions. Everything else falls under the 11019 // "may accept other forms of constant expressions" exception. 11020 // (We never end up here for C++, so the constant expression 11021 // rules there don't matter.) 11022 const Expr *Culprit; 11023 if (Init->isConstantInitializer(Context, false, &Culprit)) 11024 return false; 11025 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 11026 << Culprit->getSourceRange(); 11027 return true; 11028 } 11029 11030 namespace { 11031 // Visits an initialization expression to see if OrigDecl is evaluated in 11032 // its own initialization and throws a warning if it does. 11033 class SelfReferenceChecker 11034 : public EvaluatedExprVisitor<SelfReferenceChecker> { 11035 Sema &S; 11036 Decl *OrigDecl; 11037 bool isRecordType; 11038 bool isPODType; 11039 bool isReferenceType; 11040 11041 bool isInitList; 11042 llvm::SmallVector<unsigned, 4> InitFieldIndex; 11043 11044 public: 11045 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 11046 11047 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 11048 S(S), OrigDecl(OrigDecl) { 11049 isPODType = false; 11050 isRecordType = false; 11051 isReferenceType = false; 11052 isInitList = false; 11053 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 11054 isPODType = VD->getType().isPODType(S.Context); 11055 isRecordType = VD->getType()->isRecordType(); 11056 isReferenceType = VD->getType()->isReferenceType(); 11057 } 11058 } 11059 11060 // For most expressions, just call the visitor. For initializer lists, 11061 // track the index of the field being initialized since fields are 11062 // initialized in order allowing use of previously initialized fields. 11063 void CheckExpr(Expr *E) { 11064 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 11065 if (!InitList) { 11066 Visit(E); 11067 return; 11068 } 11069 11070 // Track and increment the index here. 11071 isInitList = true; 11072 InitFieldIndex.push_back(0); 11073 for (auto Child : InitList->children()) { 11074 CheckExpr(cast<Expr>(Child)); 11075 ++InitFieldIndex.back(); 11076 } 11077 InitFieldIndex.pop_back(); 11078 } 11079 11080 // Returns true if MemberExpr is checked and no further checking is needed. 11081 // Returns false if additional checking is required. 11082 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 11083 llvm::SmallVector<FieldDecl*, 4> Fields; 11084 Expr *Base = E; 11085 bool ReferenceField = false; 11086 11087 // Get the field members used. 11088 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11089 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 11090 if (!FD) 11091 return false; 11092 Fields.push_back(FD); 11093 if (FD->getType()->isReferenceType()) 11094 ReferenceField = true; 11095 Base = ME->getBase()->IgnoreParenImpCasts(); 11096 } 11097 11098 // Keep checking only if the base Decl is the same. 11099 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 11100 if (!DRE || DRE->getDecl() != OrigDecl) 11101 return false; 11102 11103 // A reference field can be bound to an unininitialized field. 11104 if (CheckReference && !ReferenceField) 11105 return true; 11106 11107 // Convert FieldDecls to their index number. 11108 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 11109 for (const FieldDecl *I : llvm::reverse(Fields)) 11110 UsedFieldIndex.push_back(I->getFieldIndex()); 11111 11112 // See if a warning is needed by checking the first difference in index 11113 // numbers. If field being used has index less than the field being 11114 // initialized, then the use is safe. 11115 for (auto UsedIter = UsedFieldIndex.begin(), 11116 UsedEnd = UsedFieldIndex.end(), 11117 OrigIter = InitFieldIndex.begin(), 11118 OrigEnd = InitFieldIndex.end(); 11119 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 11120 if (*UsedIter < *OrigIter) 11121 return true; 11122 if (*UsedIter > *OrigIter) 11123 break; 11124 } 11125 11126 // TODO: Add a different warning which will print the field names. 11127 HandleDeclRefExpr(DRE); 11128 return true; 11129 } 11130 11131 // For most expressions, the cast is directly above the DeclRefExpr. 11132 // For conditional operators, the cast can be outside the conditional 11133 // operator if both expressions are DeclRefExpr's. 11134 void HandleValue(Expr *E) { 11135 E = E->IgnoreParens(); 11136 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 11137 HandleDeclRefExpr(DRE); 11138 return; 11139 } 11140 11141 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 11142 Visit(CO->getCond()); 11143 HandleValue(CO->getTrueExpr()); 11144 HandleValue(CO->getFalseExpr()); 11145 return; 11146 } 11147 11148 if (BinaryConditionalOperator *BCO = 11149 dyn_cast<BinaryConditionalOperator>(E)) { 11150 Visit(BCO->getCond()); 11151 HandleValue(BCO->getFalseExpr()); 11152 return; 11153 } 11154 11155 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 11156 HandleValue(OVE->getSourceExpr()); 11157 return; 11158 } 11159 11160 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11161 if (BO->getOpcode() == BO_Comma) { 11162 Visit(BO->getLHS()); 11163 HandleValue(BO->getRHS()); 11164 return; 11165 } 11166 } 11167 11168 if (isa<MemberExpr>(E)) { 11169 if (isInitList) { 11170 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 11171 false /*CheckReference*/)) 11172 return; 11173 } 11174 11175 Expr *Base = E->IgnoreParenImpCasts(); 11176 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11177 // Check for static member variables and don't warn on them. 11178 if (!isa<FieldDecl>(ME->getMemberDecl())) 11179 return; 11180 Base = ME->getBase()->IgnoreParenImpCasts(); 11181 } 11182 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 11183 HandleDeclRefExpr(DRE); 11184 return; 11185 } 11186 11187 Visit(E); 11188 } 11189 11190 // Reference types not handled in HandleValue are handled here since all 11191 // uses of references are bad, not just r-value uses. 11192 void VisitDeclRefExpr(DeclRefExpr *E) { 11193 if (isReferenceType) 11194 HandleDeclRefExpr(E); 11195 } 11196 11197 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 11198 if (E->getCastKind() == CK_LValueToRValue) { 11199 HandleValue(E->getSubExpr()); 11200 return; 11201 } 11202 11203 Inherited::VisitImplicitCastExpr(E); 11204 } 11205 11206 void VisitMemberExpr(MemberExpr *E) { 11207 if (isInitList) { 11208 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 11209 return; 11210 } 11211 11212 // Don't warn on arrays since they can be treated as pointers. 11213 if (E->getType()->canDecayToPointerType()) return; 11214 11215 // Warn when a non-static method call is followed by non-static member 11216 // field accesses, which is followed by a DeclRefExpr. 11217 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 11218 bool Warn = (MD && !MD->isStatic()); 11219 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 11220 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11221 if (!isa<FieldDecl>(ME->getMemberDecl())) 11222 Warn = false; 11223 Base = ME->getBase()->IgnoreParenImpCasts(); 11224 } 11225 11226 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 11227 if (Warn) 11228 HandleDeclRefExpr(DRE); 11229 return; 11230 } 11231 11232 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 11233 // Visit that expression. 11234 Visit(Base); 11235 } 11236 11237 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 11238 Expr *Callee = E->getCallee(); 11239 11240 if (isa<UnresolvedLookupExpr>(Callee)) 11241 return Inherited::VisitCXXOperatorCallExpr(E); 11242 11243 Visit(Callee); 11244 for (auto Arg: E->arguments()) 11245 HandleValue(Arg->IgnoreParenImpCasts()); 11246 } 11247 11248 void VisitUnaryOperator(UnaryOperator *E) { 11249 // For POD record types, addresses of its own members are well-defined. 11250 if (E->getOpcode() == UO_AddrOf && isRecordType && 11251 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 11252 if (!isPODType) 11253 HandleValue(E->getSubExpr()); 11254 return; 11255 } 11256 11257 if (E->isIncrementDecrementOp()) { 11258 HandleValue(E->getSubExpr()); 11259 return; 11260 } 11261 11262 Inherited::VisitUnaryOperator(E); 11263 } 11264 11265 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 11266 11267 void VisitCXXConstructExpr(CXXConstructExpr *E) { 11268 if (E->getConstructor()->isCopyConstructor()) { 11269 Expr *ArgExpr = E->getArg(0); 11270 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 11271 if (ILE->getNumInits() == 1) 11272 ArgExpr = ILE->getInit(0); 11273 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 11274 if (ICE->getCastKind() == CK_NoOp) 11275 ArgExpr = ICE->getSubExpr(); 11276 HandleValue(ArgExpr); 11277 return; 11278 } 11279 Inherited::VisitCXXConstructExpr(E); 11280 } 11281 11282 void VisitCallExpr(CallExpr *E) { 11283 // Treat std::move as a use. 11284 if (E->isCallToStdMove()) { 11285 HandleValue(E->getArg(0)); 11286 return; 11287 } 11288 11289 Inherited::VisitCallExpr(E); 11290 } 11291 11292 void VisitBinaryOperator(BinaryOperator *E) { 11293 if (E->isCompoundAssignmentOp()) { 11294 HandleValue(E->getLHS()); 11295 Visit(E->getRHS()); 11296 return; 11297 } 11298 11299 Inherited::VisitBinaryOperator(E); 11300 } 11301 11302 // A custom visitor for BinaryConditionalOperator is needed because the 11303 // regular visitor would check the condition and true expression separately 11304 // but both point to the same place giving duplicate diagnostics. 11305 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 11306 Visit(E->getCond()); 11307 Visit(E->getFalseExpr()); 11308 } 11309 11310 void HandleDeclRefExpr(DeclRefExpr *DRE) { 11311 Decl* ReferenceDecl = DRE->getDecl(); 11312 if (OrigDecl != ReferenceDecl) return; 11313 unsigned diag; 11314 if (isReferenceType) { 11315 diag = diag::warn_uninit_self_reference_in_reference_init; 11316 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 11317 diag = diag::warn_static_self_reference_in_init; 11318 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 11319 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 11320 DRE->getDecl()->getType()->isRecordType()) { 11321 diag = diag::warn_uninit_self_reference_in_init; 11322 } else { 11323 // Local variables will be handled by the CFG analysis. 11324 return; 11325 } 11326 11327 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE, 11328 S.PDiag(diag) 11329 << DRE->getDecl() << OrigDecl->getLocation() 11330 << DRE->getSourceRange()); 11331 } 11332 }; 11333 11334 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 11335 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 11336 bool DirectInit) { 11337 // Parameters arguments are occassionially constructed with itself, 11338 // for instance, in recursive functions. Skip them. 11339 if (isa<ParmVarDecl>(OrigDecl)) 11340 return; 11341 11342 E = E->IgnoreParens(); 11343 11344 // Skip checking T a = a where T is not a record or reference type. 11345 // Doing so is a way to silence uninitialized warnings. 11346 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 11347 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 11348 if (ICE->getCastKind() == CK_LValueToRValue) 11349 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 11350 if (DRE->getDecl() == OrigDecl) 11351 return; 11352 11353 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 11354 } 11355 } // end anonymous namespace 11356 11357 namespace { 11358 // Simple wrapper to add the name of a variable or (if no variable is 11359 // available) a DeclarationName into a diagnostic. 11360 struct VarDeclOrName { 11361 VarDecl *VDecl; 11362 DeclarationName Name; 11363 11364 friend const Sema::SemaDiagnosticBuilder & 11365 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 11366 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 11367 } 11368 }; 11369 } // end anonymous namespace 11370 11371 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 11372 DeclarationName Name, QualType Type, 11373 TypeSourceInfo *TSI, 11374 SourceRange Range, bool DirectInit, 11375 Expr *Init) { 11376 bool IsInitCapture = !VDecl; 11377 assert((!VDecl || !VDecl->isInitCapture()) && 11378 "init captures are expected to be deduced prior to initialization"); 11379 11380 VarDeclOrName VN{VDecl, Name}; 11381 11382 DeducedType *Deduced = Type->getContainedDeducedType(); 11383 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 11384 11385 // C++11 [dcl.spec.auto]p3 11386 if (!Init) { 11387 assert(VDecl && "no init for init capture deduction?"); 11388 11389 // Except for class argument deduction, and then for an initializing 11390 // declaration only, i.e. no static at class scope or extern. 11391 if (!isa<DeducedTemplateSpecializationType>(Deduced) || 11392 VDecl->hasExternalStorage() || 11393 VDecl->isStaticDataMember()) { 11394 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 11395 << VDecl->getDeclName() << Type; 11396 return QualType(); 11397 } 11398 } 11399 11400 ArrayRef<Expr*> DeduceInits; 11401 if (Init) 11402 DeduceInits = Init; 11403 11404 if (DirectInit) { 11405 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) 11406 DeduceInits = PL->exprs(); 11407 } 11408 11409 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 11410 assert(VDecl && "non-auto type for init capture deduction?"); 11411 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 11412 InitializationKind Kind = InitializationKind::CreateForInit( 11413 VDecl->getLocation(), DirectInit, Init); 11414 // FIXME: Initialization should not be taking a mutable list of inits. 11415 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 11416 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 11417 InitsCopy); 11418 } 11419 11420 if (DirectInit) { 11421 if (auto *IL = dyn_cast<InitListExpr>(Init)) 11422 DeduceInits = IL->inits(); 11423 } 11424 11425 // Deduction only works if we have exactly one source expression. 11426 if (DeduceInits.empty()) { 11427 // It isn't possible to write this directly, but it is possible to 11428 // end up in this situation with "auto x(some_pack...);" 11429 Diag(Init->getBeginLoc(), IsInitCapture 11430 ? diag::err_init_capture_no_expression 11431 : diag::err_auto_var_init_no_expression) 11432 << VN << Type << Range; 11433 return QualType(); 11434 } 11435 11436 if (DeduceInits.size() > 1) { 11437 Diag(DeduceInits[1]->getBeginLoc(), 11438 IsInitCapture ? diag::err_init_capture_multiple_expressions 11439 : diag::err_auto_var_init_multiple_expressions) 11440 << VN << Type << Range; 11441 return QualType(); 11442 } 11443 11444 Expr *DeduceInit = DeduceInits[0]; 11445 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 11446 Diag(Init->getBeginLoc(), IsInitCapture 11447 ? diag::err_init_capture_paren_braces 11448 : diag::err_auto_var_init_paren_braces) 11449 << isa<InitListExpr>(Init) << VN << Type << Range; 11450 return QualType(); 11451 } 11452 11453 // Expressions default to 'id' when we're in a debugger. 11454 bool DefaultedAnyToId = false; 11455 if (getLangOpts().DebuggerCastResultToId && 11456 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 11457 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 11458 if (Result.isInvalid()) { 11459 return QualType(); 11460 } 11461 Init = Result.get(); 11462 DefaultedAnyToId = true; 11463 } 11464 11465 // C++ [dcl.decomp]p1: 11466 // If the assignment-expression [...] has array type A and no ref-qualifier 11467 // is present, e has type cv A 11468 if (VDecl && isa<DecompositionDecl>(VDecl) && 11469 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 11470 DeduceInit->getType()->isConstantArrayType()) 11471 return Context.getQualifiedType(DeduceInit->getType(), 11472 Type.getQualifiers()); 11473 11474 QualType DeducedType; 11475 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 11476 if (!IsInitCapture) 11477 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 11478 else if (isa<InitListExpr>(Init)) 11479 Diag(Range.getBegin(), 11480 diag::err_init_capture_deduction_failure_from_init_list) 11481 << VN 11482 << (DeduceInit->getType().isNull() ? TSI->getType() 11483 : DeduceInit->getType()) 11484 << DeduceInit->getSourceRange(); 11485 else 11486 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 11487 << VN << TSI->getType() 11488 << (DeduceInit->getType().isNull() ? TSI->getType() 11489 : DeduceInit->getType()) 11490 << DeduceInit->getSourceRange(); 11491 } 11492 11493 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 11494 // 'id' instead of a specific object type prevents most of our usual 11495 // checks. 11496 // We only want to warn outside of template instantiations, though: 11497 // inside a template, the 'id' could have come from a parameter. 11498 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 11499 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 11500 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 11501 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 11502 } 11503 11504 return DeducedType; 11505 } 11506 11507 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 11508 Expr *Init) { 11509 QualType DeducedType = deduceVarTypeFromInitializer( 11510 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 11511 VDecl->getSourceRange(), DirectInit, Init); 11512 if (DeducedType.isNull()) { 11513 VDecl->setInvalidDecl(); 11514 return true; 11515 } 11516 11517 VDecl->setType(DeducedType); 11518 assert(VDecl->isLinkageValid()); 11519 11520 // In ARC, infer lifetime. 11521 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 11522 VDecl->setInvalidDecl(); 11523 11524 if (getLangOpts().OpenCL) 11525 deduceOpenCLAddressSpace(VDecl); 11526 11527 // If this is a redeclaration, check that the type we just deduced matches 11528 // the previously declared type. 11529 if (VarDecl *Old = VDecl->getPreviousDecl()) { 11530 // We never need to merge the type, because we cannot form an incomplete 11531 // array of auto, nor deduce such a type. 11532 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 11533 } 11534 11535 // Check the deduced type is valid for a variable declaration. 11536 CheckVariableDeclarationType(VDecl); 11537 return VDecl->isInvalidDecl(); 11538 } 11539 11540 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init, 11541 SourceLocation Loc) { 11542 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 11543 Init = CE->getSubExpr(); 11544 11545 QualType InitType = Init->getType(); 11546 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 11547 InitType.hasNonTrivialToPrimitiveCopyCUnion()) && 11548 "shouldn't be called if type doesn't have a non-trivial C struct"); 11549 if (auto *ILE = dyn_cast<InitListExpr>(Init)) { 11550 for (auto I : ILE->inits()) { 11551 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() && 11552 !I->getType().hasNonTrivialToPrimitiveCopyCUnion()) 11553 continue; 11554 SourceLocation SL = I->getExprLoc(); 11555 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc); 11556 } 11557 return; 11558 } 11559 11560 if (isa<ImplicitValueInitExpr>(Init)) { 11561 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 11562 checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject, 11563 NTCUK_Init); 11564 } else { 11565 // Assume all other explicit initializers involving copying some existing 11566 // object. 11567 // TODO: ignore any explicit initializers where we can guarantee 11568 // copy-elision. 11569 if (InitType.hasNonTrivialToPrimitiveCopyCUnion()) 11570 checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy); 11571 } 11572 } 11573 11574 namespace { 11575 11576 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) { 11577 // Ignore unavailable fields. A field can be marked as unavailable explicitly 11578 // in the source code or implicitly by the compiler if it is in a union 11579 // defined in a system header and has non-trivial ObjC ownership 11580 // qualifications. We don't want those fields to participate in determining 11581 // whether the containing union is non-trivial. 11582 return FD->hasAttr<UnavailableAttr>(); 11583 } 11584 11585 struct DiagNonTrivalCUnionDefaultInitializeVisitor 11586 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 11587 void> { 11588 using Super = 11589 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 11590 void>; 11591 11592 DiagNonTrivalCUnionDefaultInitializeVisitor( 11593 QualType OrigTy, SourceLocation OrigLoc, 11594 Sema::NonTrivialCUnionContext UseContext, Sema &S) 11595 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11596 11597 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT, 11598 const FieldDecl *FD, bool InNonTrivialUnion) { 11599 if (const auto *AT = S.Context.getAsArrayType(QT)) 11600 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11601 InNonTrivialUnion); 11602 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion); 11603 } 11604 11605 void visitARCStrong(QualType QT, const FieldDecl *FD, 11606 bool InNonTrivialUnion) { 11607 if (InNonTrivialUnion) 11608 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11609 << 1 << 0 << QT << FD->getName(); 11610 } 11611 11612 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11613 if (InNonTrivialUnion) 11614 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11615 << 1 << 0 << QT << FD->getName(); 11616 } 11617 11618 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11619 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11620 if (RD->isUnion()) { 11621 if (OrigLoc.isValid()) { 11622 bool IsUnion = false; 11623 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11624 IsUnion = OrigRD->isUnion(); 11625 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11626 << 0 << OrigTy << IsUnion << UseContext; 11627 // Reset OrigLoc so that this diagnostic is emitted only once. 11628 OrigLoc = SourceLocation(); 11629 } 11630 InNonTrivialUnion = true; 11631 } 11632 11633 if (InNonTrivialUnion) 11634 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11635 << 0 << 0 << QT.getUnqualifiedType() << ""; 11636 11637 for (const FieldDecl *FD : RD->fields()) 11638 if (!shouldIgnoreForRecordTriviality(FD)) 11639 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11640 } 11641 11642 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11643 11644 // The non-trivial C union type or the struct/union type that contains a 11645 // non-trivial C union. 11646 QualType OrigTy; 11647 SourceLocation OrigLoc; 11648 Sema::NonTrivialCUnionContext UseContext; 11649 Sema &S; 11650 }; 11651 11652 struct DiagNonTrivalCUnionDestructedTypeVisitor 11653 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> { 11654 using Super = 11655 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>; 11656 11657 DiagNonTrivalCUnionDestructedTypeVisitor( 11658 QualType OrigTy, SourceLocation OrigLoc, 11659 Sema::NonTrivialCUnionContext UseContext, Sema &S) 11660 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11661 11662 void visitWithKind(QualType::DestructionKind DK, QualType QT, 11663 const FieldDecl *FD, bool InNonTrivialUnion) { 11664 if (const auto *AT = S.Context.getAsArrayType(QT)) 11665 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11666 InNonTrivialUnion); 11667 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion); 11668 } 11669 11670 void visitARCStrong(QualType QT, const FieldDecl *FD, 11671 bool InNonTrivialUnion) { 11672 if (InNonTrivialUnion) 11673 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11674 << 1 << 1 << QT << FD->getName(); 11675 } 11676 11677 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11678 if (InNonTrivialUnion) 11679 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11680 << 1 << 1 << QT << FD->getName(); 11681 } 11682 11683 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11684 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11685 if (RD->isUnion()) { 11686 if (OrigLoc.isValid()) { 11687 bool IsUnion = false; 11688 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11689 IsUnion = OrigRD->isUnion(); 11690 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11691 << 1 << OrigTy << IsUnion << UseContext; 11692 // Reset OrigLoc so that this diagnostic is emitted only once. 11693 OrigLoc = SourceLocation(); 11694 } 11695 InNonTrivialUnion = true; 11696 } 11697 11698 if (InNonTrivialUnion) 11699 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11700 << 0 << 1 << QT.getUnqualifiedType() << ""; 11701 11702 for (const FieldDecl *FD : RD->fields()) 11703 if (!shouldIgnoreForRecordTriviality(FD)) 11704 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11705 } 11706 11707 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11708 void visitCXXDestructor(QualType QT, const FieldDecl *FD, 11709 bool InNonTrivialUnion) {} 11710 11711 // The non-trivial C union type or the struct/union type that contains a 11712 // non-trivial C union. 11713 QualType OrigTy; 11714 SourceLocation OrigLoc; 11715 Sema::NonTrivialCUnionContext UseContext; 11716 Sema &S; 11717 }; 11718 11719 struct DiagNonTrivalCUnionCopyVisitor 11720 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> { 11721 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>; 11722 11723 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc, 11724 Sema::NonTrivialCUnionContext UseContext, 11725 Sema &S) 11726 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11727 11728 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT, 11729 const FieldDecl *FD, bool InNonTrivialUnion) { 11730 if (const auto *AT = S.Context.getAsArrayType(QT)) 11731 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11732 InNonTrivialUnion); 11733 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion); 11734 } 11735 11736 void visitARCStrong(QualType QT, const FieldDecl *FD, 11737 bool InNonTrivialUnion) { 11738 if (InNonTrivialUnion) 11739 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11740 << 1 << 2 << QT << FD->getName(); 11741 } 11742 11743 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11744 if (InNonTrivialUnion) 11745 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11746 << 1 << 2 << QT << FD->getName(); 11747 } 11748 11749 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11750 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11751 if (RD->isUnion()) { 11752 if (OrigLoc.isValid()) { 11753 bool IsUnion = false; 11754 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11755 IsUnion = OrigRD->isUnion(); 11756 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11757 << 2 << OrigTy << IsUnion << UseContext; 11758 // Reset OrigLoc so that this diagnostic is emitted only once. 11759 OrigLoc = SourceLocation(); 11760 } 11761 InNonTrivialUnion = true; 11762 } 11763 11764 if (InNonTrivialUnion) 11765 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11766 << 0 << 2 << QT.getUnqualifiedType() << ""; 11767 11768 for (const FieldDecl *FD : RD->fields()) 11769 if (!shouldIgnoreForRecordTriviality(FD)) 11770 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11771 } 11772 11773 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT, 11774 const FieldDecl *FD, bool InNonTrivialUnion) {} 11775 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11776 void visitVolatileTrivial(QualType QT, const FieldDecl *FD, 11777 bool InNonTrivialUnion) {} 11778 11779 // The non-trivial C union type or the struct/union type that contains a 11780 // non-trivial C union. 11781 QualType OrigTy; 11782 SourceLocation OrigLoc; 11783 Sema::NonTrivialCUnionContext UseContext; 11784 Sema &S; 11785 }; 11786 11787 } // namespace 11788 11789 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc, 11790 NonTrivialCUnionContext UseContext, 11791 unsigned NonTrivialKind) { 11792 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 11793 QT.hasNonTrivialToPrimitiveDestructCUnion() || 11794 QT.hasNonTrivialToPrimitiveCopyCUnion()) && 11795 "shouldn't be called if type doesn't have a non-trivial C union"); 11796 11797 if ((NonTrivialKind & NTCUK_Init) && 11798 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 11799 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this) 11800 .visit(QT, nullptr, false); 11801 if ((NonTrivialKind & NTCUK_Destruct) && 11802 QT.hasNonTrivialToPrimitiveDestructCUnion()) 11803 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this) 11804 .visit(QT, nullptr, false); 11805 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion()) 11806 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this) 11807 .visit(QT, nullptr, false); 11808 } 11809 11810 /// AddInitializerToDecl - Adds the initializer Init to the 11811 /// declaration dcl. If DirectInit is true, this is C++ direct 11812 /// initialization rather than copy initialization. 11813 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 11814 // If there is no declaration, there was an error parsing it. Just ignore 11815 // the initializer. 11816 if (!RealDecl || RealDecl->isInvalidDecl()) { 11817 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 11818 return; 11819 } 11820 11821 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 11822 // Pure-specifiers are handled in ActOnPureSpecifier. 11823 Diag(Method->getLocation(), diag::err_member_function_initialization) 11824 << Method->getDeclName() << Init->getSourceRange(); 11825 Method->setInvalidDecl(); 11826 return; 11827 } 11828 11829 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 11830 if (!VDecl) { 11831 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 11832 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 11833 RealDecl->setInvalidDecl(); 11834 return; 11835 } 11836 11837 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 11838 if (VDecl->getType()->isUndeducedType()) { 11839 // Attempt typo correction early so that the type of the init expression can 11840 // be deduced based on the chosen correction if the original init contains a 11841 // TypoExpr. 11842 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 11843 if (!Res.isUsable()) { 11844 RealDecl->setInvalidDecl(); 11845 return; 11846 } 11847 Init = Res.get(); 11848 11849 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 11850 return; 11851 } 11852 11853 // dllimport cannot be used on variable definitions. 11854 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 11855 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 11856 VDecl->setInvalidDecl(); 11857 return; 11858 } 11859 11860 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 11861 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 11862 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 11863 VDecl->setInvalidDecl(); 11864 return; 11865 } 11866 11867 if (!VDecl->getType()->isDependentType()) { 11868 // A definition must end up with a complete type, which means it must be 11869 // complete with the restriction that an array type might be completed by 11870 // the initializer; note that later code assumes this restriction. 11871 QualType BaseDeclType = VDecl->getType(); 11872 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 11873 BaseDeclType = Array->getElementType(); 11874 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 11875 diag::err_typecheck_decl_incomplete_type)) { 11876 RealDecl->setInvalidDecl(); 11877 return; 11878 } 11879 11880 // The variable can not have an abstract class type. 11881 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 11882 diag::err_abstract_type_in_decl, 11883 AbstractVariableType)) 11884 VDecl->setInvalidDecl(); 11885 } 11886 11887 // If adding the initializer will turn this declaration into a definition, 11888 // and we already have a definition for this variable, diagnose or otherwise 11889 // handle the situation. 11890 VarDecl *Def; 11891 if ((Def = VDecl->getDefinition()) && Def != VDecl && 11892 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 11893 !VDecl->isThisDeclarationADemotedDefinition() && 11894 checkVarDeclRedefinition(Def, VDecl)) 11895 return; 11896 11897 if (getLangOpts().CPlusPlus) { 11898 // C++ [class.static.data]p4 11899 // If a static data member is of const integral or const 11900 // enumeration type, its declaration in the class definition can 11901 // specify a constant-initializer which shall be an integral 11902 // constant expression (5.19). In that case, the member can appear 11903 // in integral constant expressions. The member shall still be 11904 // defined in a namespace scope if it is used in the program and the 11905 // namespace scope definition shall not contain an initializer. 11906 // 11907 // We already performed a redefinition check above, but for static 11908 // data members we also need to check whether there was an in-class 11909 // declaration with an initializer. 11910 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 11911 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 11912 << VDecl->getDeclName(); 11913 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 11914 diag::note_previous_initializer) 11915 << 0; 11916 return; 11917 } 11918 11919 if (VDecl->hasLocalStorage()) 11920 setFunctionHasBranchProtectedScope(); 11921 11922 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 11923 VDecl->setInvalidDecl(); 11924 return; 11925 } 11926 } 11927 11928 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 11929 // a kernel function cannot be initialized." 11930 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 11931 Diag(VDecl->getLocation(), diag::err_local_cant_init); 11932 VDecl->setInvalidDecl(); 11933 return; 11934 } 11935 11936 // Get the decls type and save a reference for later, since 11937 // CheckInitializerTypes may change it. 11938 QualType DclT = VDecl->getType(), SavT = DclT; 11939 11940 // Expressions default to 'id' when we're in a debugger 11941 // and we are assigning it to a variable of Objective-C pointer type. 11942 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 11943 Init->getType() == Context.UnknownAnyTy) { 11944 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 11945 if (Result.isInvalid()) { 11946 VDecl->setInvalidDecl(); 11947 return; 11948 } 11949 Init = Result.get(); 11950 } 11951 11952 // Perform the initialization. 11953 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 11954 if (!VDecl->isInvalidDecl()) { 11955 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 11956 InitializationKind Kind = InitializationKind::CreateForInit( 11957 VDecl->getLocation(), DirectInit, Init); 11958 11959 MultiExprArg Args = Init; 11960 if (CXXDirectInit) 11961 Args = MultiExprArg(CXXDirectInit->getExprs(), 11962 CXXDirectInit->getNumExprs()); 11963 11964 // Try to correct any TypoExprs in the initialization arguments. 11965 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 11966 ExprResult Res = CorrectDelayedTyposInExpr( 11967 Args[Idx], VDecl, [this, Entity, Kind](Expr *E) { 11968 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 11969 return Init.Failed() ? ExprError() : E; 11970 }); 11971 if (Res.isInvalid()) { 11972 VDecl->setInvalidDecl(); 11973 } else if (Res.get() != Args[Idx]) { 11974 Args[Idx] = Res.get(); 11975 } 11976 } 11977 if (VDecl->isInvalidDecl()) 11978 return; 11979 11980 InitializationSequence InitSeq(*this, Entity, Kind, Args, 11981 /*TopLevelOfInitList=*/false, 11982 /*TreatUnavailableAsInvalid=*/false); 11983 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 11984 if (Result.isInvalid()) { 11985 VDecl->setInvalidDecl(); 11986 return; 11987 } 11988 11989 Init = Result.getAs<Expr>(); 11990 } 11991 11992 // Check for self-references within variable initializers. 11993 // Variables declared within a function/method body (except for references) 11994 // are handled by a dataflow analysis. 11995 // This is undefined behavior in C++, but valid in C. 11996 if (getLangOpts().CPlusPlus) { 11997 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 11998 VDecl->getType()->isReferenceType()) { 11999 CheckSelfReference(*this, RealDecl, Init, DirectInit); 12000 } 12001 } 12002 12003 // If the type changed, it means we had an incomplete type that was 12004 // completed by the initializer. For example: 12005 // int ary[] = { 1, 3, 5 }; 12006 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 12007 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 12008 VDecl->setType(DclT); 12009 12010 if (!VDecl->isInvalidDecl()) { 12011 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 12012 12013 if (VDecl->hasAttr<BlocksAttr>()) 12014 checkRetainCycles(VDecl, Init); 12015 12016 // It is safe to assign a weak reference into a strong variable. 12017 // Although this code can still have problems: 12018 // id x = self.weakProp; 12019 // id y = self.weakProp; 12020 // we do not warn to warn spuriously when 'x' and 'y' are on separate 12021 // paths through the function. This should be revisited if 12022 // -Wrepeated-use-of-weak is made flow-sensitive. 12023 if (FunctionScopeInfo *FSI = getCurFunction()) 12024 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 12025 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 12026 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 12027 Init->getBeginLoc())) 12028 FSI->markSafeWeakUse(Init); 12029 } 12030 12031 // The initialization is usually a full-expression. 12032 // 12033 // FIXME: If this is a braced initialization of an aggregate, it is not 12034 // an expression, and each individual field initializer is a separate 12035 // full-expression. For instance, in: 12036 // 12037 // struct Temp { ~Temp(); }; 12038 // struct S { S(Temp); }; 12039 // struct T { S a, b; } t = { Temp(), Temp() } 12040 // 12041 // we should destroy the first Temp before constructing the second. 12042 ExprResult Result = 12043 ActOnFinishFullExpr(Init, VDecl->getLocation(), 12044 /*DiscardedValue*/ false, VDecl->isConstexpr()); 12045 if (Result.isInvalid()) { 12046 VDecl->setInvalidDecl(); 12047 return; 12048 } 12049 Init = Result.get(); 12050 12051 // Attach the initializer to the decl. 12052 VDecl->setInit(Init); 12053 12054 if (VDecl->isLocalVarDecl()) { 12055 // Don't check the initializer if the declaration is malformed. 12056 if (VDecl->isInvalidDecl()) { 12057 // do nothing 12058 12059 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 12060 // This is true even in C++ for OpenCL. 12061 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 12062 CheckForConstantInitializer(Init, DclT); 12063 12064 // Otherwise, C++ does not restrict the initializer. 12065 } else if (getLangOpts().CPlusPlus) { 12066 // do nothing 12067 12068 // C99 6.7.8p4: All the expressions in an initializer for an object that has 12069 // static storage duration shall be constant expressions or string literals. 12070 } else if (VDecl->getStorageClass() == SC_Static) { 12071 CheckForConstantInitializer(Init, DclT); 12072 12073 // C89 is stricter than C99 for aggregate initializers. 12074 // C89 6.5.7p3: All the expressions [...] in an initializer list 12075 // for an object that has aggregate or union type shall be 12076 // constant expressions. 12077 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 12078 isa<InitListExpr>(Init)) { 12079 const Expr *Culprit; 12080 if (!Init->isConstantInitializer(Context, false, &Culprit)) { 12081 Diag(Culprit->getExprLoc(), 12082 diag::ext_aggregate_init_not_constant) 12083 << Culprit->getSourceRange(); 12084 } 12085 } 12086 12087 if (auto *E = dyn_cast<ExprWithCleanups>(Init)) 12088 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens())) 12089 if (VDecl->hasLocalStorage()) 12090 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 12091 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 12092 VDecl->getLexicalDeclContext()->isRecord()) { 12093 // This is an in-class initialization for a static data member, e.g., 12094 // 12095 // struct S { 12096 // static const int value = 17; 12097 // }; 12098 12099 // C++ [class.mem]p4: 12100 // A member-declarator can contain a constant-initializer only 12101 // if it declares a static member (9.4) of const integral or 12102 // const enumeration type, see 9.4.2. 12103 // 12104 // C++11 [class.static.data]p3: 12105 // If a non-volatile non-inline const static data member is of integral 12106 // or enumeration type, its declaration in the class definition can 12107 // specify a brace-or-equal-initializer in which every initializer-clause 12108 // that is an assignment-expression is a constant expression. A static 12109 // data member of literal type can be declared in the class definition 12110 // with the constexpr specifier; if so, its declaration shall specify a 12111 // brace-or-equal-initializer in which every initializer-clause that is 12112 // an assignment-expression is a constant expression. 12113 12114 // Do nothing on dependent types. 12115 if (DclT->isDependentType()) { 12116 12117 // Allow any 'static constexpr' members, whether or not they are of literal 12118 // type. We separately check that every constexpr variable is of literal 12119 // type. 12120 } else if (VDecl->isConstexpr()) { 12121 12122 // Require constness. 12123 } else if (!DclT.isConstQualified()) { 12124 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 12125 << Init->getSourceRange(); 12126 VDecl->setInvalidDecl(); 12127 12128 // We allow integer constant expressions in all cases. 12129 } else if (DclT->isIntegralOrEnumerationType()) { 12130 // Check whether the expression is a constant expression. 12131 SourceLocation Loc; 12132 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 12133 // In C++11, a non-constexpr const static data member with an 12134 // in-class initializer cannot be volatile. 12135 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 12136 else if (Init->isValueDependent()) 12137 ; // Nothing to check. 12138 else if (Init->isIntegerConstantExpr(Context, &Loc)) 12139 ; // Ok, it's an ICE! 12140 else if (Init->getType()->isScopedEnumeralType() && 12141 Init->isCXX11ConstantExpr(Context)) 12142 ; // Ok, it is a scoped-enum constant expression. 12143 else if (Init->isEvaluatable(Context)) { 12144 // If we can constant fold the initializer through heroics, accept it, 12145 // but report this as a use of an extension for -pedantic. 12146 Diag(Loc, diag::ext_in_class_initializer_non_constant) 12147 << Init->getSourceRange(); 12148 } else { 12149 // Otherwise, this is some crazy unknown case. Report the issue at the 12150 // location provided by the isIntegerConstantExpr failed check. 12151 Diag(Loc, diag::err_in_class_initializer_non_constant) 12152 << Init->getSourceRange(); 12153 VDecl->setInvalidDecl(); 12154 } 12155 12156 // We allow foldable floating-point constants as an extension. 12157 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 12158 // In C++98, this is a GNU extension. In C++11, it is not, but we support 12159 // it anyway and provide a fixit to add the 'constexpr'. 12160 if (getLangOpts().CPlusPlus11) { 12161 Diag(VDecl->getLocation(), 12162 diag::ext_in_class_initializer_float_type_cxx11) 12163 << DclT << Init->getSourceRange(); 12164 Diag(VDecl->getBeginLoc(), 12165 diag::note_in_class_initializer_float_type_cxx11) 12166 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12167 } else { 12168 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 12169 << DclT << Init->getSourceRange(); 12170 12171 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 12172 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 12173 << Init->getSourceRange(); 12174 VDecl->setInvalidDecl(); 12175 } 12176 } 12177 12178 // Suggest adding 'constexpr' in C++11 for literal types. 12179 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 12180 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 12181 << DclT << Init->getSourceRange() 12182 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12183 VDecl->setConstexpr(true); 12184 12185 } else { 12186 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 12187 << DclT << Init->getSourceRange(); 12188 VDecl->setInvalidDecl(); 12189 } 12190 } else if (VDecl->isFileVarDecl()) { 12191 // In C, extern is typically used to avoid tentative definitions when 12192 // declaring variables in headers, but adding an intializer makes it a 12193 // definition. This is somewhat confusing, so GCC and Clang both warn on it. 12194 // In C++, extern is often used to give implictly static const variables 12195 // external linkage, so don't warn in that case. If selectany is present, 12196 // this might be header code intended for C and C++ inclusion, so apply the 12197 // C++ rules. 12198 if (VDecl->getStorageClass() == SC_Extern && 12199 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 12200 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 12201 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 12202 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 12203 Diag(VDecl->getLocation(), diag::warn_extern_init); 12204 12205 // In Microsoft C++ mode, a const variable defined in namespace scope has 12206 // external linkage by default if the variable is declared with 12207 // __declspec(dllexport). 12208 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 12209 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() && 12210 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition()) 12211 VDecl->setStorageClass(SC_Extern); 12212 12213 // C99 6.7.8p4. All file scoped initializers need to be constant. 12214 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 12215 CheckForConstantInitializer(Init, DclT); 12216 } 12217 12218 QualType InitType = Init->getType(); 12219 if (!InitType.isNull() && 12220 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12221 InitType.hasNonTrivialToPrimitiveCopyCUnion())) 12222 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc()); 12223 12224 // We will represent direct-initialization similarly to copy-initialization: 12225 // int x(1); -as-> int x = 1; 12226 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 12227 // 12228 // Clients that want to distinguish between the two forms, can check for 12229 // direct initializer using VarDecl::getInitStyle(). 12230 // A major benefit is that clients that don't particularly care about which 12231 // exactly form was it (like the CodeGen) can handle both cases without 12232 // special case code. 12233 12234 // C++ 8.5p11: 12235 // The form of initialization (using parentheses or '=') is generally 12236 // insignificant, but does matter when the entity being initialized has a 12237 // class type. 12238 if (CXXDirectInit) { 12239 assert(DirectInit && "Call-style initializer must be direct init."); 12240 VDecl->setInitStyle(VarDecl::CallInit); 12241 } else if (DirectInit) { 12242 // This must be list-initialization. No other way is direct-initialization. 12243 VDecl->setInitStyle(VarDecl::ListInit); 12244 } 12245 12246 CheckCompleteVariableDeclaration(VDecl); 12247 } 12248 12249 /// ActOnInitializerError - Given that there was an error parsing an 12250 /// initializer for the given declaration, try to return to some form 12251 /// of sanity. 12252 void Sema::ActOnInitializerError(Decl *D) { 12253 // Our main concern here is re-establishing invariants like "a 12254 // variable's type is either dependent or complete". 12255 if (!D || D->isInvalidDecl()) return; 12256 12257 VarDecl *VD = dyn_cast<VarDecl>(D); 12258 if (!VD) return; 12259 12260 // Bindings are not usable if we can't make sense of the initializer. 12261 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 12262 for (auto *BD : DD->bindings()) 12263 BD->setInvalidDecl(); 12264 12265 // Auto types are meaningless if we can't make sense of the initializer. 12266 if (ParsingInitForAutoVars.count(D)) { 12267 D->setInvalidDecl(); 12268 return; 12269 } 12270 12271 QualType Ty = VD->getType(); 12272 if (Ty->isDependentType()) return; 12273 12274 // Require a complete type. 12275 if (RequireCompleteType(VD->getLocation(), 12276 Context.getBaseElementType(Ty), 12277 diag::err_typecheck_decl_incomplete_type)) { 12278 VD->setInvalidDecl(); 12279 return; 12280 } 12281 12282 // Require a non-abstract type. 12283 if (RequireNonAbstractType(VD->getLocation(), Ty, 12284 diag::err_abstract_type_in_decl, 12285 AbstractVariableType)) { 12286 VD->setInvalidDecl(); 12287 return; 12288 } 12289 12290 // Don't bother complaining about constructors or destructors, 12291 // though. 12292 } 12293 12294 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 12295 // If there is no declaration, there was an error parsing it. Just ignore it. 12296 if (!RealDecl) 12297 return; 12298 12299 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 12300 QualType Type = Var->getType(); 12301 12302 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 12303 if (isa<DecompositionDecl>(RealDecl)) { 12304 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 12305 Var->setInvalidDecl(); 12306 return; 12307 } 12308 12309 if (Type->isUndeducedType() && 12310 DeduceVariableDeclarationType(Var, false, nullptr)) 12311 return; 12312 12313 // C++11 [class.static.data]p3: A static data member can be declared with 12314 // the constexpr specifier; if so, its declaration shall specify 12315 // a brace-or-equal-initializer. 12316 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 12317 // the definition of a variable [...] or the declaration of a static data 12318 // member. 12319 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 12320 !Var->isThisDeclarationADemotedDefinition()) { 12321 if (Var->isStaticDataMember()) { 12322 // C++1z removes the relevant rule; the in-class declaration is always 12323 // a definition there. 12324 if (!getLangOpts().CPlusPlus17 && 12325 !Context.getTargetInfo().getCXXABI().isMicrosoft()) { 12326 Diag(Var->getLocation(), 12327 diag::err_constexpr_static_mem_var_requires_init) 12328 << Var->getDeclName(); 12329 Var->setInvalidDecl(); 12330 return; 12331 } 12332 } else { 12333 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 12334 Var->setInvalidDecl(); 12335 return; 12336 } 12337 } 12338 12339 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 12340 // be initialized. 12341 if (!Var->isInvalidDecl() && 12342 Var->getType().getAddressSpace() == LangAS::opencl_constant && 12343 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 12344 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 12345 Var->setInvalidDecl(); 12346 return; 12347 } 12348 12349 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition(); 12350 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly && 12351 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 12352 checkNonTrivialCUnion(Var->getType(), Var->getLocation(), 12353 NTCUC_DefaultInitializedObject, NTCUK_Init); 12354 12355 12356 switch (DefKind) { 12357 case VarDecl::Definition: 12358 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 12359 break; 12360 12361 // We have an out-of-line definition of a static data member 12362 // that has an in-class initializer, so we type-check this like 12363 // a declaration. 12364 // 12365 LLVM_FALLTHROUGH; 12366 12367 case VarDecl::DeclarationOnly: 12368 // It's only a declaration. 12369 12370 // Block scope. C99 6.7p7: If an identifier for an object is 12371 // declared with no linkage (C99 6.2.2p6), the type for the 12372 // object shall be complete. 12373 if (!Type->isDependentType() && Var->isLocalVarDecl() && 12374 !Var->hasLinkage() && !Var->isInvalidDecl() && 12375 RequireCompleteType(Var->getLocation(), Type, 12376 diag::err_typecheck_decl_incomplete_type)) 12377 Var->setInvalidDecl(); 12378 12379 // Make sure that the type is not abstract. 12380 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12381 RequireNonAbstractType(Var->getLocation(), Type, 12382 diag::err_abstract_type_in_decl, 12383 AbstractVariableType)) 12384 Var->setInvalidDecl(); 12385 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12386 Var->getStorageClass() == SC_PrivateExtern) { 12387 Diag(Var->getLocation(), diag::warn_private_extern); 12388 Diag(Var->getLocation(), diag::note_private_extern); 12389 } 12390 12391 if (Context.getTargetInfo().allowDebugInfoForExternalVar() && 12392 !Var->isInvalidDecl() && !getLangOpts().CPlusPlus) 12393 ExternalDeclarations.push_back(Var); 12394 12395 return; 12396 12397 case VarDecl::TentativeDefinition: 12398 // File scope. C99 6.9.2p2: A declaration of an identifier for an 12399 // object that has file scope without an initializer, and without a 12400 // storage-class specifier or with the storage-class specifier "static", 12401 // constitutes a tentative definition. Note: A tentative definition with 12402 // external linkage is valid (C99 6.2.2p5). 12403 if (!Var->isInvalidDecl()) { 12404 if (const IncompleteArrayType *ArrayT 12405 = Context.getAsIncompleteArrayType(Type)) { 12406 if (RequireCompleteType(Var->getLocation(), 12407 ArrayT->getElementType(), 12408 diag::err_illegal_decl_array_incomplete_type)) 12409 Var->setInvalidDecl(); 12410 } else if (Var->getStorageClass() == SC_Static) { 12411 // C99 6.9.2p3: If the declaration of an identifier for an object is 12412 // a tentative definition and has internal linkage (C99 6.2.2p3), the 12413 // declared type shall not be an incomplete type. 12414 // NOTE: code such as the following 12415 // static struct s; 12416 // struct s { int a; }; 12417 // is accepted by gcc. Hence here we issue a warning instead of 12418 // an error and we do not invalidate the static declaration. 12419 // NOTE: to avoid multiple warnings, only check the first declaration. 12420 if (Var->isFirstDecl()) 12421 RequireCompleteType(Var->getLocation(), Type, 12422 diag::ext_typecheck_decl_incomplete_type); 12423 } 12424 } 12425 12426 // Record the tentative definition; we're done. 12427 if (!Var->isInvalidDecl()) 12428 TentativeDefinitions.push_back(Var); 12429 return; 12430 } 12431 12432 // Provide a specific diagnostic for uninitialized variable 12433 // definitions with incomplete array type. 12434 if (Type->isIncompleteArrayType()) { 12435 Diag(Var->getLocation(), 12436 diag::err_typecheck_incomplete_array_needs_initializer); 12437 Var->setInvalidDecl(); 12438 return; 12439 } 12440 12441 // Provide a specific diagnostic for uninitialized variable 12442 // definitions with reference type. 12443 if (Type->isReferenceType()) { 12444 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 12445 << Var->getDeclName() 12446 << SourceRange(Var->getLocation(), Var->getLocation()); 12447 Var->setInvalidDecl(); 12448 return; 12449 } 12450 12451 // Do not attempt to type-check the default initializer for a 12452 // variable with dependent type. 12453 if (Type->isDependentType()) 12454 return; 12455 12456 if (Var->isInvalidDecl()) 12457 return; 12458 12459 if (!Var->hasAttr<AliasAttr>()) { 12460 if (RequireCompleteType(Var->getLocation(), 12461 Context.getBaseElementType(Type), 12462 diag::err_typecheck_decl_incomplete_type)) { 12463 Var->setInvalidDecl(); 12464 return; 12465 } 12466 } else { 12467 return; 12468 } 12469 12470 // The variable can not have an abstract class type. 12471 if (RequireNonAbstractType(Var->getLocation(), Type, 12472 diag::err_abstract_type_in_decl, 12473 AbstractVariableType)) { 12474 Var->setInvalidDecl(); 12475 return; 12476 } 12477 12478 // Check for jumps past the implicit initializer. C++0x 12479 // clarifies that this applies to a "variable with automatic 12480 // storage duration", not a "local variable". 12481 // C++11 [stmt.dcl]p3 12482 // A program that jumps from a point where a variable with automatic 12483 // storage duration is not in scope to a point where it is in scope is 12484 // ill-formed unless the variable has scalar type, class type with a 12485 // trivial default constructor and a trivial destructor, a cv-qualified 12486 // version of one of these types, or an array of one of the preceding 12487 // types and is declared without an initializer. 12488 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 12489 if (const RecordType *Record 12490 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 12491 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 12492 // Mark the function (if we're in one) for further checking even if the 12493 // looser rules of C++11 do not require such checks, so that we can 12494 // diagnose incompatibilities with C++98. 12495 if (!CXXRecord->isPOD()) 12496 setFunctionHasBranchProtectedScope(); 12497 } 12498 } 12499 // In OpenCL, we can't initialize objects in the __local address space, 12500 // even implicitly, so don't synthesize an implicit initializer. 12501 if (getLangOpts().OpenCL && 12502 Var->getType().getAddressSpace() == LangAS::opencl_local) 12503 return; 12504 // C++03 [dcl.init]p9: 12505 // If no initializer is specified for an object, and the 12506 // object is of (possibly cv-qualified) non-POD class type (or 12507 // array thereof), the object shall be default-initialized; if 12508 // the object is of const-qualified type, the underlying class 12509 // type shall have a user-declared default 12510 // constructor. Otherwise, if no initializer is specified for 12511 // a non- static object, the object and its subobjects, if 12512 // any, have an indeterminate initial value); if the object 12513 // or any of its subobjects are of const-qualified type, the 12514 // program is ill-formed. 12515 // C++0x [dcl.init]p11: 12516 // If no initializer is specified for an object, the object is 12517 // default-initialized; [...]. 12518 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 12519 InitializationKind Kind 12520 = InitializationKind::CreateDefault(Var->getLocation()); 12521 12522 InitializationSequence InitSeq(*this, Entity, Kind, None); 12523 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 12524 if (Init.isInvalid()) 12525 Var->setInvalidDecl(); 12526 else if (Init.get()) { 12527 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 12528 // This is important for template substitution. 12529 Var->setInitStyle(VarDecl::CallInit); 12530 } 12531 12532 CheckCompleteVariableDeclaration(Var); 12533 } 12534 } 12535 12536 void Sema::ActOnCXXForRangeDecl(Decl *D) { 12537 // If there is no declaration, there was an error parsing it. Ignore it. 12538 if (!D) 12539 return; 12540 12541 VarDecl *VD = dyn_cast<VarDecl>(D); 12542 if (!VD) { 12543 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 12544 D->setInvalidDecl(); 12545 return; 12546 } 12547 12548 VD->setCXXForRangeDecl(true); 12549 12550 // for-range-declaration cannot be given a storage class specifier. 12551 int Error = -1; 12552 switch (VD->getStorageClass()) { 12553 case SC_None: 12554 break; 12555 case SC_Extern: 12556 Error = 0; 12557 break; 12558 case SC_Static: 12559 Error = 1; 12560 break; 12561 case SC_PrivateExtern: 12562 Error = 2; 12563 break; 12564 case SC_Auto: 12565 Error = 3; 12566 break; 12567 case SC_Register: 12568 Error = 4; 12569 break; 12570 } 12571 if (Error != -1) { 12572 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 12573 << VD->getDeclName() << Error; 12574 D->setInvalidDecl(); 12575 } 12576 } 12577 12578 StmtResult 12579 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 12580 IdentifierInfo *Ident, 12581 ParsedAttributes &Attrs, 12582 SourceLocation AttrEnd) { 12583 // C++1y [stmt.iter]p1: 12584 // A range-based for statement of the form 12585 // for ( for-range-identifier : for-range-initializer ) statement 12586 // is equivalent to 12587 // for ( auto&& for-range-identifier : for-range-initializer ) statement 12588 DeclSpec DS(Attrs.getPool().getFactory()); 12589 12590 const char *PrevSpec; 12591 unsigned DiagID; 12592 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 12593 getPrintingPolicy()); 12594 12595 Declarator D(DS, DeclaratorContext::ForContext); 12596 D.SetIdentifier(Ident, IdentLoc); 12597 D.takeAttributes(Attrs, AttrEnd); 12598 12599 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false), 12600 IdentLoc); 12601 Decl *Var = ActOnDeclarator(S, D); 12602 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 12603 FinalizeDeclaration(Var); 12604 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 12605 AttrEnd.isValid() ? AttrEnd : IdentLoc); 12606 } 12607 12608 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 12609 if (var->isInvalidDecl()) return; 12610 12611 if (getLangOpts().OpenCL) { 12612 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 12613 // initialiser 12614 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 12615 !var->hasInit()) { 12616 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 12617 << 1 /*Init*/; 12618 var->setInvalidDecl(); 12619 return; 12620 } 12621 } 12622 12623 // In Objective-C, don't allow jumps past the implicit initialization of a 12624 // local retaining variable. 12625 if (getLangOpts().ObjC && 12626 var->hasLocalStorage()) { 12627 switch (var->getType().getObjCLifetime()) { 12628 case Qualifiers::OCL_None: 12629 case Qualifiers::OCL_ExplicitNone: 12630 case Qualifiers::OCL_Autoreleasing: 12631 break; 12632 12633 case Qualifiers::OCL_Weak: 12634 case Qualifiers::OCL_Strong: 12635 setFunctionHasBranchProtectedScope(); 12636 break; 12637 } 12638 } 12639 12640 if (var->hasLocalStorage() && 12641 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 12642 setFunctionHasBranchProtectedScope(); 12643 12644 // Warn about externally-visible variables being defined without a 12645 // prior declaration. We only want to do this for global 12646 // declarations, but we also specifically need to avoid doing it for 12647 // class members because the linkage of an anonymous class can 12648 // change if it's later given a typedef name. 12649 if (var->isThisDeclarationADefinition() && 12650 var->getDeclContext()->getRedeclContext()->isFileContext() && 12651 var->isExternallyVisible() && var->hasLinkage() && 12652 !var->isInline() && !var->getDescribedVarTemplate() && 12653 !isa<VarTemplatePartialSpecializationDecl>(var) && 12654 !isTemplateInstantiation(var->getTemplateSpecializationKind()) && 12655 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 12656 var->getLocation())) { 12657 // Find a previous declaration that's not a definition. 12658 VarDecl *prev = var->getPreviousDecl(); 12659 while (prev && prev->isThisDeclarationADefinition()) 12660 prev = prev->getPreviousDecl(); 12661 12662 if (!prev) { 12663 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 12664 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 12665 << /* variable */ 0; 12666 } 12667 } 12668 12669 // Cache the result of checking for constant initialization. 12670 Optional<bool> CacheHasConstInit; 12671 const Expr *CacheCulprit = nullptr; 12672 auto checkConstInit = [&]() mutable { 12673 if (!CacheHasConstInit) 12674 CacheHasConstInit = var->getInit()->isConstantInitializer( 12675 Context, var->getType()->isReferenceType(), &CacheCulprit); 12676 return *CacheHasConstInit; 12677 }; 12678 12679 if (var->getTLSKind() == VarDecl::TLS_Static) { 12680 if (var->getType().isDestructedType()) { 12681 // GNU C++98 edits for __thread, [basic.start.term]p3: 12682 // The type of an object with thread storage duration shall not 12683 // have a non-trivial destructor. 12684 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 12685 if (getLangOpts().CPlusPlus11) 12686 Diag(var->getLocation(), diag::note_use_thread_local); 12687 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 12688 if (!checkConstInit()) { 12689 // GNU C++98 edits for __thread, [basic.start.init]p4: 12690 // An object of thread storage duration shall not require dynamic 12691 // initialization. 12692 // FIXME: Need strict checking here. 12693 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 12694 << CacheCulprit->getSourceRange(); 12695 if (getLangOpts().CPlusPlus11) 12696 Diag(var->getLocation(), diag::note_use_thread_local); 12697 } 12698 } 12699 } 12700 12701 // Apply section attributes and pragmas to global variables. 12702 bool GlobalStorage = var->hasGlobalStorage(); 12703 if (GlobalStorage && var->isThisDeclarationADefinition() && 12704 !inTemplateInstantiation()) { 12705 PragmaStack<StringLiteral *> *Stack = nullptr; 12706 int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read; 12707 if (var->getType().isConstQualified()) 12708 Stack = &ConstSegStack; 12709 else if (!var->getInit()) { 12710 Stack = &BSSSegStack; 12711 SectionFlags |= ASTContext::PSF_Write; 12712 } else { 12713 Stack = &DataSegStack; 12714 SectionFlags |= ASTContext::PSF_Write; 12715 } 12716 if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) 12717 var->addAttr(SectionAttr::CreateImplicit( 12718 Context, Stack->CurrentValue->getString(), 12719 Stack->CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 12720 SectionAttr::Declspec_allocate)); 12721 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) 12722 if (UnifySection(SA->getName(), SectionFlags, var)) 12723 var->dropAttr<SectionAttr>(); 12724 12725 // Apply the init_seg attribute if this has an initializer. If the 12726 // initializer turns out to not be dynamic, we'll end up ignoring this 12727 // attribute. 12728 if (CurInitSeg && var->getInit()) 12729 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 12730 CurInitSegLoc, 12731 AttributeCommonInfo::AS_Pragma)); 12732 } 12733 12734 // All the following checks are C++ only. 12735 if (!getLangOpts().CPlusPlus) { 12736 // If this variable must be emitted, add it as an initializer for the 12737 // current module. 12738 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 12739 Context.addModuleInitializer(ModuleScopes.back().Module, var); 12740 return; 12741 } 12742 12743 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 12744 CheckCompleteDecompositionDeclaration(DD); 12745 12746 QualType type = var->getType(); 12747 if (type->isDependentType()) return; 12748 12749 if (var->hasAttr<BlocksAttr>()) 12750 getCurFunction()->addByrefBlockVar(var); 12751 12752 Expr *Init = var->getInit(); 12753 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 12754 QualType baseType = Context.getBaseElementType(type); 12755 12756 if (Init && !Init->isValueDependent()) { 12757 if (var->isConstexpr()) { 12758 SmallVector<PartialDiagnosticAt, 8> Notes; 12759 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 12760 SourceLocation DiagLoc = var->getLocation(); 12761 // If the note doesn't add any useful information other than a source 12762 // location, fold it into the primary diagnostic. 12763 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 12764 diag::note_invalid_subexpr_in_const_expr) { 12765 DiagLoc = Notes[0].first; 12766 Notes.clear(); 12767 } 12768 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 12769 << var << Init->getSourceRange(); 12770 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 12771 Diag(Notes[I].first, Notes[I].second); 12772 } 12773 } else if (var->mightBeUsableInConstantExpressions(Context)) { 12774 // Check whether the initializer of a const variable of integral or 12775 // enumeration type is an ICE now, since we can't tell whether it was 12776 // initialized by a constant expression if we check later. 12777 var->checkInitIsICE(); 12778 } 12779 12780 // Don't emit further diagnostics about constexpr globals since they 12781 // were just diagnosed. 12782 if (!var->isConstexpr() && GlobalStorage && var->hasAttr<ConstInitAttr>()) { 12783 // FIXME: Need strict checking in C++03 here. 12784 bool DiagErr = getLangOpts().CPlusPlus11 12785 ? !var->checkInitIsICE() : !checkConstInit(); 12786 if (DiagErr) { 12787 auto *Attr = var->getAttr<ConstInitAttr>(); 12788 Diag(var->getLocation(), diag::err_require_constant_init_failed) 12789 << Init->getSourceRange(); 12790 Diag(Attr->getLocation(), 12791 diag::note_declared_required_constant_init_here) 12792 << Attr->getRange() << Attr->isConstinit(); 12793 if (getLangOpts().CPlusPlus11) { 12794 APValue Value; 12795 SmallVector<PartialDiagnosticAt, 8> Notes; 12796 Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes); 12797 for (auto &it : Notes) 12798 Diag(it.first, it.second); 12799 } else { 12800 Diag(CacheCulprit->getExprLoc(), 12801 diag::note_invalid_subexpr_in_const_expr) 12802 << CacheCulprit->getSourceRange(); 12803 } 12804 } 12805 } 12806 else if (!var->isConstexpr() && IsGlobal && 12807 !getDiagnostics().isIgnored(diag::warn_global_constructor, 12808 var->getLocation())) { 12809 // Warn about globals which don't have a constant initializer. Don't 12810 // warn about globals with a non-trivial destructor because we already 12811 // warned about them. 12812 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 12813 if (!(RD && !RD->hasTrivialDestructor())) { 12814 if (!checkConstInit()) 12815 Diag(var->getLocation(), diag::warn_global_constructor) 12816 << Init->getSourceRange(); 12817 } 12818 } 12819 } 12820 12821 // Require the destructor. 12822 if (const RecordType *recordType = baseType->getAs<RecordType>()) 12823 FinalizeVarWithDestructor(var, recordType); 12824 12825 // If this variable must be emitted, add it as an initializer for the current 12826 // module. 12827 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 12828 Context.addModuleInitializer(ModuleScopes.back().Module, var); 12829 } 12830 12831 /// Determines if a variable's alignment is dependent. 12832 static bool hasDependentAlignment(VarDecl *VD) { 12833 if (VD->getType()->isDependentType()) 12834 return true; 12835 for (auto *I : VD->specific_attrs<AlignedAttr>()) 12836 if (I->isAlignmentDependent()) 12837 return true; 12838 return false; 12839 } 12840 12841 /// Check if VD needs to be dllexport/dllimport due to being in a 12842 /// dllexport/import function. 12843 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) { 12844 assert(VD->isStaticLocal()); 12845 12846 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 12847 12848 // Find outermost function when VD is in lambda function. 12849 while (FD && !getDLLAttr(FD) && 12850 !FD->hasAttr<DLLExportStaticLocalAttr>() && 12851 !FD->hasAttr<DLLImportStaticLocalAttr>()) { 12852 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod()); 12853 } 12854 12855 if (!FD) 12856 return; 12857 12858 // Static locals inherit dll attributes from their function. 12859 if (Attr *A = getDLLAttr(FD)) { 12860 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 12861 NewAttr->setInherited(true); 12862 VD->addAttr(NewAttr); 12863 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) { 12864 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A); 12865 NewAttr->setInherited(true); 12866 VD->addAttr(NewAttr); 12867 12868 // Export this function to enforce exporting this static variable even 12869 // if it is not used in this compilation unit. 12870 if (!FD->hasAttr<DLLExportAttr>()) 12871 FD->addAttr(NewAttr); 12872 12873 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) { 12874 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A); 12875 NewAttr->setInherited(true); 12876 VD->addAttr(NewAttr); 12877 } 12878 } 12879 12880 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 12881 /// any semantic actions necessary after any initializer has been attached. 12882 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 12883 // Note that we are no longer parsing the initializer for this declaration. 12884 ParsingInitForAutoVars.erase(ThisDecl); 12885 12886 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 12887 if (!VD) 12888 return; 12889 12890 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active 12891 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && 12892 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { 12893 if (PragmaClangBSSSection.Valid) 12894 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit( 12895 Context, PragmaClangBSSSection.SectionName, 12896 PragmaClangBSSSection.PragmaLocation, 12897 AttributeCommonInfo::AS_Pragma)); 12898 if (PragmaClangDataSection.Valid) 12899 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit( 12900 Context, PragmaClangDataSection.SectionName, 12901 PragmaClangDataSection.PragmaLocation, 12902 AttributeCommonInfo::AS_Pragma)); 12903 if (PragmaClangRodataSection.Valid) 12904 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit( 12905 Context, PragmaClangRodataSection.SectionName, 12906 PragmaClangRodataSection.PragmaLocation, 12907 AttributeCommonInfo::AS_Pragma)); 12908 if (PragmaClangRelroSection.Valid) 12909 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit( 12910 Context, PragmaClangRelroSection.SectionName, 12911 PragmaClangRelroSection.PragmaLocation, 12912 AttributeCommonInfo::AS_Pragma)); 12913 } 12914 12915 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 12916 for (auto *BD : DD->bindings()) { 12917 FinalizeDeclaration(BD); 12918 } 12919 } 12920 12921 checkAttributesAfterMerging(*this, *VD); 12922 12923 // Perform TLS alignment check here after attributes attached to the variable 12924 // which may affect the alignment have been processed. Only perform the check 12925 // if the target has a maximum TLS alignment (zero means no constraints). 12926 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 12927 // Protect the check so that it's not performed on dependent types and 12928 // dependent alignments (we can't determine the alignment in that case). 12929 if (VD->getTLSKind() && !hasDependentAlignment(VD) && 12930 !VD->isInvalidDecl()) { 12931 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 12932 if (Context.getDeclAlign(VD) > MaxAlignChars) { 12933 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 12934 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 12935 << (unsigned)MaxAlignChars.getQuantity(); 12936 } 12937 } 12938 } 12939 12940 if (VD->isStaticLocal()) { 12941 CheckStaticLocalForDllExport(VD); 12942 12943 if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { 12944 // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__ 12945 // function, only __shared__ variables or variables without any device 12946 // memory qualifiers may be declared with static storage class. 12947 // Note: It is unclear how a function-scope non-const static variable 12948 // without device memory qualifier is implemented, therefore only static 12949 // const variable without device memory qualifier is allowed. 12950 [&]() { 12951 if (!getLangOpts().CUDA) 12952 return; 12953 if (VD->hasAttr<CUDASharedAttr>()) 12954 return; 12955 if (VD->getType().isConstQualified() && 12956 !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>())) 12957 return; 12958 if (CUDADiagIfDeviceCode(VD->getLocation(), 12959 diag::err_device_static_local_var) 12960 << CurrentCUDATarget()) 12961 VD->setInvalidDecl(); 12962 }(); 12963 } 12964 } 12965 12966 // Perform check for initializers of device-side global variables. 12967 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 12968 // 7.5). We must also apply the same checks to all __shared__ 12969 // variables whether they are local or not. CUDA also allows 12970 // constant initializers for __constant__ and __device__ variables. 12971 if (getLangOpts().CUDA) 12972 checkAllowedCUDAInitializer(VD); 12973 12974 // Grab the dllimport or dllexport attribute off of the VarDecl. 12975 const InheritableAttr *DLLAttr = getDLLAttr(VD); 12976 12977 // Imported static data members cannot be defined out-of-line. 12978 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 12979 if (VD->isStaticDataMember() && VD->isOutOfLine() && 12980 VD->isThisDeclarationADefinition()) { 12981 // We allow definitions of dllimport class template static data members 12982 // with a warning. 12983 CXXRecordDecl *Context = 12984 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 12985 bool IsClassTemplateMember = 12986 isa<ClassTemplatePartialSpecializationDecl>(Context) || 12987 Context->getDescribedClassTemplate(); 12988 12989 Diag(VD->getLocation(), 12990 IsClassTemplateMember 12991 ? diag::warn_attribute_dllimport_static_field_definition 12992 : diag::err_attribute_dllimport_static_field_definition); 12993 Diag(IA->getLocation(), diag::note_attribute); 12994 if (!IsClassTemplateMember) 12995 VD->setInvalidDecl(); 12996 } 12997 } 12998 12999 // dllimport/dllexport variables cannot be thread local, their TLS index 13000 // isn't exported with the variable. 13001 if (DLLAttr && VD->getTLSKind()) { 13002 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 13003 if (F && getDLLAttr(F)) { 13004 assert(VD->isStaticLocal()); 13005 // But if this is a static local in a dlimport/dllexport function, the 13006 // function will never be inlined, which means the var would never be 13007 // imported, so having it marked import/export is safe. 13008 } else { 13009 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 13010 << DLLAttr; 13011 VD->setInvalidDecl(); 13012 } 13013 } 13014 13015 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 13016 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 13017 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 13018 VD->dropAttr<UsedAttr>(); 13019 } 13020 } 13021 13022 const DeclContext *DC = VD->getDeclContext(); 13023 // If there's a #pragma GCC visibility in scope, and this isn't a class 13024 // member, set the visibility of this variable. 13025 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 13026 AddPushedVisibilityAttribute(VD); 13027 13028 // FIXME: Warn on unused var template partial specializations. 13029 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 13030 MarkUnusedFileScopedDecl(VD); 13031 13032 // Now we have parsed the initializer and can update the table of magic 13033 // tag values. 13034 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 13035 !VD->getType()->isIntegralOrEnumerationType()) 13036 return; 13037 13038 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 13039 const Expr *MagicValueExpr = VD->getInit(); 13040 if (!MagicValueExpr) { 13041 continue; 13042 } 13043 llvm::APSInt MagicValueInt; 13044 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 13045 Diag(I->getRange().getBegin(), 13046 diag::err_type_tag_for_datatype_not_ice) 13047 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13048 continue; 13049 } 13050 if (MagicValueInt.getActiveBits() > 64) { 13051 Diag(I->getRange().getBegin(), 13052 diag::err_type_tag_for_datatype_too_large) 13053 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13054 continue; 13055 } 13056 uint64_t MagicValue = MagicValueInt.getZExtValue(); 13057 RegisterTypeTagForDatatype(I->getArgumentKind(), 13058 MagicValue, 13059 I->getMatchingCType(), 13060 I->getLayoutCompatible(), 13061 I->getMustBeNull()); 13062 } 13063 } 13064 13065 static bool hasDeducedAuto(DeclaratorDecl *DD) { 13066 auto *VD = dyn_cast<VarDecl>(DD); 13067 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 13068 } 13069 13070 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 13071 ArrayRef<Decl *> Group) { 13072 SmallVector<Decl*, 8> Decls; 13073 13074 if (DS.isTypeSpecOwned()) 13075 Decls.push_back(DS.getRepAsDecl()); 13076 13077 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 13078 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 13079 bool DiagnosedMultipleDecomps = false; 13080 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 13081 bool DiagnosedNonDeducedAuto = false; 13082 13083 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13084 if (Decl *D = Group[i]) { 13085 // For declarators, there are some additional syntactic-ish checks we need 13086 // to perform. 13087 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 13088 if (!FirstDeclaratorInGroup) 13089 FirstDeclaratorInGroup = DD; 13090 if (!FirstDecompDeclaratorInGroup) 13091 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 13092 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 13093 !hasDeducedAuto(DD)) 13094 FirstNonDeducedAutoInGroup = DD; 13095 13096 if (FirstDeclaratorInGroup != DD) { 13097 // A decomposition declaration cannot be combined with any other 13098 // declaration in the same group. 13099 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 13100 Diag(FirstDecompDeclaratorInGroup->getLocation(), 13101 diag::err_decomp_decl_not_alone) 13102 << FirstDeclaratorInGroup->getSourceRange() 13103 << DD->getSourceRange(); 13104 DiagnosedMultipleDecomps = true; 13105 } 13106 13107 // A declarator that uses 'auto' in any way other than to declare a 13108 // variable with a deduced type cannot be combined with any other 13109 // declarator in the same group. 13110 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 13111 Diag(FirstNonDeducedAutoInGroup->getLocation(), 13112 diag::err_auto_non_deduced_not_alone) 13113 << FirstNonDeducedAutoInGroup->getType() 13114 ->hasAutoForTrailingReturnType() 13115 << FirstDeclaratorInGroup->getSourceRange() 13116 << DD->getSourceRange(); 13117 DiagnosedNonDeducedAuto = true; 13118 } 13119 } 13120 } 13121 13122 Decls.push_back(D); 13123 } 13124 } 13125 13126 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 13127 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 13128 handleTagNumbering(Tag, S); 13129 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 13130 getLangOpts().CPlusPlus) 13131 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 13132 } 13133 } 13134 13135 return BuildDeclaratorGroup(Decls); 13136 } 13137 13138 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 13139 /// group, performing any necessary semantic checking. 13140 Sema::DeclGroupPtrTy 13141 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 13142 // C++14 [dcl.spec.auto]p7: (DR1347) 13143 // If the type that replaces the placeholder type is not the same in each 13144 // deduction, the program is ill-formed. 13145 if (Group.size() > 1) { 13146 QualType Deduced; 13147 VarDecl *DeducedDecl = nullptr; 13148 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13149 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 13150 if (!D || D->isInvalidDecl()) 13151 break; 13152 DeducedType *DT = D->getType()->getContainedDeducedType(); 13153 if (!DT || DT->getDeducedType().isNull()) 13154 continue; 13155 if (Deduced.isNull()) { 13156 Deduced = DT->getDeducedType(); 13157 DeducedDecl = D; 13158 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 13159 auto *AT = dyn_cast<AutoType>(DT); 13160 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 13161 diag::err_auto_different_deductions) 13162 << (AT ? (unsigned)AT->getKeyword() : 3) 13163 << Deduced << DeducedDecl->getDeclName() 13164 << DT->getDeducedType() << D->getDeclName() 13165 << DeducedDecl->getInit()->getSourceRange() 13166 << D->getInit()->getSourceRange(); 13167 D->setInvalidDecl(); 13168 break; 13169 } 13170 } 13171 } 13172 13173 ActOnDocumentableDecls(Group); 13174 13175 return DeclGroupPtrTy::make( 13176 DeclGroupRef::Create(Context, Group.data(), Group.size())); 13177 } 13178 13179 void Sema::ActOnDocumentableDecl(Decl *D) { 13180 ActOnDocumentableDecls(D); 13181 } 13182 13183 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 13184 // Don't parse the comment if Doxygen diagnostics are ignored. 13185 if (Group.empty() || !Group[0]) 13186 return; 13187 13188 if (Diags.isIgnored(diag::warn_doc_param_not_found, 13189 Group[0]->getLocation()) && 13190 Diags.isIgnored(diag::warn_unknown_comment_command_name, 13191 Group[0]->getLocation())) 13192 return; 13193 13194 if (Group.size() >= 2) { 13195 // This is a decl group. Normally it will contain only declarations 13196 // produced from declarator list. But in case we have any definitions or 13197 // additional declaration references: 13198 // 'typedef struct S {} S;' 13199 // 'typedef struct S *S;' 13200 // 'struct S *pS;' 13201 // FinalizeDeclaratorGroup adds these as separate declarations. 13202 Decl *MaybeTagDecl = Group[0]; 13203 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 13204 Group = Group.slice(1); 13205 } 13206 } 13207 13208 // FIMXE: We assume every Decl in the group is in the same file. 13209 // This is false when preprocessor constructs the group from decls in 13210 // different files (e. g. macros or #include). 13211 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor()); 13212 } 13213 13214 /// Common checks for a parameter-declaration that should apply to both function 13215 /// parameters and non-type template parameters. 13216 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) { 13217 // Check that there are no default arguments inside the type of this 13218 // parameter. 13219 if (getLangOpts().CPlusPlus) 13220 CheckExtraCXXDefaultArguments(D); 13221 13222 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 13223 if (D.getCXXScopeSpec().isSet()) { 13224 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 13225 << D.getCXXScopeSpec().getRange(); 13226 } 13227 13228 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a 13229 // simple identifier except [...irrelevant cases...]. 13230 switch (D.getName().getKind()) { 13231 case UnqualifiedIdKind::IK_Identifier: 13232 break; 13233 13234 case UnqualifiedIdKind::IK_OperatorFunctionId: 13235 case UnqualifiedIdKind::IK_ConversionFunctionId: 13236 case UnqualifiedIdKind::IK_LiteralOperatorId: 13237 case UnqualifiedIdKind::IK_ConstructorName: 13238 case UnqualifiedIdKind::IK_DestructorName: 13239 case UnqualifiedIdKind::IK_ImplicitSelfParam: 13240 case UnqualifiedIdKind::IK_DeductionGuideName: 13241 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 13242 << GetNameForDeclarator(D).getName(); 13243 break; 13244 13245 case UnqualifiedIdKind::IK_TemplateId: 13246 case UnqualifiedIdKind::IK_ConstructorTemplateId: 13247 // GetNameForDeclarator would not produce a useful name in this case. 13248 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id); 13249 break; 13250 } 13251 } 13252 13253 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 13254 /// to introduce parameters into function prototype scope. 13255 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 13256 const DeclSpec &DS = D.getDeclSpec(); 13257 13258 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 13259 13260 // C++03 [dcl.stc]p2 also permits 'auto'. 13261 StorageClass SC = SC_None; 13262 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 13263 SC = SC_Register; 13264 // In C++11, the 'register' storage class specifier is deprecated. 13265 // In C++17, it is not allowed, but we tolerate it as an extension. 13266 if (getLangOpts().CPlusPlus11) { 13267 Diag(DS.getStorageClassSpecLoc(), 13268 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 13269 : diag::warn_deprecated_register) 13270 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 13271 } 13272 } else if (getLangOpts().CPlusPlus && 13273 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 13274 SC = SC_Auto; 13275 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 13276 Diag(DS.getStorageClassSpecLoc(), 13277 diag::err_invalid_storage_class_in_func_decl); 13278 D.getMutableDeclSpec().ClearStorageClassSpecs(); 13279 } 13280 13281 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 13282 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 13283 << DeclSpec::getSpecifierName(TSCS); 13284 if (DS.isInlineSpecified()) 13285 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 13286 << getLangOpts().CPlusPlus17; 13287 if (DS.hasConstexprSpecifier()) 13288 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 13289 << 0 << D.getDeclSpec().getConstexprSpecifier(); 13290 13291 DiagnoseFunctionSpecifiers(DS); 13292 13293 CheckFunctionOrTemplateParamDeclarator(S, D); 13294 13295 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13296 QualType parmDeclType = TInfo->getType(); 13297 13298 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 13299 IdentifierInfo *II = D.getIdentifier(); 13300 if (II) { 13301 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 13302 ForVisibleRedeclaration); 13303 LookupName(R, S); 13304 if (R.isSingleResult()) { 13305 NamedDecl *PrevDecl = R.getFoundDecl(); 13306 if (PrevDecl->isTemplateParameter()) { 13307 // Maybe we will complain about the shadowed template parameter. 13308 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13309 // Just pretend that we didn't see the previous declaration. 13310 PrevDecl = nullptr; 13311 } else if (S->isDeclScope(PrevDecl)) { 13312 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 13313 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 13314 13315 // Recover by removing the name 13316 II = nullptr; 13317 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 13318 D.setInvalidType(true); 13319 } 13320 } 13321 } 13322 13323 // Temporarily put parameter variables in the translation unit, not 13324 // the enclosing context. This prevents them from accidentally 13325 // looking like class members in C++. 13326 ParmVarDecl *New = 13327 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(), 13328 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC); 13329 13330 if (D.isInvalidType()) 13331 New->setInvalidDecl(); 13332 13333 assert(S->isFunctionPrototypeScope()); 13334 assert(S->getFunctionPrototypeDepth() >= 1); 13335 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 13336 S->getNextFunctionPrototypeIndex()); 13337 13338 // Add the parameter declaration into this scope. 13339 S->AddDecl(New); 13340 if (II) 13341 IdResolver.AddDecl(New); 13342 13343 ProcessDeclAttributes(S, New, D); 13344 13345 if (D.getDeclSpec().isModulePrivateSpecified()) 13346 Diag(New->getLocation(), diag::err_module_private_local) 13347 << 1 << New->getDeclName() 13348 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 13349 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 13350 13351 if (New->hasAttr<BlocksAttr>()) { 13352 Diag(New->getLocation(), diag::err_block_on_nonlocal); 13353 } 13354 13355 if (getLangOpts().OpenCL) 13356 deduceOpenCLAddressSpace(New); 13357 13358 return New; 13359 } 13360 13361 /// Synthesizes a variable for a parameter arising from a 13362 /// typedef. 13363 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 13364 SourceLocation Loc, 13365 QualType T) { 13366 /* FIXME: setting StartLoc == Loc. 13367 Would it be worth to modify callers so as to provide proper source 13368 location for the unnamed parameters, embedding the parameter's type? */ 13369 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 13370 T, Context.getTrivialTypeSourceInfo(T, Loc), 13371 SC_None, nullptr); 13372 Param->setImplicit(); 13373 return Param; 13374 } 13375 13376 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 13377 // Don't diagnose unused-parameter errors in template instantiations; we 13378 // will already have done so in the template itself. 13379 if (inTemplateInstantiation()) 13380 return; 13381 13382 for (const ParmVarDecl *Parameter : Parameters) { 13383 if (!Parameter->isReferenced() && Parameter->getDeclName() && 13384 !Parameter->hasAttr<UnusedAttr>()) { 13385 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 13386 << Parameter->getDeclName(); 13387 } 13388 } 13389 } 13390 13391 void Sema::DiagnoseSizeOfParametersAndReturnValue( 13392 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 13393 if (LangOpts.NumLargeByValueCopy == 0) // No check. 13394 return; 13395 13396 // Warn if the return value is pass-by-value and larger than the specified 13397 // threshold. 13398 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 13399 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 13400 if (Size > LangOpts.NumLargeByValueCopy) 13401 Diag(D->getLocation(), diag::warn_return_value_size) 13402 << D->getDeclName() << Size; 13403 } 13404 13405 // Warn if any parameter is pass-by-value and larger than the specified 13406 // threshold. 13407 for (const ParmVarDecl *Parameter : Parameters) { 13408 QualType T = Parameter->getType(); 13409 if (T->isDependentType() || !T.isPODType(Context)) 13410 continue; 13411 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 13412 if (Size > LangOpts.NumLargeByValueCopy) 13413 Diag(Parameter->getLocation(), diag::warn_parameter_size) 13414 << Parameter->getDeclName() << Size; 13415 } 13416 } 13417 13418 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 13419 SourceLocation NameLoc, IdentifierInfo *Name, 13420 QualType T, TypeSourceInfo *TSInfo, 13421 StorageClass SC) { 13422 // In ARC, infer a lifetime qualifier for appropriate parameter types. 13423 if (getLangOpts().ObjCAutoRefCount && 13424 T.getObjCLifetime() == Qualifiers::OCL_None && 13425 T->isObjCLifetimeType()) { 13426 13427 Qualifiers::ObjCLifetime lifetime; 13428 13429 // Special cases for arrays: 13430 // - if it's const, use __unsafe_unretained 13431 // - otherwise, it's an error 13432 if (T->isArrayType()) { 13433 if (!T.isConstQualified()) { 13434 if (DelayedDiagnostics.shouldDelayDiagnostics()) 13435 DelayedDiagnostics.add( 13436 sema::DelayedDiagnostic::makeForbiddenType( 13437 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 13438 else 13439 Diag(NameLoc, diag::err_arc_array_param_no_ownership) 13440 << TSInfo->getTypeLoc().getSourceRange(); 13441 } 13442 lifetime = Qualifiers::OCL_ExplicitNone; 13443 } else { 13444 lifetime = T->getObjCARCImplicitLifetime(); 13445 } 13446 T = Context.getLifetimeQualifiedType(T, lifetime); 13447 } 13448 13449 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 13450 Context.getAdjustedParameterType(T), 13451 TSInfo, SC, nullptr); 13452 13453 // Make a note if we created a new pack in the scope of a lambda, so that 13454 // we know that references to that pack must also be expanded within the 13455 // lambda scope. 13456 if (New->isParameterPack()) 13457 if (auto *LSI = getEnclosingLambda()) 13458 LSI->LocalPacks.push_back(New); 13459 13460 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() || 13461 New->getType().hasNonTrivialToPrimitiveCopyCUnion()) 13462 checkNonTrivialCUnion(New->getType(), New->getLocation(), 13463 NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy); 13464 13465 // Parameters can not be abstract class types. 13466 // For record types, this is done by the AbstractClassUsageDiagnoser once 13467 // the class has been completely parsed. 13468 if (!CurContext->isRecord() && 13469 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 13470 AbstractParamType)) 13471 New->setInvalidDecl(); 13472 13473 // Parameter declarators cannot be interface types. All ObjC objects are 13474 // passed by reference. 13475 if (T->isObjCObjectType()) { 13476 SourceLocation TypeEndLoc = 13477 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc()); 13478 Diag(NameLoc, 13479 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 13480 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 13481 T = Context.getObjCObjectPointerType(T); 13482 New->setType(T); 13483 } 13484 13485 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 13486 // duration shall not be qualified by an address-space qualifier." 13487 // Since all parameters have automatic store duration, they can not have 13488 // an address space. 13489 if (T.getAddressSpace() != LangAS::Default && 13490 // OpenCL allows function arguments declared to be an array of a type 13491 // to be qualified with an address space. 13492 !(getLangOpts().OpenCL && 13493 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) { 13494 Diag(NameLoc, diag::err_arg_with_address_space); 13495 New->setInvalidDecl(); 13496 } 13497 13498 return New; 13499 } 13500 13501 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 13502 SourceLocation LocAfterDecls) { 13503 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 13504 13505 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 13506 // for a K&R function. 13507 if (!FTI.hasPrototype) { 13508 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 13509 --i; 13510 if (FTI.Params[i].Param == nullptr) { 13511 SmallString<256> Code; 13512 llvm::raw_svector_ostream(Code) 13513 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 13514 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 13515 << FTI.Params[i].Ident 13516 << FixItHint::CreateInsertion(LocAfterDecls, Code); 13517 13518 // Implicitly declare the argument as type 'int' for lack of a better 13519 // type. 13520 AttributeFactory attrs; 13521 DeclSpec DS(attrs); 13522 const char* PrevSpec; // unused 13523 unsigned DiagID; // unused 13524 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 13525 DiagID, Context.getPrintingPolicy()); 13526 // Use the identifier location for the type source range. 13527 DS.SetRangeStart(FTI.Params[i].IdentLoc); 13528 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 13529 Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext); 13530 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 13531 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 13532 } 13533 } 13534 } 13535 } 13536 13537 Decl * 13538 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 13539 MultiTemplateParamsArg TemplateParameterLists, 13540 SkipBodyInfo *SkipBody) { 13541 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 13542 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 13543 Scope *ParentScope = FnBodyScope->getParent(); 13544 13545 D.setFunctionDefinitionKind(FDK_Definition); 13546 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 13547 return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 13548 } 13549 13550 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 13551 Consumer.HandleInlineFunctionDefinition(D); 13552 } 13553 13554 static bool 13555 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 13556 const FunctionDecl *&PossiblePrototype) { 13557 // Don't warn about invalid declarations. 13558 if (FD->isInvalidDecl()) 13559 return false; 13560 13561 // Or declarations that aren't global. 13562 if (!FD->isGlobal()) 13563 return false; 13564 13565 // Don't warn about C++ member functions. 13566 if (isa<CXXMethodDecl>(FD)) 13567 return false; 13568 13569 // Don't warn about 'main'. 13570 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext())) 13571 if (IdentifierInfo *II = FD->getIdentifier()) 13572 if (II->isStr("main")) 13573 return false; 13574 13575 // Don't warn about inline functions. 13576 if (FD->isInlined()) 13577 return false; 13578 13579 // Don't warn about function templates. 13580 if (FD->getDescribedFunctionTemplate()) 13581 return false; 13582 13583 // Don't warn about function template specializations. 13584 if (FD->isFunctionTemplateSpecialization()) 13585 return false; 13586 13587 // Don't warn for OpenCL kernels. 13588 if (FD->hasAttr<OpenCLKernelAttr>()) 13589 return false; 13590 13591 // Don't warn on explicitly deleted functions. 13592 if (FD->isDeleted()) 13593 return false; 13594 13595 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 13596 Prev; Prev = Prev->getPreviousDecl()) { 13597 // Ignore any declarations that occur in function or method 13598 // scope, because they aren't visible from the header. 13599 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 13600 continue; 13601 13602 PossiblePrototype = Prev; 13603 return Prev->getType()->isFunctionNoProtoType(); 13604 } 13605 13606 return true; 13607 } 13608 13609 void 13610 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 13611 const FunctionDecl *EffectiveDefinition, 13612 SkipBodyInfo *SkipBody) { 13613 const FunctionDecl *Definition = EffectiveDefinition; 13614 if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) { 13615 // If this is a friend function defined in a class template, it does not 13616 // have a body until it is used, nevertheless it is a definition, see 13617 // [temp.inst]p2: 13618 // 13619 // ... for the purpose of determining whether an instantiated redeclaration 13620 // is valid according to [basic.def.odr] and [class.mem], a declaration that 13621 // corresponds to a definition in the template is considered to be a 13622 // definition. 13623 // 13624 // The following code must produce redefinition error: 13625 // 13626 // template<typename T> struct C20 { friend void func_20() {} }; 13627 // C20<int> c20i; 13628 // void func_20() {} 13629 // 13630 for (auto I : FD->redecls()) { 13631 if (I != FD && !I->isInvalidDecl() && 13632 I->getFriendObjectKind() != Decl::FOK_None) { 13633 if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) { 13634 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { 13635 // A merged copy of the same function, instantiated as a member of 13636 // the same class, is OK. 13637 if (declaresSameEntity(OrigFD, Original) && 13638 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()), 13639 cast<Decl>(FD->getLexicalDeclContext()))) 13640 continue; 13641 } 13642 13643 if (Original->isThisDeclarationADefinition()) { 13644 Definition = I; 13645 break; 13646 } 13647 } 13648 } 13649 } 13650 } 13651 13652 if (!Definition) 13653 // Similar to friend functions a friend function template may be a 13654 // definition and do not have a body if it is instantiated in a class 13655 // template. 13656 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) { 13657 for (auto I : FTD->redecls()) { 13658 auto D = cast<FunctionTemplateDecl>(I); 13659 if (D != FTD) { 13660 assert(!D->isThisDeclarationADefinition() && 13661 "More than one definition in redeclaration chain"); 13662 if (D->getFriendObjectKind() != Decl::FOK_None) 13663 if (FunctionTemplateDecl *FT = 13664 D->getInstantiatedFromMemberTemplate()) { 13665 if (FT->isThisDeclarationADefinition()) { 13666 Definition = D->getTemplatedDecl(); 13667 break; 13668 } 13669 } 13670 } 13671 } 13672 } 13673 13674 if (!Definition) 13675 return; 13676 13677 if (canRedefineFunction(Definition, getLangOpts())) 13678 return; 13679 13680 // Don't emit an error when this is redefinition of a typo-corrected 13681 // definition. 13682 if (TypoCorrectedFunctionDefinitions.count(Definition)) 13683 return; 13684 13685 // If we don't have a visible definition of the function, and it's inline or 13686 // a template, skip the new definition. 13687 if (SkipBody && !hasVisibleDefinition(Definition) && 13688 (Definition->getFormalLinkage() == InternalLinkage || 13689 Definition->isInlined() || 13690 Definition->getDescribedFunctionTemplate() || 13691 Definition->getNumTemplateParameterLists())) { 13692 SkipBody->ShouldSkip = true; 13693 SkipBody->Previous = const_cast<FunctionDecl*>(Definition); 13694 if (auto *TD = Definition->getDescribedFunctionTemplate()) 13695 makeMergedDefinitionVisible(TD); 13696 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 13697 return; 13698 } 13699 13700 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 13701 Definition->getStorageClass() == SC_Extern) 13702 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 13703 << FD->getDeclName() << getLangOpts().CPlusPlus; 13704 else 13705 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 13706 13707 Diag(Definition->getLocation(), diag::note_previous_definition); 13708 FD->setInvalidDecl(); 13709 } 13710 13711 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 13712 Sema &S) { 13713 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 13714 13715 LambdaScopeInfo *LSI = S.PushLambdaScope(); 13716 LSI->CallOperator = CallOperator; 13717 LSI->Lambda = LambdaClass; 13718 LSI->ReturnType = CallOperator->getReturnType(); 13719 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 13720 13721 if (LCD == LCD_None) 13722 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 13723 else if (LCD == LCD_ByCopy) 13724 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 13725 else if (LCD == LCD_ByRef) 13726 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 13727 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 13728 13729 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 13730 LSI->Mutable = !CallOperator->isConst(); 13731 13732 // Add the captures to the LSI so they can be noted as already 13733 // captured within tryCaptureVar. 13734 auto I = LambdaClass->field_begin(); 13735 for (const auto &C : LambdaClass->captures()) { 13736 if (C.capturesVariable()) { 13737 VarDecl *VD = C.getCapturedVar(); 13738 if (VD->isInitCapture()) 13739 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 13740 QualType CaptureType = VD->getType(); 13741 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 13742 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 13743 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 13744 /*EllipsisLoc*/C.isPackExpansion() 13745 ? C.getEllipsisLoc() : SourceLocation(), 13746 CaptureType, /*Invalid*/false); 13747 13748 } else if (C.capturesThis()) { 13749 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(), 13750 C.getCaptureKind() == LCK_StarThis); 13751 } else { 13752 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(), 13753 I->getType()); 13754 } 13755 ++I; 13756 } 13757 } 13758 13759 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 13760 SkipBodyInfo *SkipBody) { 13761 if (!D) { 13762 // Parsing the function declaration failed in some way. Push on a fake scope 13763 // anyway so we can try to parse the function body. 13764 PushFunctionScope(); 13765 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 13766 return D; 13767 } 13768 13769 FunctionDecl *FD = nullptr; 13770 13771 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 13772 FD = FunTmpl->getTemplatedDecl(); 13773 else 13774 FD = cast<FunctionDecl>(D); 13775 13776 // Do not push if it is a lambda because one is already pushed when building 13777 // the lambda in ActOnStartOfLambdaDefinition(). 13778 if (!isLambdaCallOperator(FD)) 13779 PushExpressionEvaluationContext( 13780 FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated 13781 : ExprEvalContexts.back().Context); 13782 13783 // Check for defining attributes before the check for redefinition. 13784 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 13785 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 13786 FD->dropAttr<AliasAttr>(); 13787 FD->setInvalidDecl(); 13788 } 13789 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 13790 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 13791 FD->dropAttr<IFuncAttr>(); 13792 FD->setInvalidDecl(); 13793 } 13794 13795 // See if this is a redefinition. If 'will have body' is already set, then 13796 // these checks were already performed when it was set. 13797 if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) { 13798 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 13799 13800 // If we're skipping the body, we're done. Don't enter the scope. 13801 if (SkipBody && SkipBody->ShouldSkip) 13802 return D; 13803 } 13804 13805 // Mark this function as "will have a body eventually". This lets users to 13806 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 13807 // this function. 13808 FD->setWillHaveBody(); 13809 13810 // If we are instantiating a generic lambda call operator, push 13811 // a LambdaScopeInfo onto the function stack. But use the information 13812 // that's already been calculated (ActOnLambdaExpr) to prime the current 13813 // LambdaScopeInfo. 13814 // When the template operator is being specialized, the LambdaScopeInfo, 13815 // has to be properly restored so that tryCaptureVariable doesn't try 13816 // and capture any new variables. In addition when calculating potential 13817 // captures during transformation of nested lambdas, it is necessary to 13818 // have the LSI properly restored. 13819 if (isGenericLambdaCallOperatorSpecialization(FD)) { 13820 assert(inTemplateInstantiation() && 13821 "There should be an active template instantiation on the stack " 13822 "when instantiating a generic lambda!"); 13823 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 13824 } else { 13825 // Enter a new function scope 13826 PushFunctionScope(); 13827 } 13828 13829 // Builtin functions cannot be defined. 13830 if (unsigned BuiltinID = FD->getBuiltinID()) { 13831 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 13832 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 13833 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 13834 FD->setInvalidDecl(); 13835 } 13836 } 13837 13838 // The return type of a function definition must be complete 13839 // (C99 6.9.1p3, C++ [dcl.fct]p6). 13840 QualType ResultType = FD->getReturnType(); 13841 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 13842 !FD->isInvalidDecl() && 13843 RequireCompleteType(FD->getLocation(), ResultType, 13844 diag::err_func_def_incomplete_result)) 13845 FD->setInvalidDecl(); 13846 13847 if (FnBodyScope) 13848 PushDeclContext(FnBodyScope, FD); 13849 13850 // Check the validity of our function parameters 13851 CheckParmsForFunctionDef(FD->parameters(), 13852 /*CheckParameterNames=*/true); 13853 13854 // Add non-parameter declarations already in the function to the current 13855 // scope. 13856 if (FnBodyScope) { 13857 for (Decl *NPD : FD->decls()) { 13858 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 13859 if (!NonParmDecl) 13860 continue; 13861 assert(!isa<ParmVarDecl>(NonParmDecl) && 13862 "parameters should not be in newly created FD yet"); 13863 13864 // If the decl has a name, make it accessible in the current scope. 13865 if (NonParmDecl->getDeclName()) 13866 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 13867 13868 // Similarly, dive into enums and fish their constants out, making them 13869 // accessible in this scope. 13870 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 13871 for (auto *EI : ED->enumerators()) 13872 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 13873 } 13874 } 13875 } 13876 13877 // Introduce our parameters into the function scope 13878 for (auto Param : FD->parameters()) { 13879 Param->setOwningFunction(FD); 13880 13881 // If this has an identifier, add it to the scope stack. 13882 if (Param->getIdentifier() && FnBodyScope) { 13883 CheckShadow(FnBodyScope, Param); 13884 13885 PushOnScopeChains(Param, FnBodyScope); 13886 } 13887 } 13888 13889 // Ensure that the function's exception specification is instantiated. 13890 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 13891 ResolveExceptionSpec(D->getLocation(), FPT); 13892 13893 // dllimport cannot be applied to non-inline function definitions. 13894 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 13895 !FD->isTemplateInstantiation()) { 13896 assert(!FD->hasAttr<DLLExportAttr>()); 13897 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 13898 FD->setInvalidDecl(); 13899 return D; 13900 } 13901 // We want to attach documentation to original Decl (which might be 13902 // a function template). 13903 ActOnDocumentableDecl(D); 13904 if (getCurLexicalContext()->isObjCContainer() && 13905 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 13906 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 13907 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 13908 13909 return D; 13910 } 13911 13912 /// Given the set of return statements within a function body, 13913 /// compute the variables that are subject to the named return value 13914 /// optimization. 13915 /// 13916 /// Each of the variables that is subject to the named return value 13917 /// optimization will be marked as NRVO variables in the AST, and any 13918 /// return statement that has a marked NRVO variable as its NRVO candidate can 13919 /// use the named return value optimization. 13920 /// 13921 /// This function applies a very simplistic algorithm for NRVO: if every return 13922 /// statement in the scope of a variable has the same NRVO candidate, that 13923 /// candidate is an NRVO variable. 13924 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 13925 ReturnStmt **Returns = Scope->Returns.data(); 13926 13927 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 13928 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 13929 if (!NRVOCandidate->isNRVOVariable()) 13930 Returns[I]->setNRVOCandidate(nullptr); 13931 } 13932 } 13933 } 13934 13935 bool Sema::canDelayFunctionBody(const Declarator &D) { 13936 // We can't delay parsing the body of a constexpr function template (yet). 13937 if (D.getDeclSpec().hasConstexprSpecifier()) 13938 return false; 13939 13940 // We can't delay parsing the body of a function template with a deduced 13941 // return type (yet). 13942 if (D.getDeclSpec().hasAutoTypeSpec()) { 13943 // If the placeholder introduces a non-deduced trailing return type, 13944 // we can still delay parsing it. 13945 if (D.getNumTypeObjects()) { 13946 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 13947 if (Outer.Kind == DeclaratorChunk::Function && 13948 Outer.Fun.hasTrailingReturnType()) { 13949 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 13950 return Ty.isNull() || !Ty->isUndeducedType(); 13951 } 13952 } 13953 return false; 13954 } 13955 13956 return true; 13957 } 13958 13959 bool Sema::canSkipFunctionBody(Decl *D) { 13960 // We cannot skip the body of a function (or function template) which is 13961 // constexpr, since we may need to evaluate its body in order to parse the 13962 // rest of the file. 13963 // We cannot skip the body of a function with an undeduced return type, 13964 // because any callers of that function need to know the type. 13965 if (const FunctionDecl *FD = D->getAsFunction()) { 13966 if (FD->isConstexpr()) 13967 return false; 13968 // We can't simply call Type::isUndeducedType here, because inside template 13969 // auto can be deduced to a dependent type, which is not considered 13970 // "undeduced". 13971 if (FD->getReturnType()->getContainedDeducedType()) 13972 return false; 13973 } 13974 return Consumer.shouldSkipFunctionBody(D); 13975 } 13976 13977 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 13978 if (!Decl) 13979 return nullptr; 13980 if (FunctionDecl *FD = Decl->getAsFunction()) 13981 FD->setHasSkippedBody(); 13982 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) 13983 MD->setHasSkippedBody(); 13984 return Decl; 13985 } 13986 13987 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 13988 return ActOnFinishFunctionBody(D, BodyArg, false); 13989 } 13990 13991 /// RAII object that pops an ExpressionEvaluationContext when exiting a function 13992 /// body. 13993 class ExitFunctionBodyRAII { 13994 public: 13995 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {} 13996 ~ExitFunctionBodyRAII() { 13997 if (!IsLambda) 13998 S.PopExpressionEvaluationContext(); 13999 } 14000 14001 private: 14002 Sema &S; 14003 bool IsLambda = false; 14004 }; 14005 14006 static void diagnoseImplicitlyRetainedSelf(Sema &S) { 14007 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo; 14008 14009 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) { 14010 if (EscapeInfo.count(BD)) 14011 return EscapeInfo[BD]; 14012 14013 bool R = false; 14014 const BlockDecl *CurBD = BD; 14015 14016 do { 14017 R = !CurBD->doesNotEscape(); 14018 if (R) 14019 break; 14020 CurBD = CurBD->getParent()->getInnermostBlockDecl(); 14021 } while (CurBD); 14022 14023 return EscapeInfo[BD] = R; 14024 }; 14025 14026 // If the location where 'self' is implicitly retained is inside a escaping 14027 // block, emit a diagnostic. 14028 for (const std::pair<SourceLocation, const BlockDecl *> &P : 14029 S.ImplicitlyRetainedSelfLocs) 14030 if (IsOrNestedInEscapingBlock(P.second)) 14031 S.Diag(P.first, diag::warn_implicitly_retains_self) 14032 << FixItHint::CreateInsertion(P.first, "self->"); 14033 } 14034 14035 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 14036 bool IsInstantiation) { 14037 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 14038 14039 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 14040 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 14041 14042 if (getLangOpts().Coroutines && getCurFunction()->isCoroutine()) 14043 CheckCompletedCoroutineBody(FD, Body); 14044 14045 // Do not call PopExpressionEvaluationContext() if it is a lambda because one 14046 // is already popped when finishing the lambda in BuildLambdaExpr(). This is 14047 // meant to pop the context added in ActOnStartOfFunctionDef(). 14048 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD)); 14049 14050 if (FD) { 14051 FD->setBody(Body); 14052 FD->setWillHaveBody(false); 14053 14054 if (getLangOpts().CPlusPlus14) { 14055 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 14056 FD->getReturnType()->isUndeducedType()) { 14057 // If the function has a deduced result type but contains no 'return' 14058 // statements, the result type as written must be exactly 'auto', and 14059 // the deduced result type is 'void'. 14060 if (!FD->getReturnType()->getAs<AutoType>()) { 14061 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 14062 << FD->getReturnType(); 14063 FD->setInvalidDecl(); 14064 } else { 14065 // Substitute 'void' for the 'auto' in the type. 14066 TypeLoc ResultType = getReturnTypeLoc(FD); 14067 Context.adjustDeducedFunctionResultType( 14068 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 14069 } 14070 } 14071 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 14072 // In C++11, we don't use 'auto' deduction rules for lambda call 14073 // operators because we don't support return type deduction. 14074 auto *LSI = getCurLambda(); 14075 if (LSI->HasImplicitReturnType) { 14076 deduceClosureReturnType(*LSI); 14077 14078 // C++11 [expr.prim.lambda]p4: 14079 // [...] if there are no return statements in the compound-statement 14080 // [the deduced type is] the type void 14081 QualType RetType = 14082 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 14083 14084 // Update the return type to the deduced type. 14085 const auto *Proto = FD->getType()->castAs<FunctionProtoType>(); 14086 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 14087 Proto->getExtProtoInfo())); 14088 } 14089 } 14090 14091 // If the function implicitly returns zero (like 'main') or is naked, 14092 // don't complain about missing return statements. 14093 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 14094 WP.disableCheckFallThrough(); 14095 14096 // MSVC permits the use of pure specifier (=0) on function definition, 14097 // defined at class scope, warn about this non-standard construct. 14098 if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine()) 14099 Diag(FD->getLocation(), diag::ext_pure_function_definition); 14100 14101 if (!FD->isInvalidDecl()) { 14102 // Don't diagnose unused parameters of defaulted or deleted functions. 14103 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody()) 14104 DiagnoseUnusedParameters(FD->parameters()); 14105 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 14106 FD->getReturnType(), FD); 14107 14108 // If this is a structor, we need a vtable. 14109 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 14110 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 14111 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 14112 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 14113 14114 // Try to apply the named return value optimization. We have to check 14115 // if we can do this here because lambdas keep return statements around 14116 // to deduce an implicit return type. 14117 if (FD->getReturnType()->isRecordType() && 14118 (!getLangOpts().CPlusPlus || !FD->isDependentContext())) 14119 computeNRVO(Body, getCurFunction()); 14120 } 14121 14122 // GNU warning -Wmissing-prototypes: 14123 // Warn if a global function is defined without a previous 14124 // prototype declaration. This warning is issued even if the 14125 // definition itself provides a prototype. The aim is to detect 14126 // global functions that fail to be declared in header files. 14127 const FunctionDecl *PossiblePrototype = nullptr; 14128 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) { 14129 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 14130 14131 if (PossiblePrototype) { 14132 // We found a declaration that is not a prototype, 14133 // but that could be a zero-parameter prototype 14134 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) { 14135 TypeLoc TL = TI->getTypeLoc(); 14136 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 14137 Diag(PossiblePrototype->getLocation(), 14138 diag::note_declaration_not_a_prototype) 14139 << (FD->getNumParams() != 0) 14140 << (FD->getNumParams() == 0 14141 ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void") 14142 : FixItHint{}); 14143 } 14144 } else { 14145 Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 14146 << /* function */ 1 14147 << (FD->getStorageClass() == SC_None 14148 ? FixItHint::CreateInsertion(FD->getTypeSpecStartLoc(), 14149 "static ") 14150 : FixItHint{}); 14151 } 14152 14153 // GNU warning -Wstrict-prototypes 14154 // Warn if K&R function is defined without a previous declaration. 14155 // This warning is issued only if the definition itself does not provide 14156 // a prototype. Only K&R definitions do not provide a prototype. 14157 if (!FD->hasWrittenPrototype()) { 14158 TypeSourceInfo *TI = FD->getTypeSourceInfo(); 14159 TypeLoc TL = TI->getTypeLoc(); 14160 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); 14161 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2; 14162 } 14163 } 14164 14165 // Warn on CPUDispatch with an actual body. 14166 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body) 14167 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body)) 14168 if (!CmpndBody->body_empty()) 14169 Diag(CmpndBody->body_front()->getBeginLoc(), 14170 diag::warn_dispatch_body_ignored); 14171 14172 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 14173 const CXXMethodDecl *KeyFunction; 14174 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 14175 MD->isVirtual() && 14176 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 14177 MD == KeyFunction->getCanonicalDecl()) { 14178 // Update the key-function state if necessary for this ABI. 14179 if (FD->isInlined() && 14180 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 14181 Context.setNonKeyFunction(MD); 14182 14183 // If the newly-chosen key function is already defined, then we 14184 // need to mark the vtable as used retroactively. 14185 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 14186 const FunctionDecl *Definition; 14187 if (KeyFunction && KeyFunction->isDefined(Definition)) 14188 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 14189 } else { 14190 // We just defined they key function; mark the vtable as used. 14191 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 14192 } 14193 } 14194 } 14195 14196 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 14197 "Function parsing confused"); 14198 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 14199 assert(MD == getCurMethodDecl() && "Method parsing confused"); 14200 MD->setBody(Body); 14201 if (!MD->isInvalidDecl()) { 14202 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 14203 MD->getReturnType(), MD); 14204 14205 if (Body) 14206 computeNRVO(Body, getCurFunction()); 14207 } 14208 if (getCurFunction()->ObjCShouldCallSuper) { 14209 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call) 14210 << MD->getSelector().getAsString(); 14211 getCurFunction()->ObjCShouldCallSuper = false; 14212 } 14213 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 14214 const ObjCMethodDecl *InitMethod = nullptr; 14215 bool isDesignated = 14216 MD->isDesignatedInitializerForTheInterface(&InitMethod); 14217 assert(isDesignated && InitMethod); 14218 (void)isDesignated; 14219 14220 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 14221 auto IFace = MD->getClassInterface(); 14222 if (!IFace) 14223 return false; 14224 auto SuperD = IFace->getSuperClass(); 14225 if (!SuperD) 14226 return false; 14227 return SuperD->getIdentifier() == 14228 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 14229 }; 14230 // Don't issue this warning for unavailable inits or direct subclasses 14231 // of NSObject. 14232 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 14233 Diag(MD->getLocation(), 14234 diag::warn_objc_designated_init_missing_super_call); 14235 Diag(InitMethod->getLocation(), 14236 diag::note_objc_designated_init_marked_here); 14237 } 14238 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 14239 } 14240 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 14241 // Don't issue this warning for unavaialable inits. 14242 if (!MD->isUnavailable()) 14243 Diag(MD->getLocation(), 14244 diag::warn_objc_secondary_init_missing_init_call); 14245 getCurFunction()->ObjCWarnForNoInitDelegation = false; 14246 } 14247 14248 diagnoseImplicitlyRetainedSelf(*this); 14249 } else { 14250 // Parsing the function declaration failed in some way. Pop the fake scope 14251 // we pushed on. 14252 PopFunctionScopeInfo(ActivePolicy, dcl); 14253 return nullptr; 14254 } 14255 14256 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 14257 DiagnoseUnguardedAvailabilityViolations(dcl); 14258 14259 assert(!getCurFunction()->ObjCShouldCallSuper && 14260 "This should only be set for ObjC methods, which should have been " 14261 "handled in the block above."); 14262 14263 // Verify and clean out per-function state. 14264 if (Body && (!FD || !FD->isDefaulted())) { 14265 // C++ constructors that have function-try-blocks can't have return 14266 // statements in the handlers of that block. (C++ [except.handle]p14) 14267 // Verify this. 14268 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 14269 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 14270 14271 // Verify that gotos and switch cases don't jump into scopes illegally. 14272 if (getCurFunction()->NeedsScopeChecking() && 14273 !PP.isCodeCompletionEnabled()) 14274 DiagnoseInvalidJumps(Body); 14275 14276 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 14277 if (!Destructor->getParent()->isDependentType()) 14278 CheckDestructor(Destructor); 14279 14280 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 14281 Destructor->getParent()); 14282 } 14283 14284 // If any errors have occurred, clear out any temporaries that may have 14285 // been leftover. This ensures that these temporaries won't be picked up for 14286 // deletion in some later function. 14287 if (getDiagnostics().hasErrorOccurred() || 14288 getDiagnostics().getSuppressAllDiagnostics()) { 14289 DiscardCleanupsInEvaluationContext(); 14290 } 14291 if (!getDiagnostics().hasUncompilableErrorOccurred() && 14292 !isa<FunctionTemplateDecl>(dcl)) { 14293 // Since the body is valid, issue any analysis-based warnings that are 14294 // enabled. 14295 ActivePolicy = &WP; 14296 } 14297 14298 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 14299 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose)) 14300 FD->setInvalidDecl(); 14301 14302 if (FD && FD->hasAttr<NakedAttr>()) { 14303 for (const Stmt *S : Body->children()) { 14304 // Allow local register variables without initializer as they don't 14305 // require prologue. 14306 bool RegisterVariables = false; 14307 if (auto *DS = dyn_cast<DeclStmt>(S)) { 14308 for (const auto *Decl : DS->decls()) { 14309 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 14310 RegisterVariables = 14311 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 14312 if (!RegisterVariables) 14313 break; 14314 } 14315 } 14316 } 14317 if (RegisterVariables) 14318 continue; 14319 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 14320 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function); 14321 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 14322 FD->setInvalidDecl(); 14323 break; 14324 } 14325 } 14326 } 14327 14328 assert(ExprCleanupObjects.size() == 14329 ExprEvalContexts.back().NumCleanupObjects && 14330 "Leftover temporaries in function"); 14331 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function"); 14332 assert(MaybeODRUseExprs.empty() && 14333 "Leftover expressions for odr-use checking"); 14334 } 14335 14336 if (!IsInstantiation) 14337 PopDeclContext(); 14338 14339 PopFunctionScopeInfo(ActivePolicy, dcl); 14340 // If any errors have occurred, clear out any temporaries that may have 14341 // been leftover. This ensures that these temporaries won't be picked up for 14342 // deletion in some later function. 14343 if (getDiagnostics().hasErrorOccurred()) { 14344 DiscardCleanupsInEvaluationContext(); 14345 } 14346 14347 return dcl; 14348 } 14349 14350 /// When we finish delayed parsing of an attribute, we must attach it to the 14351 /// relevant Decl. 14352 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 14353 ParsedAttributes &Attrs) { 14354 // Always attach attributes to the underlying decl. 14355 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 14356 D = TD->getTemplatedDecl(); 14357 ProcessDeclAttributeList(S, D, Attrs); 14358 14359 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 14360 if (Method->isStatic()) 14361 checkThisInStaticMemberFunctionAttributes(Method); 14362 } 14363 14364 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 14365 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 14366 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 14367 IdentifierInfo &II, Scope *S) { 14368 // Find the scope in which the identifier is injected and the corresponding 14369 // DeclContext. 14370 // FIXME: C89 does not say what happens if there is no enclosing block scope. 14371 // In that case, we inject the declaration into the translation unit scope 14372 // instead. 14373 Scope *BlockScope = S; 14374 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) 14375 BlockScope = BlockScope->getParent(); 14376 14377 Scope *ContextScope = BlockScope; 14378 while (!ContextScope->getEntity()) 14379 ContextScope = ContextScope->getParent(); 14380 ContextRAII SavedContext(*this, ContextScope->getEntity()); 14381 14382 // Before we produce a declaration for an implicitly defined 14383 // function, see whether there was a locally-scoped declaration of 14384 // this name as a function or variable. If so, use that 14385 // (non-visible) declaration, and complain about it. 14386 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); 14387 if (ExternCPrev) { 14388 // We still need to inject the function into the enclosing block scope so 14389 // that later (non-call) uses can see it. 14390 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); 14391 14392 // C89 footnote 38: 14393 // If in fact it is not defined as having type "function returning int", 14394 // the behavior is undefined. 14395 if (!isa<FunctionDecl>(ExternCPrev) || 14396 !Context.typesAreCompatible( 14397 cast<FunctionDecl>(ExternCPrev)->getType(), 14398 Context.getFunctionNoProtoType(Context.IntTy))) { 14399 Diag(Loc, diag::ext_use_out_of_scope_declaration) 14400 << ExternCPrev << !getLangOpts().C99; 14401 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 14402 return ExternCPrev; 14403 } 14404 } 14405 14406 // Extension in C99. Legal in C90, but warn about it. 14407 unsigned diag_id; 14408 if (II.getName().startswith("__builtin_")) 14409 diag_id = diag::warn_builtin_unknown; 14410 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. 14411 else if (getLangOpts().OpenCL) 14412 diag_id = diag::err_opencl_implicit_function_decl; 14413 else if (getLangOpts().C99) 14414 diag_id = diag::ext_implicit_function_decl; 14415 else 14416 diag_id = diag::warn_implicit_function_decl; 14417 Diag(Loc, diag_id) << &II; 14418 14419 // If we found a prior declaration of this function, don't bother building 14420 // another one. We've already pushed that one into scope, so there's nothing 14421 // more to do. 14422 if (ExternCPrev) 14423 return ExternCPrev; 14424 14425 // Because typo correction is expensive, only do it if the implicit 14426 // function declaration is going to be treated as an error. 14427 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 14428 TypoCorrection Corrected; 14429 DeclFilterCCC<FunctionDecl> CCC{}; 14430 if (S && (Corrected = 14431 CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName, 14432 S, nullptr, CCC, CTK_NonError))) 14433 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 14434 /*ErrorRecovery*/false); 14435 } 14436 14437 // Set a Declarator for the implicit definition: int foo(); 14438 const char *Dummy; 14439 AttributeFactory attrFactory; 14440 DeclSpec DS(attrFactory); 14441 unsigned DiagID; 14442 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 14443 Context.getPrintingPolicy()); 14444 (void)Error; // Silence warning. 14445 assert(!Error && "Error setting up implicit decl!"); 14446 SourceLocation NoLoc; 14447 Declarator D(DS, DeclaratorContext::BlockContext); 14448 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 14449 /*IsAmbiguous=*/false, 14450 /*LParenLoc=*/NoLoc, 14451 /*Params=*/nullptr, 14452 /*NumParams=*/0, 14453 /*EllipsisLoc=*/NoLoc, 14454 /*RParenLoc=*/NoLoc, 14455 /*RefQualifierIsLvalueRef=*/true, 14456 /*RefQualifierLoc=*/NoLoc, 14457 /*MutableLoc=*/NoLoc, EST_None, 14458 /*ESpecRange=*/SourceRange(), 14459 /*Exceptions=*/nullptr, 14460 /*ExceptionRanges=*/nullptr, 14461 /*NumExceptions=*/0, 14462 /*NoexceptExpr=*/nullptr, 14463 /*ExceptionSpecTokens=*/nullptr, 14464 /*DeclsInPrototype=*/None, Loc, 14465 Loc, D), 14466 std::move(DS.getAttributes()), SourceLocation()); 14467 D.SetIdentifier(&II, Loc); 14468 14469 // Insert this function into the enclosing block scope. 14470 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); 14471 FD->setImplicit(); 14472 14473 AddKnownFunctionAttributes(FD); 14474 14475 return FD; 14476 } 14477 14478 /// Adds any function attributes that we know a priori based on 14479 /// the declaration of this function. 14480 /// 14481 /// These attributes can apply both to implicitly-declared builtins 14482 /// (like __builtin___printf_chk) or to library-declared functions 14483 /// like NSLog or printf. 14484 /// 14485 /// We need to check for duplicate attributes both here and where user-written 14486 /// attributes are applied to declarations. 14487 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 14488 if (FD->isInvalidDecl()) 14489 return; 14490 14491 // If this is a built-in function, map its builtin attributes to 14492 // actual attributes. 14493 if (unsigned BuiltinID = FD->getBuiltinID()) { 14494 // Handle printf-formatting attributes. 14495 unsigned FormatIdx; 14496 bool HasVAListArg; 14497 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 14498 if (!FD->hasAttr<FormatAttr>()) { 14499 const char *fmt = "printf"; 14500 unsigned int NumParams = FD->getNumParams(); 14501 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 14502 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 14503 fmt = "NSString"; 14504 FD->addAttr(FormatAttr::CreateImplicit(Context, 14505 &Context.Idents.get(fmt), 14506 FormatIdx+1, 14507 HasVAListArg ? 0 : FormatIdx+2, 14508 FD->getLocation())); 14509 } 14510 } 14511 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 14512 HasVAListArg)) { 14513 if (!FD->hasAttr<FormatAttr>()) 14514 FD->addAttr(FormatAttr::CreateImplicit(Context, 14515 &Context.Idents.get("scanf"), 14516 FormatIdx+1, 14517 HasVAListArg ? 0 : FormatIdx+2, 14518 FD->getLocation())); 14519 } 14520 14521 // Handle automatically recognized callbacks. 14522 SmallVector<int, 4> Encoding; 14523 if (!FD->hasAttr<CallbackAttr>() && 14524 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding)) 14525 FD->addAttr(CallbackAttr::CreateImplicit( 14526 Context, Encoding.data(), Encoding.size(), FD->getLocation())); 14527 14528 // Mark const if we don't care about errno and that is the only thing 14529 // preventing the function from being const. This allows IRgen to use LLVM 14530 // intrinsics for such functions. 14531 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() && 14532 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) 14533 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14534 14535 // We make "fma" on some platforms const because we know it does not set 14536 // errno in those environments even though it could set errno based on the 14537 // C standard. 14538 const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); 14539 if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) && 14540 !FD->hasAttr<ConstAttr>()) { 14541 switch (BuiltinID) { 14542 case Builtin::BI__builtin_fma: 14543 case Builtin::BI__builtin_fmaf: 14544 case Builtin::BI__builtin_fmal: 14545 case Builtin::BIfma: 14546 case Builtin::BIfmaf: 14547 case Builtin::BIfmal: 14548 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14549 break; 14550 default: 14551 break; 14552 } 14553 } 14554 14555 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 14556 !FD->hasAttr<ReturnsTwiceAttr>()) 14557 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 14558 FD->getLocation())); 14559 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 14560 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 14561 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 14562 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 14563 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 14564 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14565 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 14566 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 14567 // Add the appropriate attribute, depending on the CUDA compilation mode 14568 // and which target the builtin belongs to. For example, during host 14569 // compilation, aux builtins are __device__, while the rest are __host__. 14570 if (getLangOpts().CUDAIsDevice != 14571 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 14572 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 14573 else 14574 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 14575 } 14576 } 14577 14578 // If C++ exceptions are enabled but we are told extern "C" functions cannot 14579 // throw, add an implicit nothrow attribute to any extern "C" function we come 14580 // across. 14581 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 14582 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 14583 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 14584 if (!FPT || FPT->getExceptionSpecType() == EST_None) 14585 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 14586 } 14587 14588 IdentifierInfo *Name = FD->getIdentifier(); 14589 if (!Name) 14590 return; 14591 if ((!getLangOpts().CPlusPlus && 14592 FD->getDeclContext()->isTranslationUnit()) || 14593 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 14594 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 14595 LinkageSpecDecl::lang_c)) { 14596 // Okay: this could be a libc/libm/Objective-C function we know 14597 // about. 14598 } else 14599 return; 14600 14601 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 14602 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 14603 // target-specific builtins, perhaps? 14604 if (!FD->hasAttr<FormatAttr>()) 14605 FD->addAttr(FormatAttr::CreateImplicit(Context, 14606 &Context.Idents.get("printf"), 2, 14607 Name->isStr("vasprintf") ? 0 : 3, 14608 FD->getLocation())); 14609 } 14610 14611 if (Name->isStr("__CFStringMakeConstantString")) { 14612 // We already have a __builtin___CFStringMakeConstantString, 14613 // but builds that use -fno-constant-cfstrings don't go through that. 14614 if (!FD->hasAttr<FormatArgAttr>()) 14615 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), 14616 FD->getLocation())); 14617 } 14618 } 14619 14620 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 14621 TypeSourceInfo *TInfo) { 14622 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 14623 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 14624 14625 if (!TInfo) { 14626 assert(D.isInvalidType() && "no declarator info for valid type"); 14627 TInfo = Context.getTrivialTypeSourceInfo(T); 14628 } 14629 14630 // Scope manipulation handled by caller. 14631 TypedefDecl *NewTD = 14632 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(), 14633 D.getIdentifierLoc(), D.getIdentifier(), TInfo); 14634 14635 // Bail out immediately if we have an invalid declaration. 14636 if (D.isInvalidType()) { 14637 NewTD->setInvalidDecl(); 14638 return NewTD; 14639 } 14640 14641 if (D.getDeclSpec().isModulePrivateSpecified()) { 14642 if (CurContext->isFunctionOrMethod()) 14643 Diag(NewTD->getLocation(), diag::err_module_private_local) 14644 << 2 << NewTD->getDeclName() 14645 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 14646 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 14647 else 14648 NewTD->setModulePrivate(); 14649 } 14650 14651 // C++ [dcl.typedef]p8: 14652 // If the typedef declaration defines an unnamed class (or 14653 // enum), the first typedef-name declared by the declaration 14654 // to be that class type (or enum type) is used to denote the 14655 // class type (or enum type) for linkage purposes only. 14656 // We need to check whether the type was declared in the declaration. 14657 switch (D.getDeclSpec().getTypeSpecType()) { 14658 case TST_enum: 14659 case TST_struct: 14660 case TST_interface: 14661 case TST_union: 14662 case TST_class: { 14663 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 14664 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 14665 break; 14666 } 14667 14668 default: 14669 break; 14670 } 14671 14672 return NewTD; 14673 } 14674 14675 /// Check that this is a valid underlying type for an enum declaration. 14676 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 14677 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 14678 QualType T = TI->getType(); 14679 14680 if (T->isDependentType()) 14681 return false; 14682 14683 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 14684 if (BT->isInteger()) 14685 return false; 14686 14687 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 14688 return true; 14689 } 14690 14691 /// Check whether this is a valid redeclaration of a previous enumeration. 14692 /// \return true if the redeclaration was invalid. 14693 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 14694 QualType EnumUnderlyingTy, bool IsFixed, 14695 const EnumDecl *Prev) { 14696 if (IsScoped != Prev->isScoped()) { 14697 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 14698 << Prev->isScoped(); 14699 Diag(Prev->getLocation(), diag::note_previous_declaration); 14700 return true; 14701 } 14702 14703 if (IsFixed && Prev->isFixed()) { 14704 if (!EnumUnderlyingTy->isDependentType() && 14705 !Prev->getIntegerType()->isDependentType() && 14706 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 14707 Prev->getIntegerType())) { 14708 // TODO: Highlight the underlying type of the redeclaration. 14709 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 14710 << EnumUnderlyingTy << Prev->getIntegerType(); 14711 Diag(Prev->getLocation(), diag::note_previous_declaration) 14712 << Prev->getIntegerTypeRange(); 14713 return true; 14714 } 14715 } else if (IsFixed != Prev->isFixed()) { 14716 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 14717 << Prev->isFixed(); 14718 Diag(Prev->getLocation(), diag::note_previous_declaration); 14719 return true; 14720 } 14721 14722 return false; 14723 } 14724 14725 /// Get diagnostic %select index for tag kind for 14726 /// redeclaration diagnostic message. 14727 /// WARNING: Indexes apply to particular diagnostics only! 14728 /// 14729 /// \returns diagnostic %select index. 14730 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 14731 switch (Tag) { 14732 case TTK_Struct: return 0; 14733 case TTK_Interface: return 1; 14734 case TTK_Class: return 2; 14735 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 14736 } 14737 } 14738 14739 /// Determine if tag kind is a class-key compatible with 14740 /// class for redeclaration (class, struct, or __interface). 14741 /// 14742 /// \returns true iff the tag kind is compatible. 14743 static bool isClassCompatTagKind(TagTypeKind Tag) 14744 { 14745 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 14746 } 14747 14748 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 14749 TagTypeKind TTK) { 14750 if (isa<TypedefDecl>(PrevDecl)) 14751 return NTK_Typedef; 14752 else if (isa<TypeAliasDecl>(PrevDecl)) 14753 return NTK_TypeAlias; 14754 else if (isa<ClassTemplateDecl>(PrevDecl)) 14755 return NTK_Template; 14756 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 14757 return NTK_TypeAliasTemplate; 14758 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 14759 return NTK_TemplateTemplateArgument; 14760 switch (TTK) { 14761 case TTK_Struct: 14762 case TTK_Interface: 14763 case TTK_Class: 14764 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 14765 case TTK_Union: 14766 return NTK_NonUnion; 14767 case TTK_Enum: 14768 return NTK_NonEnum; 14769 } 14770 llvm_unreachable("invalid TTK"); 14771 } 14772 14773 /// Determine whether a tag with a given kind is acceptable 14774 /// as a redeclaration of the given tag declaration. 14775 /// 14776 /// \returns true if the new tag kind is acceptable, false otherwise. 14777 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 14778 TagTypeKind NewTag, bool isDefinition, 14779 SourceLocation NewTagLoc, 14780 const IdentifierInfo *Name) { 14781 // C++ [dcl.type.elab]p3: 14782 // The class-key or enum keyword present in the 14783 // elaborated-type-specifier shall agree in kind with the 14784 // declaration to which the name in the elaborated-type-specifier 14785 // refers. This rule also applies to the form of 14786 // elaborated-type-specifier that declares a class-name or 14787 // friend class since it can be construed as referring to the 14788 // definition of the class. Thus, in any 14789 // elaborated-type-specifier, the enum keyword shall be used to 14790 // refer to an enumeration (7.2), the union class-key shall be 14791 // used to refer to a union (clause 9), and either the class or 14792 // struct class-key shall be used to refer to a class (clause 9) 14793 // declared using the class or struct class-key. 14794 TagTypeKind OldTag = Previous->getTagKind(); 14795 if (OldTag != NewTag && 14796 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag))) 14797 return false; 14798 14799 // Tags are compatible, but we might still want to warn on mismatched tags. 14800 // Non-class tags can't be mismatched at this point. 14801 if (!isClassCompatTagKind(NewTag)) 14802 return true; 14803 14804 // Declarations for which -Wmismatched-tags is disabled are entirely ignored 14805 // by our warning analysis. We don't want to warn about mismatches with (eg) 14806 // declarations in system headers that are designed to be specialized, but if 14807 // a user asks us to warn, we should warn if their code contains mismatched 14808 // declarations. 14809 auto IsIgnoredLoc = [&](SourceLocation Loc) { 14810 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch, 14811 Loc); 14812 }; 14813 if (IsIgnoredLoc(NewTagLoc)) 14814 return true; 14815 14816 auto IsIgnored = [&](const TagDecl *Tag) { 14817 return IsIgnoredLoc(Tag->getLocation()); 14818 }; 14819 while (IsIgnored(Previous)) { 14820 Previous = Previous->getPreviousDecl(); 14821 if (!Previous) 14822 return true; 14823 OldTag = Previous->getTagKind(); 14824 } 14825 14826 bool isTemplate = false; 14827 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 14828 isTemplate = Record->getDescribedClassTemplate(); 14829 14830 if (inTemplateInstantiation()) { 14831 if (OldTag != NewTag) { 14832 // In a template instantiation, do not offer fix-its for tag mismatches 14833 // since they usually mess up the template instead of fixing the problem. 14834 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 14835 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 14836 << getRedeclDiagFromTagKind(OldTag); 14837 // FIXME: Note previous location? 14838 } 14839 return true; 14840 } 14841 14842 if (isDefinition) { 14843 // On definitions, check all previous tags and issue a fix-it for each 14844 // one that doesn't match the current tag. 14845 if (Previous->getDefinition()) { 14846 // Don't suggest fix-its for redefinitions. 14847 return true; 14848 } 14849 14850 bool previousMismatch = false; 14851 for (const TagDecl *I : Previous->redecls()) { 14852 if (I->getTagKind() != NewTag) { 14853 // Ignore previous declarations for which the warning was disabled. 14854 if (IsIgnored(I)) 14855 continue; 14856 14857 if (!previousMismatch) { 14858 previousMismatch = true; 14859 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 14860 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 14861 << getRedeclDiagFromTagKind(I->getTagKind()); 14862 } 14863 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 14864 << getRedeclDiagFromTagKind(NewTag) 14865 << FixItHint::CreateReplacement(I->getInnerLocStart(), 14866 TypeWithKeyword::getTagTypeKindName(NewTag)); 14867 } 14868 } 14869 return true; 14870 } 14871 14872 // Identify the prevailing tag kind: this is the kind of the definition (if 14873 // there is a non-ignored definition), or otherwise the kind of the prior 14874 // (non-ignored) declaration. 14875 const TagDecl *PrevDef = Previous->getDefinition(); 14876 if (PrevDef && IsIgnored(PrevDef)) 14877 PrevDef = nullptr; 14878 const TagDecl *Redecl = PrevDef ? PrevDef : Previous; 14879 if (Redecl->getTagKind() != NewTag) { 14880 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 14881 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 14882 << getRedeclDiagFromTagKind(OldTag); 14883 Diag(Redecl->getLocation(), diag::note_previous_use); 14884 14885 // If there is a previous definition, suggest a fix-it. 14886 if (PrevDef) { 14887 Diag(NewTagLoc, diag::note_struct_class_suggestion) 14888 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 14889 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 14890 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 14891 } 14892 } 14893 14894 return true; 14895 } 14896 14897 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 14898 /// from an outer enclosing namespace or file scope inside a friend declaration. 14899 /// This should provide the commented out code in the following snippet: 14900 /// namespace N { 14901 /// struct X; 14902 /// namespace M { 14903 /// struct Y { friend struct /*N::*/ X; }; 14904 /// } 14905 /// } 14906 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 14907 SourceLocation NameLoc) { 14908 // While the decl is in a namespace, do repeated lookup of that name and see 14909 // if we get the same namespace back. If we do not, continue until 14910 // translation unit scope, at which point we have a fully qualified NNS. 14911 SmallVector<IdentifierInfo *, 4> Namespaces; 14912 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 14913 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 14914 // This tag should be declared in a namespace, which can only be enclosed by 14915 // other namespaces. Bail if there's an anonymous namespace in the chain. 14916 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 14917 if (!Namespace || Namespace->isAnonymousNamespace()) 14918 return FixItHint(); 14919 IdentifierInfo *II = Namespace->getIdentifier(); 14920 Namespaces.push_back(II); 14921 NamedDecl *Lookup = SemaRef.LookupSingleName( 14922 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 14923 if (Lookup == Namespace) 14924 break; 14925 } 14926 14927 // Once we have all the namespaces, reverse them to go outermost first, and 14928 // build an NNS. 14929 SmallString<64> Insertion; 14930 llvm::raw_svector_ostream OS(Insertion); 14931 if (DC->isTranslationUnit()) 14932 OS << "::"; 14933 std::reverse(Namespaces.begin(), Namespaces.end()); 14934 for (auto *II : Namespaces) 14935 OS << II->getName() << "::"; 14936 return FixItHint::CreateInsertion(NameLoc, Insertion); 14937 } 14938 14939 /// Determine whether a tag originally declared in context \p OldDC can 14940 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup 14941 /// found a declaration in \p OldDC as a previous decl, perhaps through a 14942 /// using-declaration). 14943 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 14944 DeclContext *NewDC) { 14945 OldDC = OldDC->getRedeclContext(); 14946 NewDC = NewDC->getRedeclContext(); 14947 14948 if (OldDC->Equals(NewDC)) 14949 return true; 14950 14951 // In MSVC mode, we allow a redeclaration if the contexts are related (either 14952 // encloses the other). 14953 if (S.getLangOpts().MSVCCompat && 14954 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 14955 return true; 14956 14957 return false; 14958 } 14959 14960 /// This is invoked when we see 'struct foo' or 'struct {'. In the 14961 /// former case, Name will be non-null. In the later case, Name will be null. 14962 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 14963 /// reference/declaration/definition of a tag. 14964 /// 14965 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 14966 /// trailing-type-specifier) other than one in an alias-declaration. 14967 /// 14968 /// \param SkipBody If non-null, will be set to indicate if the caller should 14969 /// skip the definition of this tag and treat it as if it were a declaration. 14970 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 14971 SourceLocation KWLoc, CXXScopeSpec &SS, 14972 IdentifierInfo *Name, SourceLocation NameLoc, 14973 const ParsedAttributesView &Attrs, AccessSpecifier AS, 14974 SourceLocation ModulePrivateLoc, 14975 MultiTemplateParamsArg TemplateParameterLists, 14976 bool &OwnedDecl, bool &IsDependent, 14977 SourceLocation ScopedEnumKWLoc, 14978 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, 14979 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 14980 SkipBodyInfo *SkipBody) { 14981 // If this is not a definition, it must have a name. 14982 IdentifierInfo *OrigName = Name; 14983 assert((Name != nullptr || TUK == TUK_Definition) && 14984 "Nameless record must be a definition!"); 14985 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 14986 14987 OwnedDecl = false; 14988 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 14989 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 14990 14991 // FIXME: Check member specializations more carefully. 14992 bool isMemberSpecialization = false; 14993 bool Invalid = false; 14994 14995 // We only need to do this matching if we have template parameters 14996 // or a scope specifier, which also conveniently avoids this work 14997 // for non-C++ cases. 14998 if (TemplateParameterLists.size() > 0 || 14999 (SS.isNotEmpty() && TUK != TUK_Reference)) { 15000 if (TemplateParameterList *TemplateParams = 15001 MatchTemplateParametersToScopeSpecifier( 15002 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 15003 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 15004 if (Kind == TTK_Enum) { 15005 Diag(KWLoc, diag::err_enum_template); 15006 return nullptr; 15007 } 15008 15009 if (TemplateParams->size() > 0) { 15010 // This is a declaration or definition of a class template (which may 15011 // be a member of another template). 15012 15013 if (Invalid) 15014 return nullptr; 15015 15016 OwnedDecl = false; 15017 DeclResult Result = CheckClassTemplate( 15018 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams, 15019 AS, ModulePrivateLoc, 15020 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1, 15021 TemplateParameterLists.data(), SkipBody); 15022 return Result.get(); 15023 } else { 15024 // The "template<>" header is extraneous. 15025 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 15026 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 15027 isMemberSpecialization = true; 15028 } 15029 } 15030 } 15031 15032 // Figure out the underlying type if this a enum declaration. We need to do 15033 // this early, because it's needed to detect if this is an incompatible 15034 // redeclaration. 15035 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 15036 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; 15037 15038 if (Kind == TTK_Enum) { 15039 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { 15040 // No underlying type explicitly specified, or we failed to parse the 15041 // type, default to int. 15042 EnumUnderlying = Context.IntTy.getTypePtr(); 15043 } else if (UnderlyingType.get()) { 15044 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 15045 // integral type; any cv-qualification is ignored. 15046 TypeSourceInfo *TI = nullptr; 15047 GetTypeFromParser(UnderlyingType.get(), &TI); 15048 EnumUnderlying = TI; 15049 15050 if (CheckEnumUnderlyingType(TI)) 15051 // Recover by falling back to int. 15052 EnumUnderlying = Context.IntTy.getTypePtr(); 15053 15054 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 15055 UPPC_FixedUnderlyingType)) 15056 EnumUnderlying = Context.IntTy.getTypePtr(); 15057 15058 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) { 15059 // For MSVC ABI compatibility, unfixed enums must use an underlying type 15060 // of 'int'. However, if this is an unfixed forward declaration, don't set 15061 // the underlying type unless the user enables -fms-compatibility. This 15062 // makes unfixed forward declared enums incomplete and is more conforming. 15063 if (TUK == TUK_Definition || getLangOpts().MSVCCompat) 15064 EnumUnderlying = Context.IntTy.getTypePtr(); 15065 } 15066 } 15067 15068 DeclContext *SearchDC = CurContext; 15069 DeclContext *DC = CurContext; 15070 bool isStdBadAlloc = false; 15071 bool isStdAlignValT = false; 15072 15073 RedeclarationKind Redecl = forRedeclarationInCurContext(); 15074 if (TUK == TUK_Friend || TUK == TUK_Reference) 15075 Redecl = NotForRedeclaration; 15076 15077 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C 15078 /// implemented asks for structural equivalence checking, the returned decl 15079 /// here is passed back to the parser, allowing the tag body to be parsed. 15080 auto createTagFromNewDecl = [&]() -> TagDecl * { 15081 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage"); 15082 // If there is an identifier, use the location of the identifier as the 15083 // location of the decl, otherwise use the location of the struct/union 15084 // keyword. 15085 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 15086 TagDecl *New = nullptr; 15087 15088 if (Kind == TTK_Enum) { 15089 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, 15090 ScopedEnum, ScopedEnumUsesClassTag, IsFixed); 15091 // If this is an undefined enum, bail. 15092 if (TUK != TUK_Definition && !Invalid) 15093 return nullptr; 15094 if (EnumUnderlying) { 15095 EnumDecl *ED = cast<EnumDecl>(New); 15096 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) 15097 ED->setIntegerTypeSourceInfo(TI); 15098 else 15099 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); 15100 ED->setPromotionType(ED->getIntegerType()); 15101 } 15102 } else { // struct/union 15103 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 15104 nullptr); 15105 } 15106 15107 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 15108 // Add alignment attributes if necessary; these attributes are checked 15109 // when the ASTContext lays out the structure. 15110 // 15111 // It is important for implementing the correct semantics that this 15112 // happen here (in ActOnTag). The #pragma pack stack is 15113 // maintained as a result of parser callbacks which can occur at 15114 // many points during the parsing of a struct declaration (because 15115 // the #pragma tokens are effectively skipped over during the 15116 // parsing of the struct). 15117 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 15118 AddAlignmentAttributesForRecord(RD); 15119 AddMsStructLayoutForRecord(RD); 15120 } 15121 } 15122 New->setLexicalDeclContext(CurContext); 15123 return New; 15124 }; 15125 15126 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 15127 if (Name && SS.isNotEmpty()) { 15128 // We have a nested-name tag ('struct foo::bar'). 15129 15130 // Check for invalid 'foo::'. 15131 if (SS.isInvalid()) { 15132 Name = nullptr; 15133 goto CreateNewDecl; 15134 } 15135 15136 // If this is a friend or a reference to a class in a dependent 15137 // context, don't try to make a decl for it. 15138 if (TUK == TUK_Friend || TUK == TUK_Reference) { 15139 DC = computeDeclContext(SS, false); 15140 if (!DC) { 15141 IsDependent = true; 15142 return nullptr; 15143 } 15144 } else { 15145 DC = computeDeclContext(SS, true); 15146 if (!DC) { 15147 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 15148 << SS.getRange(); 15149 return nullptr; 15150 } 15151 } 15152 15153 if (RequireCompleteDeclContext(SS, DC)) 15154 return nullptr; 15155 15156 SearchDC = DC; 15157 // Look-up name inside 'foo::'. 15158 LookupQualifiedName(Previous, DC); 15159 15160 if (Previous.isAmbiguous()) 15161 return nullptr; 15162 15163 if (Previous.empty()) { 15164 // Name lookup did not find anything. However, if the 15165 // nested-name-specifier refers to the current instantiation, 15166 // and that current instantiation has any dependent base 15167 // classes, we might find something at instantiation time: treat 15168 // this as a dependent elaborated-type-specifier. 15169 // But this only makes any sense for reference-like lookups. 15170 if (Previous.wasNotFoundInCurrentInstantiation() && 15171 (TUK == TUK_Reference || TUK == TUK_Friend)) { 15172 IsDependent = true; 15173 return nullptr; 15174 } 15175 15176 // A tag 'foo::bar' must already exist. 15177 Diag(NameLoc, diag::err_not_tag_in_scope) 15178 << Kind << Name << DC << SS.getRange(); 15179 Name = nullptr; 15180 Invalid = true; 15181 goto CreateNewDecl; 15182 } 15183 } else if (Name) { 15184 // C++14 [class.mem]p14: 15185 // If T is the name of a class, then each of the following shall have a 15186 // name different from T: 15187 // -- every member of class T that is itself a type 15188 if (TUK != TUK_Reference && TUK != TUK_Friend && 15189 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 15190 return nullptr; 15191 15192 // If this is a named struct, check to see if there was a previous forward 15193 // declaration or definition. 15194 // FIXME: We're looking into outer scopes here, even when we 15195 // shouldn't be. Doing so can result in ambiguities that we 15196 // shouldn't be diagnosing. 15197 LookupName(Previous, S); 15198 15199 // When declaring or defining a tag, ignore ambiguities introduced 15200 // by types using'ed into this scope. 15201 if (Previous.isAmbiguous() && 15202 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 15203 LookupResult::Filter F = Previous.makeFilter(); 15204 while (F.hasNext()) { 15205 NamedDecl *ND = F.next(); 15206 if (!ND->getDeclContext()->getRedeclContext()->Equals( 15207 SearchDC->getRedeclContext())) 15208 F.erase(); 15209 } 15210 F.done(); 15211 } 15212 15213 // C++11 [namespace.memdef]p3: 15214 // If the name in a friend declaration is neither qualified nor 15215 // a template-id and the declaration is a function or an 15216 // elaborated-type-specifier, the lookup to determine whether 15217 // the entity has been previously declared shall not consider 15218 // any scopes outside the innermost enclosing namespace. 15219 // 15220 // MSVC doesn't implement the above rule for types, so a friend tag 15221 // declaration may be a redeclaration of a type declared in an enclosing 15222 // scope. They do implement this rule for friend functions. 15223 // 15224 // Does it matter that this should be by scope instead of by 15225 // semantic context? 15226 if (!Previous.empty() && TUK == TUK_Friend) { 15227 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 15228 LookupResult::Filter F = Previous.makeFilter(); 15229 bool FriendSawTagOutsideEnclosingNamespace = false; 15230 while (F.hasNext()) { 15231 NamedDecl *ND = F.next(); 15232 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15233 if (DC->isFileContext() && 15234 !EnclosingNS->Encloses(ND->getDeclContext())) { 15235 if (getLangOpts().MSVCCompat) 15236 FriendSawTagOutsideEnclosingNamespace = true; 15237 else 15238 F.erase(); 15239 } 15240 } 15241 F.done(); 15242 15243 // Diagnose this MSVC extension in the easy case where lookup would have 15244 // unambiguously found something outside the enclosing namespace. 15245 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 15246 NamedDecl *ND = Previous.getFoundDecl(); 15247 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 15248 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 15249 } 15250 } 15251 15252 // Note: there used to be some attempt at recovery here. 15253 if (Previous.isAmbiguous()) 15254 return nullptr; 15255 15256 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 15257 // FIXME: This makes sure that we ignore the contexts associated 15258 // with C structs, unions, and enums when looking for a matching 15259 // tag declaration or definition. See the similar lookup tweak 15260 // in Sema::LookupName; is there a better way to deal with this? 15261 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 15262 SearchDC = SearchDC->getParent(); 15263 } 15264 } 15265 15266 if (Previous.isSingleResult() && 15267 Previous.getFoundDecl()->isTemplateParameter()) { 15268 // Maybe we will complain about the shadowed template parameter. 15269 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 15270 // Just pretend that we didn't see the previous declaration. 15271 Previous.clear(); 15272 } 15273 15274 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 15275 DC->Equals(getStdNamespace())) { 15276 if (Name->isStr("bad_alloc")) { 15277 // This is a declaration of or a reference to "std::bad_alloc". 15278 isStdBadAlloc = true; 15279 15280 // If std::bad_alloc has been implicitly declared (but made invisible to 15281 // name lookup), fill in this implicit declaration as the previous 15282 // declaration, so that the declarations get chained appropriately. 15283 if (Previous.empty() && StdBadAlloc) 15284 Previous.addDecl(getStdBadAlloc()); 15285 } else if (Name->isStr("align_val_t")) { 15286 isStdAlignValT = true; 15287 if (Previous.empty() && StdAlignValT) 15288 Previous.addDecl(getStdAlignValT()); 15289 } 15290 } 15291 15292 // If we didn't find a previous declaration, and this is a reference 15293 // (or friend reference), move to the correct scope. In C++, we 15294 // also need to do a redeclaration lookup there, just in case 15295 // there's a shadow friend decl. 15296 if (Name && Previous.empty() && 15297 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { 15298 if (Invalid) goto CreateNewDecl; 15299 assert(SS.isEmpty()); 15300 15301 if (TUK == TUK_Reference || IsTemplateParamOrArg) { 15302 // C++ [basic.scope.pdecl]p5: 15303 // -- for an elaborated-type-specifier of the form 15304 // 15305 // class-key identifier 15306 // 15307 // if the elaborated-type-specifier is used in the 15308 // decl-specifier-seq or parameter-declaration-clause of a 15309 // function defined in namespace scope, the identifier is 15310 // declared as a class-name in the namespace that contains 15311 // the declaration; otherwise, except as a friend 15312 // declaration, the identifier is declared in the smallest 15313 // non-class, non-function-prototype scope that contains the 15314 // declaration. 15315 // 15316 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 15317 // C structs and unions. 15318 // 15319 // It is an error in C++ to declare (rather than define) an enum 15320 // type, including via an elaborated type specifier. We'll 15321 // diagnose that later; for now, declare the enum in the same 15322 // scope as we would have picked for any other tag type. 15323 // 15324 // GNU C also supports this behavior as part of its incomplete 15325 // enum types extension, while GNU C++ does not. 15326 // 15327 // Find the context where we'll be declaring the tag. 15328 // FIXME: We would like to maintain the current DeclContext as the 15329 // lexical context, 15330 SearchDC = getTagInjectionContext(SearchDC); 15331 15332 // Find the scope where we'll be declaring the tag. 15333 S = getTagInjectionScope(S, getLangOpts()); 15334 } else { 15335 assert(TUK == TUK_Friend); 15336 // C++ [namespace.memdef]p3: 15337 // If a friend declaration in a non-local class first declares a 15338 // class or function, the friend class or function is a member of 15339 // the innermost enclosing namespace. 15340 SearchDC = SearchDC->getEnclosingNamespaceContext(); 15341 } 15342 15343 // In C++, we need to do a redeclaration lookup to properly 15344 // diagnose some problems. 15345 // FIXME: redeclaration lookup is also used (with and without C++) to find a 15346 // hidden declaration so that we don't get ambiguity errors when using a 15347 // type declared by an elaborated-type-specifier. In C that is not correct 15348 // and we should instead merge compatible types found by lookup. 15349 if (getLangOpts().CPlusPlus) { 15350 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 15351 LookupQualifiedName(Previous, SearchDC); 15352 } else { 15353 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 15354 LookupName(Previous, S); 15355 } 15356 } 15357 15358 // If we have a known previous declaration to use, then use it. 15359 if (Previous.empty() && SkipBody && SkipBody->Previous) 15360 Previous.addDecl(SkipBody->Previous); 15361 15362 if (!Previous.empty()) { 15363 NamedDecl *PrevDecl = Previous.getFoundDecl(); 15364 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 15365 15366 // It's okay to have a tag decl in the same scope as a typedef 15367 // which hides a tag decl in the same scope. Finding this 15368 // insanity with a redeclaration lookup can only actually happen 15369 // in C++. 15370 // 15371 // This is also okay for elaborated-type-specifiers, which is 15372 // technically forbidden by the current standard but which is 15373 // okay according to the likely resolution of an open issue; 15374 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 15375 if (getLangOpts().CPlusPlus) { 15376 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 15377 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 15378 TagDecl *Tag = TT->getDecl(); 15379 if (Tag->getDeclName() == Name && 15380 Tag->getDeclContext()->getRedeclContext() 15381 ->Equals(TD->getDeclContext()->getRedeclContext())) { 15382 PrevDecl = Tag; 15383 Previous.clear(); 15384 Previous.addDecl(Tag); 15385 Previous.resolveKind(); 15386 } 15387 } 15388 } 15389 } 15390 15391 // If this is a redeclaration of a using shadow declaration, it must 15392 // declare a tag in the same context. In MSVC mode, we allow a 15393 // redefinition if either context is within the other. 15394 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 15395 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 15396 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 15397 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 15398 !(OldTag && isAcceptableTagRedeclContext( 15399 *this, OldTag->getDeclContext(), SearchDC))) { 15400 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 15401 Diag(Shadow->getTargetDecl()->getLocation(), 15402 diag::note_using_decl_target); 15403 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) 15404 << 0; 15405 // Recover by ignoring the old declaration. 15406 Previous.clear(); 15407 goto CreateNewDecl; 15408 } 15409 } 15410 15411 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 15412 // If this is a use of a previous tag, or if the tag is already declared 15413 // in the same scope (so that the definition/declaration completes or 15414 // rementions the tag), reuse the decl. 15415 if (TUK == TUK_Reference || TUK == TUK_Friend || 15416 isDeclInScope(DirectPrevDecl, SearchDC, S, 15417 SS.isNotEmpty() || isMemberSpecialization)) { 15418 // Make sure that this wasn't declared as an enum and now used as a 15419 // struct or something similar. 15420 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 15421 TUK == TUK_Definition, KWLoc, 15422 Name)) { 15423 bool SafeToContinue 15424 = (PrevTagDecl->getTagKind() != TTK_Enum && 15425 Kind != TTK_Enum); 15426 if (SafeToContinue) 15427 Diag(KWLoc, diag::err_use_with_wrong_tag) 15428 << Name 15429 << FixItHint::CreateReplacement(SourceRange(KWLoc), 15430 PrevTagDecl->getKindName()); 15431 else 15432 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 15433 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 15434 15435 if (SafeToContinue) 15436 Kind = PrevTagDecl->getTagKind(); 15437 else { 15438 // Recover by making this an anonymous redefinition. 15439 Name = nullptr; 15440 Previous.clear(); 15441 Invalid = true; 15442 } 15443 } 15444 15445 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 15446 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 15447 15448 // If this is an elaborated-type-specifier for a scoped enumeration, 15449 // the 'class' keyword is not necessary and not permitted. 15450 if (TUK == TUK_Reference || TUK == TUK_Friend) { 15451 if (ScopedEnum) 15452 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 15453 << PrevEnum->isScoped() 15454 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 15455 return PrevTagDecl; 15456 } 15457 15458 QualType EnumUnderlyingTy; 15459 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 15460 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 15461 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 15462 EnumUnderlyingTy = QualType(T, 0); 15463 15464 // All conflicts with previous declarations are recovered by 15465 // returning the previous declaration, unless this is a definition, 15466 // in which case we want the caller to bail out. 15467 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 15468 ScopedEnum, EnumUnderlyingTy, 15469 IsFixed, PrevEnum)) 15470 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 15471 } 15472 15473 // C++11 [class.mem]p1: 15474 // A member shall not be declared twice in the member-specification, 15475 // except that a nested class or member class template can be declared 15476 // and then later defined. 15477 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 15478 S->isDeclScope(PrevDecl)) { 15479 Diag(NameLoc, diag::ext_member_redeclared); 15480 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 15481 } 15482 15483 if (!Invalid) { 15484 // If this is a use, just return the declaration we found, unless 15485 // we have attributes. 15486 if (TUK == TUK_Reference || TUK == TUK_Friend) { 15487 if (!Attrs.empty()) { 15488 // FIXME: Diagnose these attributes. For now, we create a new 15489 // declaration to hold them. 15490 } else if (TUK == TUK_Reference && 15491 (PrevTagDecl->getFriendObjectKind() == 15492 Decl::FOK_Undeclared || 15493 PrevDecl->getOwningModule() != getCurrentModule()) && 15494 SS.isEmpty()) { 15495 // This declaration is a reference to an existing entity, but 15496 // has different visibility from that entity: it either makes 15497 // a friend visible or it makes a type visible in a new module. 15498 // In either case, create a new declaration. We only do this if 15499 // the declaration would have meant the same thing if no prior 15500 // declaration were found, that is, if it was found in the same 15501 // scope where we would have injected a declaration. 15502 if (!getTagInjectionContext(CurContext)->getRedeclContext() 15503 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 15504 return PrevTagDecl; 15505 // This is in the injected scope, create a new declaration in 15506 // that scope. 15507 S = getTagInjectionScope(S, getLangOpts()); 15508 } else { 15509 return PrevTagDecl; 15510 } 15511 } 15512 15513 // Diagnose attempts to redefine a tag. 15514 if (TUK == TUK_Definition) { 15515 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 15516 // If we're defining a specialization and the previous definition 15517 // is from an implicit instantiation, don't emit an error 15518 // here; we'll catch this in the general case below. 15519 bool IsExplicitSpecializationAfterInstantiation = false; 15520 if (isMemberSpecialization) { 15521 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 15522 IsExplicitSpecializationAfterInstantiation = 15523 RD->getTemplateSpecializationKind() != 15524 TSK_ExplicitSpecialization; 15525 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 15526 IsExplicitSpecializationAfterInstantiation = 15527 ED->getTemplateSpecializationKind() != 15528 TSK_ExplicitSpecialization; 15529 } 15530 15531 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do 15532 // not keep more that one definition around (merge them). However, 15533 // ensure the decl passes the structural compatibility check in 15534 // C11 6.2.7/1 (or 6.1.2.6/1 in C89). 15535 NamedDecl *Hidden = nullptr; 15536 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 15537 // There is a definition of this tag, but it is not visible. We 15538 // explicitly make use of C++'s one definition rule here, and 15539 // assume that this definition is identical to the hidden one 15540 // we already have. Make the existing definition visible and 15541 // use it in place of this one. 15542 if (!getLangOpts().CPlusPlus) { 15543 // Postpone making the old definition visible until after we 15544 // complete parsing the new one and do the structural 15545 // comparison. 15546 SkipBody->CheckSameAsPrevious = true; 15547 SkipBody->New = createTagFromNewDecl(); 15548 SkipBody->Previous = Def; 15549 return Def; 15550 } else { 15551 SkipBody->ShouldSkip = true; 15552 SkipBody->Previous = Def; 15553 makeMergedDefinitionVisible(Hidden); 15554 // Carry on and handle it like a normal definition. We'll 15555 // skip starting the definitiion later. 15556 } 15557 } else if (!IsExplicitSpecializationAfterInstantiation) { 15558 // A redeclaration in function prototype scope in C isn't 15559 // visible elsewhere, so merely issue a warning. 15560 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 15561 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 15562 else 15563 Diag(NameLoc, diag::err_redefinition) << Name; 15564 notePreviousDefinition(Def, 15565 NameLoc.isValid() ? NameLoc : KWLoc); 15566 // If this is a redefinition, recover by making this 15567 // struct be anonymous, which will make any later 15568 // references get the previous definition. 15569 Name = nullptr; 15570 Previous.clear(); 15571 Invalid = true; 15572 } 15573 } else { 15574 // If the type is currently being defined, complain 15575 // about a nested redefinition. 15576 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 15577 if (TD->isBeingDefined()) { 15578 Diag(NameLoc, diag::err_nested_redefinition) << Name; 15579 Diag(PrevTagDecl->getLocation(), 15580 diag::note_previous_definition); 15581 Name = nullptr; 15582 Previous.clear(); 15583 Invalid = true; 15584 } 15585 } 15586 15587 // Okay, this is definition of a previously declared or referenced 15588 // tag. We're going to create a new Decl for it. 15589 } 15590 15591 // Okay, we're going to make a redeclaration. If this is some kind 15592 // of reference, make sure we build the redeclaration in the same DC 15593 // as the original, and ignore the current access specifier. 15594 if (TUK == TUK_Friend || TUK == TUK_Reference) { 15595 SearchDC = PrevTagDecl->getDeclContext(); 15596 AS = AS_none; 15597 } 15598 } 15599 // If we get here we have (another) forward declaration or we 15600 // have a definition. Just create a new decl. 15601 15602 } else { 15603 // If we get here, this is a definition of a new tag type in a nested 15604 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 15605 // new decl/type. We set PrevDecl to NULL so that the entities 15606 // have distinct types. 15607 Previous.clear(); 15608 } 15609 // If we get here, we're going to create a new Decl. If PrevDecl 15610 // is non-NULL, it's a definition of the tag declared by 15611 // PrevDecl. If it's NULL, we have a new definition. 15612 15613 // Otherwise, PrevDecl is not a tag, but was found with tag 15614 // lookup. This is only actually possible in C++, where a few 15615 // things like templates still live in the tag namespace. 15616 } else { 15617 // Use a better diagnostic if an elaborated-type-specifier 15618 // found the wrong kind of type on the first 15619 // (non-redeclaration) lookup. 15620 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 15621 !Previous.isForRedeclaration()) { 15622 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 15623 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 15624 << Kind; 15625 Diag(PrevDecl->getLocation(), diag::note_declared_at); 15626 Invalid = true; 15627 15628 // Otherwise, only diagnose if the declaration is in scope. 15629 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 15630 SS.isNotEmpty() || isMemberSpecialization)) { 15631 // do nothing 15632 15633 // Diagnose implicit declarations introduced by elaborated types. 15634 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 15635 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 15636 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 15637 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 15638 Invalid = true; 15639 15640 // Otherwise it's a declaration. Call out a particularly common 15641 // case here. 15642 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 15643 unsigned Kind = 0; 15644 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 15645 Diag(NameLoc, diag::err_tag_definition_of_typedef) 15646 << Name << Kind << TND->getUnderlyingType(); 15647 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 15648 Invalid = true; 15649 15650 // Otherwise, diagnose. 15651 } else { 15652 // The tag name clashes with something else in the target scope, 15653 // issue an error and recover by making this tag be anonymous. 15654 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 15655 notePreviousDefinition(PrevDecl, NameLoc); 15656 Name = nullptr; 15657 Invalid = true; 15658 } 15659 15660 // The existing declaration isn't relevant to us; we're in a 15661 // new scope, so clear out the previous declaration. 15662 Previous.clear(); 15663 } 15664 } 15665 15666 CreateNewDecl: 15667 15668 TagDecl *PrevDecl = nullptr; 15669 if (Previous.isSingleResult()) 15670 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 15671 15672 // If there is an identifier, use the location of the identifier as the 15673 // location of the decl, otherwise use the location of the struct/union 15674 // keyword. 15675 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 15676 15677 // Otherwise, create a new declaration. If there is a previous 15678 // declaration of the same entity, the two will be linked via 15679 // PrevDecl. 15680 TagDecl *New; 15681 15682 if (Kind == TTK_Enum) { 15683 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 15684 // enum X { A, B, C } D; D should chain to X. 15685 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 15686 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 15687 ScopedEnumUsesClassTag, IsFixed); 15688 15689 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 15690 StdAlignValT = cast<EnumDecl>(New); 15691 15692 // If this is an undefined enum, warn. 15693 if (TUK != TUK_Definition && !Invalid) { 15694 TagDecl *Def; 15695 if (IsFixed && cast<EnumDecl>(New)->isFixed()) { 15696 // C++0x: 7.2p2: opaque-enum-declaration. 15697 // Conflicts are diagnosed above. Do nothing. 15698 } 15699 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 15700 Diag(Loc, diag::ext_forward_ref_enum_def) 15701 << New; 15702 Diag(Def->getLocation(), diag::note_previous_definition); 15703 } else { 15704 unsigned DiagID = diag::ext_forward_ref_enum; 15705 if (getLangOpts().MSVCCompat) 15706 DiagID = diag::ext_ms_forward_ref_enum; 15707 else if (getLangOpts().CPlusPlus) 15708 DiagID = diag::err_forward_ref_enum; 15709 Diag(Loc, DiagID); 15710 } 15711 } 15712 15713 if (EnumUnderlying) { 15714 EnumDecl *ED = cast<EnumDecl>(New); 15715 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 15716 ED->setIntegerTypeSourceInfo(TI); 15717 else 15718 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 15719 ED->setPromotionType(ED->getIntegerType()); 15720 assert(ED->isComplete() && "enum with type should be complete"); 15721 } 15722 } else { 15723 // struct/union/class 15724 15725 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 15726 // struct X { int A; } D; D should chain to X. 15727 if (getLangOpts().CPlusPlus) { 15728 // FIXME: Look for a way to use RecordDecl for simple structs. 15729 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 15730 cast_or_null<CXXRecordDecl>(PrevDecl)); 15731 15732 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 15733 StdBadAlloc = cast<CXXRecordDecl>(New); 15734 } else 15735 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 15736 cast_or_null<RecordDecl>(PrevDecl)); 15737 } 15738 15739 // C++11 [dcl.type]p3: 15740 // A type-specifier-seq shall not define a class or enumeration [...]. 15741 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && 15742 TUK == TUK_Definition) { 15743 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 15744 << Context.getTagDeclType(New); 15745 Invalid = true; 15746 } 15747 15748 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && 15749 DC->getDeclKind() == Decl::Enum) { 15750 Diag(New->getLocation(), diag::err_type_defined_in_enum) 15751 << Context.getTagDeclType(New); 15752 Invalid = true; 15753 } 15754 15755 // Maybe add qualifier info. 15756 if (SS.isNotEmpty()) { 15757 if (SS.isSet()) { 15758 // If this is either a declaration or a definition, check the 15759 // nested-name-specifier against the current context. 15760 if ((TUK == TUK_Definition || TUK == TUK_Declaration) && 15761 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, 15762 isMemberSpecialization)) 15763 Invalid = true; 15764 15765 New->setQualifierInfo(SS.getWithLocInContext(Context)); 15766 if (TemplateParameterLists.size() > 0) { 15767 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 15768 } 15769 } 15770 else 15771 Invalid = true; 15772 } 15773 15774 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 15775 // Add alignment attributes if necessary; these attributes are checked when 15776 // the ASTContext lays out the structure. 15777 // 15778 // It is important for implementing the correct semantics that this 15779 // happen here (in ActOnTag). The #pragma pack stack is 15780 // maintained as a result of parser callbacks which can occur at 15781 // many points during the parsing of a struct declaration (because 15782 // the #pragma tokens are effectively skipped over during the 15783 // parsing of the struct). 15784 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 15785 AddAlignmentAttributesForRecord(RD); 15786 AddMsStructLayoutForRecord(RD); 15787 } 15788 } 15789 15790 if (ModulePrivateLoc.isValid()) { 15791 if (isMemberSpecialization) 15792 Diag(New->getLocation(), diag::err_module_private_specialization) 15793 << 2 15794 << FixItHint::CreateRemoval(ModulePrivateLoc); 15795 // __module_private__ does not apply to local classes. However, we only 15796 // diagnose this as an error when the declaration specifiers are 15797 // freestanding. Here, we just ignore the __module_private__. 15798 else if (!SearchDC->isFunctionOrMethod()) 15799 New->setModulePrivate(); 15800 } 15801 15802 // If this is a specialization of a member class (of a class template), 15803 // check the specialization. 15804 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 15805 Invalid = true; 15806 15807 // If we're declaring or defining a tag in function prototype scope in C, 15808 // note that this type can only be used within the function and add it to 15809 // the list of decls to inject into the function definition scope. 15810 if ((Name || Kind == TTK_Enum) && 15811 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 15812 if (getLangOpts().CPlusPlus) { 15813 // C++ [dcl.fct]p6: 15814 // Types shall not be defined in return or parameter types. 15815 if (TUK == TUK_Definition && !IsTypeSpecifier) { 15816 Diag(Loc, diag::err_type_defined_in_param_type) 15817 << Name; 15818 Invalid = true; 15819 } 15820 } else if (!PrevDecl) { 15821 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 15822 } 15823 } 15824 15825 if (Invalid) 15826 New->setInvalidDecl(); 15827 15828 // Set the lexical context. If the tag has a C++ scope specifier, the 15829 // lexical context will be different from the semantic context. 15830 New->setLexicalDeclContext(CurContext); 15831 15832 // Mark this as a friend decl if applicable. 15833 // In Microsoft mode, a friend declaration also acts as a forward 15834 // declaration so we always pass true to setObjectOfFriendDecl to make 15835 // the tag name visible. 15836 if (TUK == TUK_Friend) 15837 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 15838 15839 // Set the access specifier. 15840 if (!Invalid && SearchDC->isRecord()) 15841 SetMemberAccessSpecifier(New, PrevDecl, AS); 15842 15843 if (PrevDecl) 15844 CheckRedeclarationModuleOwnership(New, PrevDecl); 15845 15846 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) 15847 New->startDefinition(); 15848 15849 ProcessDeclAttributeList(S, New, Attrs); 15850 AddPragmaAttributes(S, New); 15851 15852 // If this has an identifier, add it to the scope stack. 15853 if (TUK == TUK_Friend) { 15854 // We might be replacing an existing declaration in the lookup tables; 15855 // if so, borrow its access specifier. 15856 if (PrevDecl) 15857 New->setAccess(PrevDecl->getAccess()); 15858 15859 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 15860 DC->makeDeclVisibleInContext(New); 15861 if (Name) // can be null along some error paths 15862 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 15863 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 15864 } else if (Name) { 15865 S = getNonFieldDeclScope(S); 15866 PushOnScopeChains(New, S, true); 15867 } else { 15868 CurContext->addDecl(New); 15869 } 15870 15871 // If this is the C FILE type, notify the AST context. 15872 if (IdentifierInfo *II = New->getIdentifier()) 15873 if (!New->isInvalidDecl() && 15874 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 15875 II->isStr("FILE")) 15876 Context.setFILEDecl(New); 15877 15878 if (PrevDecl) 15879 mergeDeclAttributes(New, PrevDecl); 15880 15881 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) 15882 inferGslOwnerPointerAttribute(CXXRD); 15883 15884 // If there's a #pragma GCC visibility in scope, set the visibility of this 15885 // record. 15886 AddPushedVisibilityAttribute(New); 15887 15888 if (isMemberSpecialization && !New->isInvalidDecl()) 15889 CompleteMemberSpecialization(New, Previous); 15890 15891 OwnedDecl = true; 15892 // In C++, don't return an invalid declaration. We can't recover well from 15893 // the cases where we make the type anonymous. 15894 if (Invalid && getLangOpts().CPlusPlus) { 15895 if (New->isBeingDefined()) 15896 if (auto RD = dyn_cast<RecordDecl>(New)) 15897 RD->completeDefinition(); 15898 return nullptr; 15899 } else if (SkipBody && SkipBody->ShouldSkip) { 15900 return SkipBody->Previous; 15901 } else { 15902 return New; 15903 } 15904 } 15905 15906 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 15907 AdjustDeclIfTemplate(TagD); 15908 TagDecl *Tag = cast<TagDecl>(TagD); 15909 15910 // Enter the tag context. 15911 PushDeclContext(S, Tag); 15912 15913 ActOnDocumentableDecl(TagD); 15914 15915 // If there's a #pragma GCC visibility in scope, set the visibility of this 15916 // record. 15917 AddPushedVisibilityAttribute(Tag); 15918 } 15919 15920 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, 15921 SkipBodyInfo &SkipBody) { 15922 if (!hasStructuralCompatLayout(Prev, SkipBody.New)) 15923 return false; 15924 15925 // Make the previous decl visible. 15926 makeMergedDefinitionVisible(SkipBody.Previous); 15927 return true; 15928 } 15929 15930 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 15931 assert(isa<ObjCContainerDecl>(IDecl) && 15932 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 15933 DeclContext *OCD = cast<DeclContext>(IDecl); 15934 assert(getContainingDC(OCD) == CurContext && 15935 "The next DeclContext should be lexically contained in the current one."); 15936 CurContext = OCD; 15937 return IDecl; 15938 } 15939 15940 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 15941 SourceLocation FinalLoc, 15942 bool IsFinalSpelledSealed, 15943 SourceLocation LBraceLoc) { 15944 AdjustDeclIfTemplate(TagD); 15945 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 15946 15947 FieldCollector->StartClass(); 15948 15949 if (!Record->getIdentifier()) 15950 return; 15951 15952 if (FinalLoc.isValid()) 15953 Record->addAttr(FinalAttr::Create( 15954 Context, FinalLoc, AttributeCommonInfo::AS_Keyword, 15955 static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed))); 15956 15957 // C++ [class]p2: 15958 // [...] The class-name is also inserted into the scope of the 15959 // class itself; this is known as the injected-class-name. For 15960 // purposes of access checking, the injected-class-name is treated 15961 // as if it were a public member name. 15962 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create( 15963 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(), 15964 Record->getLocation(), Record->getIdentifier(), 15965 /*PrevDecl=*/nullptr, 15966 /*DelayTypeCreation=*/true); 15967 Context.getTypeDeclType(InjectedClassName, Record); 15968 InjectedClassName->setImplicit(); 15969 InjectedClassName->setAccess(AS_public); 15970 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 15971 InjectedClassName->setDescribedClassTemplate(Template); 15972 PushOnScopeChains(InjectedClassName, S); 15973 assert(InjectedClassName->isInjectedClassName() && 15974 "Broken injected-class-name"); 15975 } 15976 15977 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 15978 SourceRange BraceRange) { 15979 AdjustDeclIfTemplate(TagD); 15980 TagDecl *Tag = cast<TagDecl>(TagD); 15981 Tag->setBraceRange(BraceRange); 15982 15983 // Make sure we "complete" the definition even it is invalid. 15984 if (Tag->isBeingDefined()) { 15985 assert(Tag->isInvalidDecl() && "We should already have completed it"); 15986 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 15987 RD->completeDefinition(); 15988 } 15989 15990 if (isa<CXXRecordDecl>(Tag)) { 15991 FieldCollector->FinishClass(); 15992 } 15993 15994 // Exit this scope of this tag's definition. 15995 PopDeclContext(); 15996 15997 if (getCurLexicalContext()->isObjCContainer() && 15998 Tag->getDeclContext()->isFileContext()) 15999 Tag->setTopLevelDeclInObjCContainer(); 16000 16001 // Notify the consumer that we've defined a tag. 16002 if (!Tag->isInvalidDecl()) 16003 Consumer.HandleTagDeclDefinition(Tag); 16004 } 16005 16006 void Sema::ActOnObjCContainerFinishDefinition() { 16007 // Exit this scope of this interface definition. 16008 PopDeclContext(); 16009 } 16010 16011 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 16012 assert(DC == CurContext && "Mismatch of container contexts"); 16013 OriginalLexicalContext = DC; 16014 ActOnObjCContainerFinishDefinition(); 16015 } 16016 16017 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 16018 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 16019 OriginalLexicalContext = nullptr; 16020 } 16021 16022 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 16023 AdjustDeclIfTemplate(TagD); 16024 TagDecl *Tag = cast<TagDecl>(TagD); 16025 Tag->setInvalidDecl(); 16026 16027 // Make sure we "complete" the definition even it is invalid. 16028 if (Tag->isBeingDefined()) { 16029 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16030 RD->completeDefinition(); 16031 } 16032 16033 // We're undoing ActOnTagStartDefinition here, not 16034 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 16035 // the FieldCollector. 16036 16037 PopDeclContext(); 16038 } 16039 16040 // Note that FieldName may be null for anonymous bitfields. 16041 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 16042 IdentifierInfo *FieldName, 16043 QualType FieldTy, bool IsMsStruct, 16044 Expr *BitWidth, bool *ZeroWidth) { 16045 // Default to true; that shouldn't confuse checks for emptiness 16046 if (ZeroWidth) 16047 *ZeroWidth = true; 16048 16049 // C99 6.7.2.1p4 - verify the field type. 16050 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 16051 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 16052 // Handle incomplete types with specific error. 16053 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 16054 return ExprError(); 16055 if (FieldName) 16056 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 16057 << FieldName << FieldTy << BitWidth->getSourceRange(); 16058 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 16059 << FieldTy << BitWidth->getSourceRange(); 16060 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 16061 UPPC_BitFieldWidth)) 16062 return ExprError(); 16063 16064 // If the bit-width is type- or value-dependent, don't try to check 16065 // it now. 16066 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 16067 return BitWidth; 16068 16069 llvm::APSInt Value; 16070 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 16071 if (ICE.isInvalid()) 16072 return ICE; 16073 BitWidth = ICE.get(); 16074 16075 if (Value != 0 && ZeroWidth) 16076 *ZeroWidth = false; 16077 16078 // Zero-width bitfield is ok for anonymous field. 16079 if (Value == 0 && FieldName) 16080 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 16081 16082 if (Value.isSigned() && Value.isNegative()) { 16083 if (FieldName) 16084 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 16085 << FieldName << Value.toString(10); 16086 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 16087 << Value.toString(10); 16088 } 16089 16090 if (!FieldTy->isDependentType()) { 16091 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 16092 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 16093 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 16094 16095 // Over-wide bitfields are an error in C or when using the MSVC bitfield 16096 // ABI. 16097 bool CStdConstraintViolation = 16098 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 16099 bool MSBitfieldViolation = 16100 Value.ugt(TypeStorageSize) && 16101 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 16102 if (CStdConstraintViolation || MSBitfieldViolation) { 16103 unsigned DiagWidth = 16104 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 16105 if (FieldName) 16106 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 16107 << FieldName << (unsigned)Value.getZExtValue() 16108 << !CStdConstraintViolation << DiagWidth; 16109 16110 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) 16111 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation 16112 << DiagWidth; 16113 } 16114 16115 // Warn on types where the user might conceivably expect to get all 16116 // specified bits as value bits: that's all integral types other than 16117 // 'bool'. 16118 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) { 16119 if (FieldName) 16120 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 16121 << FieldName << (unsigned)Value.getZExtValue() 16122 << (unsigned)TypeWidth; 16123 else 16124 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width) 16125 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth; 16126 } 16127 } 16128 16129 return BitWidth; 16130 } 16131 16132 /// ActOnField - Each field of a C struct/union is passed into this in order 16133 /// to create a FieldDecl object for it. 16134 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 16135 Declarator &D, Expr *BitfieldWidth) { 16136 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 16137 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 16138 /*InitStyle=*/ICIS_NoInit, AS_public); 16139 return Res; 16140 } 16141 16142 /// HandleField - Analyze a field of a C struct or a C++ data member. 16143 /// 16144 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 16145 SourceLocation DeclStart, 16146 Declarator &D, Expr *BitWidth, 16147 InClassInitStyle InitStyle, 16148 AccessSpecifier AS) { 16149 if (D.isDecompositionDeclarator()) { 16150 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 16151 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 16152 << Decomp.getSourceRange(); 16153 return nullptr; 16154 } 16155 16156 IdentifierInfo *II = D.getIdentifier(); 16157 SourceLocation Loc = DeclStart; 16158 if (II) Loc = D.getIdentifierLoc(); 16159 16160 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16161 QualType T = TInfo->getType(); 16162 if (getLangOpts().CPlusPlus) { 16163 CheckExtraCXXDefaultArguments(D); 16164 16165 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 16166 UPPC_DataMemberType)) { 16167 D.setInvalidType(); 16168 T = Context.IntTy; 16169 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 16170 } 16171 } 16172 16173 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 16174 16175 if (D.getDeclSpec().isInlineSpecified()) 16176 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 16177 << getLangOpts().CPlusPlus17; 16178 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 16179 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 16180 diag::err_invalid_thread) 16181 << DeclSpec::getSpecifierName(TSCS); 16182 16183 // Check to see if this name was declared as a member previously 16184 NamedDecl *PrevDecl = nullptr; 16185 LookupResult Previous(*this, II, Loc, LookupMemberName, 16186 ForVisibleRedeclaration); 16187 LookupName(Previous, S); 16188 switch (Previous.getResultKind()) { 16189 case LookupResult::Found: 16190 case LookupResult::FoundUnresolvedValue: 16191 PrevDecl = Previous.getAsSingle<NamedDecl>(); 16192 break; 16193 16194 case LookupResult::FoundOverloaded: 16195 PrevDecl = Previous.getRepresentativeDecl(); 16196 break; 16197 16198 case LookupResult::NotFound: 16199 case LookupResult::NotFoundInCurrentInstantiation: 16200 case LookupResult::Ambiguous: 16201 break; 16202 } 16203 Previous.suppressDiagnostics(); 16204 16205 if (PrevDecl && PrevDecl->isTemplateParameter()) { 16206 // Maybe we will complain about the shadowed template parameter. 16207 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 16208 // Just pretend that we didn't see the previous declaration. 16209 PrevDecl = nullptr; 16210 } 16211 16212 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 16213 PrevDecl = nullptr; 16214 16215 bool Mutable 16216 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 16217 SourceLocation TSSL = D.getBeginLoc(); 16218 FieldDecl *NewFD 16219 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 16220 TSSL, AS, PrevDecl, &D); 16221 16222 if (NewFD->isInvalidDecl()) 16223 Record->setInvalidDecl(); 16224 16225 if (D.getDeclSpec().isModulePrivateSpecified()) 16226 NewFD->setModulePrivate(); 16227 16228 if (NewFD->isInvalidDecl() && PrevDecl) { 16229 // Don't introduce NewFD into scope; there's already something 16230 // with the same name in the same scope. 16231 } else if (II) { 16232 PushOnScopeChains(NewFD, S); 16233 } else 16234 Record->addDecl(NewFD); 16235 16236 return NewFD; 16237 } 16238 16239 /// Build a new FieldDecl and check its well-formedness. 16240 /// 16241 /// This routine builds a new FieldDecl given the fields name, type, 16242 /// record, etc. \p PrevDecl should refer to any previous declaration 16243 /// with the same name and in the same scope as the field to be 16244 /// created. 16245 /// 16246 /// \returns a new FieldDecl. 16247 /// 16248 /// \todo The Declarator argument is a hack. It will be removed once 16249 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 16250 TypeSourceInfo *TInfo, 16251 RecordDecl *Record, SourceLocation Loc, 16252 bool Mutable, Expr *BitWidth, 16253 InClassInitStyle InitStyle, 16254 SourceLocation TSSL, 16255 AccessSpecifier AS, NamedDecl *PrevDecl, 16256 Declarator *D) { 16257 IdentifierInfo *II = Name.getAsIdentifierInfo(); 16258 bool InvalidDecl = false; 16259 if (D) InvalidDecl = D->isInvalidType(); 16260 16261 // If we receive a broken type, recover by assuming 'int' and 16262 // marking this declaration as invalid. 16263 if (T.isNull()) { 16264 InvalidDecl = true; 16265 T = Context.IntTy; 16266 } 16267 16268 QualType EltTy = Context.getBaseElementType(T); 16269 if (!EltTy->isDependentType()) { 16270 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 16271 // Fields of incomplete type force their record to be invalid. 16272 Record->setInvalidDecl(); 16273 InvalidDecl = true; 16274 } else { 16275 NamedDecl *Def; 16276 EltTy->isIncompleteType(&Def); 16277 if (Def && Def->isInvalidDecl()) { 16278 Record->setInvalidDecl(); 16279 InvalidDecl = true; 16280 } 16281 } 16282 } 16283 16284 // TR 18037 does not allow fields to be declared with address space 16285 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() || 16286 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { 16287 Diag(Loc, diag::err_field_with_address_space); 16288 Record->setInvalidDecl(); 16289 InvalidDecl = true; 16290 } 16291 16292 if (LangOpts.OpenCL) { 16293 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 16294 // used as structure or union field: image, sampler, event or block types. 16295 if (T->isEventT() || T->isImageType() || T->isSamplerT() || 16296 T->isBlockPointerType()) { 16297 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 16298 Record->setInvalidDecl(); 16299 InvalidDecl = true; 16300 } 16301 // OpenCL v1.2 s6.9.c: bitfields are not supported. 16302 if (BitWidth) { 16303 Diag(Loc, diag::err_opencl_bitfields); 16304 InvalidDecl = true; 16305 } 16306 } 16307 16308 // Anonymous bit-fields cannot be cv-qualified (CWG 2229). 16309 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && 16310 T.hasQualifiers()) { 16311 InvalidDecl = true; 16312 Diag(Loc, diag::err_anon_bitfield_qualifiers); 16313 } 16314 16315 // C99 6.7.2.1p8: A member of a structure or union may have any type other 16316 // than a variably modified type. 16317 if (!InvalidDecl && T->isVariablyModifiedType()) { 16318 bool SizeIsNegative; 16319 llvm::APSInt Oversized; 16320 16321 TypeSourceInfo *FixedTInfo = 16322 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 16323 SizeIsNegative, 16324 Oversized); 16325 if (FixedTInfo) { 16326 Diag(Loc, diag::warn_illegal_constant_array_size); 16327 TInfo = FixedTInfo; 16328 T = FixedTInfo->getType(); 16329 } else { 16330 if (SizeIsNegative) 16331 Diag(Loc, diag::err_typecheck_negative_array_size); 16332 else if (Oversized.getBoolValue()) 16333 Diag(Loc, diag::err_array_too_large) 16334 << Oversized.toString(10); 16335 else 16336 Diag(Loc, diag::err_typecheck_field_variable_size); 16337 InvalidDecl = true; 16338 } 16339 } 16340 16341 // Fields can not have abstract class types 16342 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 16343 diag::err_abstract_type_in_decl, 16344 AbstractFieldType)) 16345 InvalidDecl = true; 16346 16347 bool ZeroWidth = false; 16348 if (InvalidDecl) 16349 BitWidth = nullptr; 16350 // If this is declared as a bit-field, check the bit-field. 16351 if (BitWidth) { 16352 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 16353 &ZeroWidth).get(); 16354 if (!BitWidth) { 16355 InvalidDecl = true; 16356 BitWidth = nullptr; 16357 ZeroWidth = false; 16358 } 16359 } 16360 16361 // Check that 'mutable' is consistent with the type of the declaration. 16362 if (!InvalidDecl && Mutable) { 16363 unsigned DiagID = 0; 16364 if (T->isReferenceType()) 16365 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 16366 : diag::err_mutable_reference; 16367 else if (T.isConstQualified()) 16368 DiagID = diag::err_mutable_const; 16369 16370 if (DiagID) { 16371 SourceLocation ErrLoc = Loc; 16372 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 16373 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 16374 Diag(ErrLoc, DiagID); 16375 if (DiagID != diag::ext_mutable_reference) { 16376 Mutable = false; 16377 InvalidDecl = true; 16378 } 16379 } 16380 } 16381 16382 // C++11 [class.union]p8 (DR1460): 16383 // At most one variant member of a union may have a 16384 // brace-or-equal-initializer. 16385 if (InitStyle != ICIS_NoInit) 16386 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 16387 16388 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 16389 BitWidth, Mutable, InitStyle); 16390 if (InvalidDecl) 16391 NewFD->setInvalidDecl(); 16392 16393 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 16394 Diag(Loc, diag::err_duplicate_member) << II; 16395 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 16396 NewFD->setInvalidDecl(); 16397 } 16398 16399 if (!InvalidDecl && getLangOpts().CPlusPlus) { 16400 if (Record->isUnion()) { 16401 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 16402 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 16403 if (RDecl->getDefinition()) { 16404 // C++ [class.union]p1: An object of a class with a non-trivial 16405 // constructor, a non-trivial copy constructor, a non-trivial 16406 // destructor, or a non-trivial copy assignment operator 16407 // cannot be a member of a union, nor can an array of such 16408 // objects. 16409 if (CheckNontrivialField(NewFD)) 16410 NewFD->setInvalidDecl(); 16411 } 16412 } 16413 16414 // C++ [class.union]p1: If a union contains a member of reference type, 16415 // the program is ill-formed, except when compiling with MSVC extensions 16416 // enabled. 16417 if (EltTy->isReferenceType()) { 16418 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 16419 diag::ext_union_member_of_reference_type : 16420 diag::err_union_member_of_reference_type) 16421 << NewFD->getDeclName() << EltTy; 16422 if (!getLangOpts().MicrosoftExt) 16423 NewFD->setInvalidDecl(); 16424 } 16425 } 16426 } 16427 16428 // FIXME: We need to pass in the attributes given an AST 16429 // representation, not a parser representation. 16430 if (D) { 16431 // FIXME: The current scope is almost... but not entirely... correct here. 16432 ProcessDeclAttributes(getCurScope(), NewFD, *D); 16433 16434 if (NewFD->hasAttrs()) 16435 CheckAlignasUnderalignment(NewFD); 16436 } 16437 16438 // In auto-retain/release, infer strong retension for fields of 16439 // retainable type. 16440 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 16441 NewFD->setInvalidDecl(); 16442 16443 if (T.isObjCGCWeak()) 16444 Diag(Loc, diag::warn_attribute_weak_on_field); 16445 16446 NewFD->setAccess(AS); 16447 return NewFD; 16448 } 16449 16450 bool Sema::CheckNontrivialField(FieldDecl *FD) { 16451 assert(FD); 16452 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 16453 16454 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 16455 return false; 16456 16457 QualType EltTy = Context.getBaseElementType(FD->getType()); 16458 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 16459 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 16460 if (RDecl->getDefinition()) { 16461 // We check for copy constructors before constructors 16462 // because otherwise we'll never get complaints about 16463 // copy constructors. 16464 16465 CXXSpecialMember member = CXXInvalid; 16466 // We're required to check for any non-trivial constructors. Since the 16467 // implicit default constructor is suppressed if there are any 16468 // user-declared constructors, we just need to check that there is a 16469 // trivial default constructor and a trivial copy constructor. (We don't 16470 // worry about move constructors here, since this is a C++98 check.) 16471 if (RDecl->hasNonTrivialCopyConstructor()) 16472 member = CXXCopyConstructor; 16473 else if (!RDecl->hasTrivialDefaultConstructor()) 16474 member = CXXDefaultConstructor; 16475 else if (RDecl->hasNonTrivialCopyAssignment()) 16476 member = CXXCopyAssignment; 16477 else if (RDecl->hasNonTrivialDestructor()) 16478 member = CXXDestructor; 16479 16480 if (member != CXXInvalid) { 16481 if (!getLangOpts().CPlusPlus11 && 16482 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 16483 // Objective-C++ ARC: it is an error to have a non-trivial field of 16484 // a union. However, system headers in Objective-C programs 16485 // occasionally have Objective-C lifetime objects within unions, 16486 // and rather than cause the program to fail, we make those 16487 // members unavailable. 16488 SourceLocation Loc = FD->getLocation(); 16489 if (getSourceManager().isInSystemHeader(Loc)) { 16490 if (!FD->hasAttr<UnavailableAttr>()) 16491 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 16492 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 16493 return false; 16494 } 16495 } 16496 16497 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 16498 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 16499 diag::err_illegal_union_or_anon_struct_member) 16500 << FD->getParent()->isUnion() << FD->getDeclName() << member; 16501 DiagnoseNontrivial(RDecl, member); 16502 return !getLangOpts().CPlusPlus11; 16503 } 16504 } 16505 } 16506 16507 return false; 16508 } 16509 16510 /// TranslateIvarVisibility - Translate visibility from a token ID to an 16511 /// AST enum value. 16512 static ObjCIvarDecl::AccessControl 16513 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 16514 switch (ivarVisibility) { 16515 default: llvm_unreachable("Unknown visitibility kind"); 16516 case tok::objc_private: return ObjCIvarDecl::Private; 16517 case tok::objc_public: return ObjCIvarDecl::Public; 16518 case tok::objc_protected: return ObjCIvarDecl::Protected; 16519 case tok::objc_package: return ObjCIvarDecl::Package; 16520 } 16521 } 16522 16523 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 16524 /// in order to create an IvarDecl object for it. 16525 Decl *Sema::ActOnIvar(Scope *S, 16526 SourceLocation DeclStart, 16527 Declarator &D, Expr *BitfieldWidth, 16528 tok::ObjCKeywordKind Visibility) { 16529 16530 IdentifierInfo *II = D.getIdentifier(); 16531 Expr *BitWidth = (Expr*)BitfieldWidth; 16532 SourceLocation Loc = DeclStart; 16533 if (II) Loc = D.getIdentifierLoc(); 16534 16535 // FIXME: Unnamed fields can be handled in various different ways, for 16536 // example, unnamed unions inject all members into the struct namespace! 16537 16538 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16539 QualType T = TInfo->getType(); 16540 16541 if (BitWidth) { 16542 // 6.7.2.1p3, 6.7.2.1p4 16543 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 16544 if (!BitWidth) 16545 D.setInvalidType(); 16546 } else { 16547 // Not a bitfield. 16548 16549 // validate II. 16550 16551 } 16552 if (T->isReferenceType()) { 16553 Diag(Loc, diag::err_ivar_reference_type); 16554 D.setInvalidType(); 16555 } 16556 // C99 6.7.2.1p8: A member of a structure or union may have any type other 16557 // than a variably modified type. 16558 else if (T->isVariablyModifiedType()) { 16559 Diag(Loc, diag::err_typecheck_ivar_variable_size); 16560 D.setInvalidType(); 16561 } 16562 16563 // Get the visibility (access control) for this ivar. 16564 ObjCIvarDecl::AccessControl ac = 16565 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 16566 : ObjCIvarDecl::None; 16567 // Must set ivar's DeclContext to its enclosing interface. 16568 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 16569 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 16570 return nullptr; 16571 ObjCContainerDecl *EnclosingContext; 16572 if (ObjCImplementationDecl *IMPDecl = 16573 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 16574 if (LangOpts.ObjCRuntime.isFragile()) { 16575 // Case of ivar declared in an implementation. Context is that of its class. 16576 EnclosingContext = IMPDecl->getClassInterface(); 16577 assert(EnclosingContext && "Implementation has no class interface!"); 16578 } 16579 else 16580 EnclosingContext = EnclosingDecl; 16581 } else { 16582 if (ObjCCategoryDecl *CDecl = 16583 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 16584 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 16585 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 16586 return nullptr; 16587 } 16588 } 16589 EnclosingContext = EnclosingDecl; 16590 } 16591 16592 // Construct the decl. 16593 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 16594 DeclStart, Loc, II, T, 16595 TInfo, ac, (Expr *)BitfieldWidth); 16596 16597 if (II) { 16598 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 16599 ForVisibleRedeclaration); 16600 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 16601 && !isa<TagDecl>(PrevDecl)) { 16602 Diag(Loc, diag::err_duplicate_member) << II; 16603 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 16604 NewID->setInvalidDecl(); 16605 } 16606 } 16607 16608 // Process attributes attached to the ivar. 16609 ProcessDeclAttributes(S, NewID, D); 16610 16611 if (D.isInvalidType()) 16612 NewID->setInvalidDecl(); 16613 16614 // In ARC, infer 'retaining' for ivars of retainable type. 16615 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 16616 NewID->setInvalidDecl(); 16617 16618 if (D.getDeclSpec().isModulePrivateSpecified()) 16619 NewID->setModulePrivate(); 16620 16621 if (II) { 16622 // FIXME: When interfaces are DeclContexts, we'll need to add 16623 // these to the interface. 16624 S->AddDecl(NewID); 16625 IdResolver.AddDecl(NewID); 16626 } 16627 16628 if (LangOpts.ObjCRuntime.isNonFragile() && 16629 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 16630 Diag(Loc, diag::warn_ivars_in_interface); 16631 16632 return NewID; 16633 } 16634 16635 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 16636 /// class and class extensions. For every class \@interface and class 16637 /// extension \@interface, if the last ivar is a bitfield of any type, 16638 /// then add an implicit `char :0` ivar to the end of that interface. 16639 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 16640 SmallVectorImpl<Decl *> &AllIvarDecls) { 16641 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 16642 return; 16643 16644 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 16645 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 16646 16647 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) 16648 return; 16649 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 16650 if (!ID) { 16651 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 16652 if (!CD->IsClassExtension()) 16653 return; 16654 } 16655 // No need to add this to end of @implementation. 16656 else 16657 return; 16658 } 16659 // All conditions are met. Add a new bitfield to the tail end of ivars. 16660 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 16661 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 16662 16663 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 16664 DeclLoc, DeclLoc, nullptr, 16665 Context.CharTy, 16666 Context.getTrivialTypeSourceInfo(Context.CharTy, 16667 DeclLoc), 16668 ObjCIvarDecl::Private, BW, 16669 true); 16670 AllIvarDecls.push_back(Ivar); 16671 } 16672 16673 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 16674 ArrayRef<Decl *> Fields, SourceLocation LBrac, 16675 SourceLocation RBrac, 16676 const ParsedAttributesView &Attrs) { 16677 assert(EnclosingDecl && "missing record or interface decl"); 16678 16679 // If this is an Objective-C @implementation or category and we have 16680 // new fields here we should reset the layout of the interface since 16681 // it will now change. 16682 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 16683 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 16684 switch (DC->getKind()) { 16685 default: break; 16686 case Decl::ObjCCategory: 16687 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 16688 break; 16689 case Decl::ObjCImplementation: 16690 Context. 16691 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 16692 break; 16693 } 16694 } 16695 16696 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 16697 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl); 16698 16699 // Start counting up the number of named members; make sure to include 16700 // members of anonymous structs and unions in the total. 16701 unsigned NumNamedMembers = 0; 16702 if (Record) { 16703 for (const auto *I : Record->decls()) { 16704 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 16705 if (IFD->getDeclName()) 16706 ++NumNamedMembers; 16707 } 16708 } 16709 16710 // Verify that all the fields are okay. 16711 SmallVector<FieldDecl*, 32> RecFields; 16712 16713 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 16714 i != end; ++i) { 16715 FieldDecl *FD = cast<FieldDecl>(*i); 16716 16717 // Get the type for the field. 16718 const Type *FDTy = FD->getType().getTypePtr(); 16719 16720 if (!FD->isAnonymousStructOrUnion()) { 16721 // Remember all fields written by the user. 16722 RecFields.push_back(FD); 16723 } 16724 16725 // If the field is already invalid for some reason, don't emit more 16726 // diagnostics about it. 16727 if (FD->isInvalidDecl()) { 16728 EnclosingDecl->setInvalidDecl(); 16729 continue; 16730 } 16731 16732 // C99 6.7.2.1p2: 16733 // A structure or union shall not contain a member with 16734 // incomplete or function type (hence, a structure shall not 16735 // contain an instance of itself, but may contain a pointer to 16736 // an instance of itself), except that the last member of a 16737 // structure with more than one named member may have incomplete 16738 // array type; such a structure (and any union containing, 16739 // possibly recursively, a member that is such a structure) 16740 // shall not be a member of a structure or an element of an 16741 // array. 16742 bool IsLastField = (i + 1 == Fields.end()); 16743 if (FDTy->isFunctionType()) { 16744 // Field declared as a function. 16745 Diag(FD->getLocation(), diag::err_field_declared_as_function) 16746 << FD->getDeclName(); 16747 FD->setInvalidDecl(); 16748 EnclosingDecl->setInvalidDecl(); 16749 continue; 16750 } else if (FDTy->isIncompleteArrayType() && 16751 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { 16752 if (Record) { 16753 // Flexible array member. 16754 // Microsoft and g++ is more permissive regarding flexible array. 16755 // It will accept flexible array in union and also 16756 // as the sole element of a struct/class. 16757 unsigned DiagID = 0; 16758 if (!Record->isUnion() && !IsLastField) { 16759 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) 16760 << FD->getDeclName() << FD->getType() << Record->getTagKind(); 16761 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); 16762 FD->setInvalidDecl(); 16763 EnclosingDecl->setInvalidDecl(); 16764 continue; 16765 } else if (Record->isUnion()) 16766 DiagID = getLangOpts().MicrosoftExt 16767 ? diag::ext_flexible_array_union_ms 16768 : getLangOpts().CPlusPlus 16769 ? diag::ext_flexible_array_union_gnu 16770 : diag::err_flexible_array_union; 16771 else if (NumNamedMembers < 1) 16772 DiagID = getLangOpts().MicrosoftExt 16773 ? diag::ext_flexible_array_empty_aggregate_ms 16774 : getLangOpts().CPlusPlus 16775 ? diag::ext_flexible_array_empty_aggregate_gnu 16776 : diag::err_flexible_array_empty_aggregate; 16777 16778 if (DiagID) 16779 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 16780 << Record->getTagKind(); 16781 // While the layout of types that contain virtual bases is not specified 16782 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 16783 // virtual bases after the derived members. This would make a flexible 16784 // array member declared at the end of an object not adjacent to the end 16785 // of the type. 16786 if (CXXRecord && CXXRecord->getNumVBases() != 0) 16787 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 16788 << FD->getDeclName() << Record->getTagKind(); 16789 if (!getLangOpts().C99) 16790 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 16791 << FD->getDeclName() << Record->getTagKind(); 16792 16793 // If the element type has a non-trivial destructor, we would not 16794 // implicitly destroy the elements, so disallow it for now. 16795 // 16796 // FIXME: GCC allows this. We should probably either implicitly delete 16797 // the destructor of the containing class, or just allow this. 16798 QualType BaseElem = Context.getBaseElementType(FD->getType()); 16799 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 16800 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 16801 << FD->getDeclName() << FD->getType(); 16802 FD->setInvalidDecl(); 16803 EnclosingDecl->setInvalidDecl(); 16804 continue; 16805 } 16806 // Okay, we have a legal flexible array member at the end of the struct. 16807 Record->setHasFlexibleArrayMember(true); 16808 } else { 16809 // In ObjCContainerDecl ivars with incomplete array type are accepted, 16810 // unless they are followed by another ivar. That check is done 16811 // elsewhere, after synthesized ivars are known. 16812 } 16813 } else if (!FDTy->isDependentType() && 16814 RequireCompleteType(FD->getLocation(), FD->getType(), 16815 diag::err_field_incomplete)) { 16816 // Incomplete type 16817 FD->setInvalidDecl(); 16818 EnclosingDecl->setInvalidDecl(); 16819 continue; 16820 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 16821 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 16822 // A type which contains a flexible array member is considered to be a 16823 // flexible array member. 16824 Record->setHasFlexibleArrayMember(true); 16825 if (!Record->isUnion()) { 16826 // If this is a struct/class and this is not the last element, reject 16827 // it. Note that GCC supports variable sized arrays in the middle of 16828 // structures. 16829 if (!IsLastField) 16830 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 16831 << FD->getDeclName() << FD->getType(); 16832 else { 16833 // We support flexible arrays at the end of structs in 16834 // other structs as an extension. 16835 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 16836 << FD->getDeclName(); 16837 } 16838 } 16839 } 16840 if (isa<ObjCContainerDecl>(EnclosingDecl) && 16841 RequireNonAbstractType(FD->getLocation(), FD->getType(), 16842 diag::err_abstract_type_in_decl, 16843 AbstractIvarType)) { 16844 // Ivars can not have abstract class types 16845 FD->setInvalidDecl(); 16846 } 16847 if (Record && FDTTy->getDecl()->hasObjectMember()) 16848 Record->setHasObjectMember(true); 16849 if (Record && FDTTy->getDecl()->hasVolatileMember()) 16850 Record->setHasVolatileMember(true); 16851 } else if (FDTy->isObjCObjectType()) { 16852 /// A field cannot be an Objective-c object 16853 Diag(FD->getLocation(), diag::err_statically_allocated_object) 16854 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 16855 QualType T = Context.getObjCObjectPointerType(FD->getType()); 16856 FD->setType(T); 16857 } else if (Record && Record->isUnion() && 16858 FD->getType().hasNonTrivialObjCLifetime() && 16859 getSourceManager().isInSystemHeader(FD->getLocation()) && 16860 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() && 16861 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong || 16862 !Context.hasDirectOwnershipQualifier(FD->getType()))) { 16863 // For backward compatibility, fields of C unions declared in system 16864 // headers that have non-trivial ObjC ownership qualifications are marked 16865 // as unavailable unless the qualifier is explicit and __strong. This can 16866 // break ABI compatibility between programs compiled with ARC and MRR, but 16867 // is a better option than rejecting programs using those unions under 16868 // ARC. 16869 FD->addAttr(UnavailableAttr::CreateImplicit( 16870 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, 16871 FD->getLocation())); 16872 } else if (getLangOpts().ObjC && 16873 getLangOpts().getGC() != LangOptions::NonGC && 16874 Record && !Record->hasObjectMember()) { 16875 if (FD->getType()->isObjCObjectPointerType() || 16876 FD->getType().isObjCGCStrong()) 16877 Record->setHasObjectMember(true); 16878 else if (Context.getAsArrayType(FD->getType())) { 16879 QualType BaseType = Context.getBaseElementType(FD->getType()); 16880 if (BaseType->isRecordType() && 16881 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember()) 16882 Record->setHasObjectMember(true); 16883 else if (BaseType->isObjCObjectPointerType() || 16884 BaseType.isObjCGCStrong()) 16885 Record->setHasObjectMember(true); 16886 } 16887 } 16888 16889 if (Record && !getLangOpts().CPlusPlus && 16890 !shouldIgnoreForRecordTriviality(FD)) { 16891 QualType FT = FD->getType(); 16892 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) { 16893 Record->setNonTrivialToPrimitiveDefaultInitialize(true); 16894 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 16895 Record->isUnion()) 16896 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true); 16897 } 16898 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); 16899 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) { 16900 Record->setNonTrivialToPrimitiveCopy(true); 16901 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion()) 16902 Record->setHasNonTrivialToPrimitiveCopyCUnion(true); 16903 } 16904 if (FT.isDestructedType()) { 16905 Record->setNonTrivialToPrimitiveDestroy(true); 16906 Record->setParamDestroyedInCallee(true); 16907 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion()) 16908 Record->setHasNonTrivialToPrimitiveDestructCUnion(true); 16909 } 16910 16911 if (const auto *RT = FT->getAs<RecordType>()) { 16912 if (RT->getDecl()->getArgPassingRestrictions() == 16913 RecordDecl::APK_CanNeverPassInRegs) 16914 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 16915 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) 16916 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 16917 } 16918 16919 if (Record && FD->getType().isVolatileQualified()) 16920 Record->setHasVolatileMember(true); 16921 // Keep track of the number of named members. 16922 if (FD->getIdentifier()) 16923 ++NumNamedMembers; 16924 } 16925 16926 // Okay, we successfully defined 'Record'. 16927 if (Record) { 16928 bool Completed = false; 16929 if (CXXRecord) { 16930 if (!CXXRecord->isInvalidDecl()) { 16931 // Set access bits correctly on the directly-declared conversions. 16932 for (CXXRecordDecl::conversion_iterator 16933 I = CXXRecord->conversion_begin(), 16934 E = CXXRecord->conversion_end(); I != E; ++I) 16935 I.setAccess((*I)->getAccess()); 16936 } 16937 16938 if (!CXXRecord->isDependentType()) { 16939 // Add any implicitly-declared members to this class. 16940 AddImplicitlyDeclaredMembersToClass(CXXRecord); 16941 16942 if (!CXXRecord->isInvalidDecl()) { 16943 // If we have virtual base classes, we may end up finding multiple 16944 // final overriders for a given virtual function. Check for this 16945 // problem now. 16946 if (CXXRecord->getNumVBases()) { 16947 CXXFinalOverriderMap FinalOverriders; 16948 CXXRecord->getFinalOverriders(FinalOverriders); 16949 16950 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 16951 MEnd = FinalOverriders.end(); 16952 M != MEnd; ++M) { 16953 for (OverridingMethods::iterator SO = M->second.begin(), 16954 SOEnd = M->second.end(); 16955 SO != SOEnd; ++SO) { 16956 assert(SO->second.size() > 0 && 16957 "Virtual function without overriding functions?"); 16958 if (SO->second.size() == 1) 16959 continue; 16960 16961 // C++ [class.virtual]p2: 16962 // In a derived class, if a virtual member function of a base 16963 // class subobject has more than one final overrider the 16964 // program is ill-formed. 16965 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 16966 << (const NamedDecl *)M->first << Record; 16967 Diag(M->first->getLocation(), 16968 diag::note_overridden_virtual_function); 16969 for (OverridingMethods::overriding_iterator 16970 OM = SO->second.begin(), 16971 OMEnd = SO->second.end(); 16972 OM != OMEnd; ++OM) 16973 Diag(OM->Method->getLocation(), diag::note_final_overrider) 16974 << (const NamedDecl *)M->first << OM->Method->getParent(); 16975 16976 Record->setInvalidDecl(); 16977 } 16978 } 16979 CXXRecord->completeDefinition(&FinalOverriders); 16980 Completed = true; 16981 } 16982 } 16983 } 16984 } 16985 16986 if (!Completed) 16987 Record->completeDefinition(); 16988 16989 // Handle attributes before checking the layout. 16990 ProcessDeclAttributeList(S, Record, Attrs); 16991 16992 // We may have deferred checking for a deleted destructor. Check now. 16993 if (CXXRecord) { 16994 auto *Dtor = CXXRecord->getDestructor(); 16995 if (Dtor && Dtor->isImplicit() && 16996 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { 16997 CXXRecord->setImplicitDestructorIsDeleted(); 16998 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 16999 } 17000 } 17001 17002 if (Record->hasAttrs()) { 17003 CheckAlignasUnderalignment(Record); 17004 17005 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 17006 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 17007 IA->getRange(), IA->getBestCase(), 17008 IA->getInheritanceModel()); 17009 } 17010 17011 // Check if the structure/union declaration is a type that can have zero 17012 // size in C. For C this is a language extension, for C++ it may cause 17013 // compatibility problems. 17014 bool CheckForZeroSize; 17015 if (!getLangOpts().CPlusPlus) { 17016 CheckForZeroSize = true; 17017 } else { 17018 // For C++ filter out types that cannot be referenced in C code. 17019 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 17020 CheckForZeroSize = 17021 CXXRecord->getLexicalDeclContext()->isExternCContext() && 17022 !CXXRecord->isDependentType() && 17023 CXXRecord->isCLike(); 17024 } 17025 if (CheckForZeroSize) { 17026 bool ZeroSize = true; 17027 bool IsEmpty = true; 17028 unsigned NonBitFields = 0; 17029 for (RecordDecl::field_iterator I = Record->field_begin(), 17030 E = Record->field_end(); 17031 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 17032 IsEmpty = false; 17033 if (I->isUnnamedBitfield()) { 17034 if (!I->isZeroLengthBitField(Context)) 17035 ZeroSize = false; 17036 } else { 17037 ++NonBitFields; 17038 QualType FieldType = I->getType(); 17039 if (FieldType->isIncompleteType() || 17040 !Context.getTypeSizeInChars(FieldType).isZero()) 17041 ZeroSize = false; 17042 } 17043 } 17044 17045 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 17046 // allowed in C++, but warn if its declaration is inside 17047 // extern "C" block. 17048 if (ZeroSize) { 17049 Diag(RecLoc, getLangOpts().CPlusPlus ? 17050 diag::warn_zero_size_struct_union_in_extern_c : 17051 diag::warn_zero_size_struct_union_compat) 17052 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 17053 } 17054 17055 // Structs without named members are extension in C (C99 6.7.2.1p7), 17056 // but are accepted by GCC. 17057 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 17058 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 17059 diag::ext_no_named_members_in_struct_union) 17060 << Record->isUnion(); 17061 } 17062 } 17063 } else { 17064 ObjCIvarDecl **ClsFields = 17065 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 17066 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 17067 ID->setEndOfDefinitionLoc(RBrac); 17068 // Add ivar's to class's DeclContext. 17069 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17070 ClsFields[i]->setLexicalDeclContext(ID); 17071 ID->addDecl(ClsFields[i]); 17072 } 17073 // Must enforce the rule that ivars in the base classes may not be 17074 // duplicates. 17075 if (ID->getSuperClass()) 17076 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 17077 } else if (ObjCImplementationDecl *IMPDecl = 17078 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 17079 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 17080 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 17081 // Ivar declared in @implementation never belongs to the implementation. 17082 // Only it is in implementation's lexical context. 17083 ClsFields[I]->setLexicalDeclContext(IMPDecl); 17084 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 17085 IMPDecl->setIvarLBraceLoc(LBrac); 17086 IMPDecl->setIvarRBraceLoc(RBrac); 17087 } else if (ObjCCategoryDecl *CDecl = 17088 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 17089 // case of ivars in class extension; all other cases have been 17090 // reported as errors elsewhere. 17091 // FIXME. Class extension does not have a LocEnd field. 17092 // CDecl->setLocEnd(RBrac); 17093 // Add ivar's to class extension's DeclContext. 17094 // Diagnose redeclaration of private ivars. 17095 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 17096 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17097 if (IDecl) { 17098 if (const ObjCIvarDecl *ClsIvar = 17099 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 17100 Diag(ClsFields[i]->getLocation(), 17101 diag::err_duplicate_ivar_declaration); 17102 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 17103 continue; 17104 } 17105 for (const auto *Ext : IDecl->known_extensions()) { 17106 if (const ObjCIvarDecl *ClsExtIvar 17107 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 17108 Diag(ClsFields[i]->getLocation(), 17109 diag::err_duplicate_ivar_declaration); 17110 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 17111 continue; 17112 } 17113 } 17114 } 17115 ClsFields[i]->setLexicalDeclContext(CDecl); 17116 CDecl->addDecl(ClsFields[i]); 17117 } 17118 CDecl->setIvarLBraceLoc(LBrac); 17119 CDecl->setIvarRBraceLoc(RBrac); 17120 } 17121 } 17122 } 17123 17124 /// Determine whether the given integral value is representable within 17125 /// the given type T. 17126 static bool isRepresentableIntegerValue(ASTContext &Context, 17127 llvm::APSInt &Value, 17128 QualType T) { 17129 assert((T->isIntegralType(Context) || T->isEnumeralType()) && 17130 "Integral type required!"); 17131 unsigned BitWidth = Context.getIntWidth(T); 17132 17133 if (Value.isUnsigned() || Value.isNonNegative()) { 17134 if (T->isSignedIntegerOrEnumerationType()) 17135 --BitWidth; 17136 return Value.getActiveBits() <= BitWidth; 17137 } 17138 return Value.getMinSignedBits() <= BitWidth; 17139 } 17140 17141 // Given an integral type, return the next larger integral type 17142 // (or a NULL type of no such type exists). 17143 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 17144 // FIXME: Int128/UInt128 support, which also needs to be introduced into 17145 // enum checking below. 17146 assert((T->isIntegralType(Context) || 17147 T->isEnumeralType()) && "Integral type required!"); 17148 const unsigned NumTypes = 4; 17149 QualType SignedIntegralTypes[NumTypes] = { 17150 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 17151 }; 17152 QualType UnsignedIntegralTypes[NumTypes] = { 17153 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 17154 Context.UnsignedLongLongTy 17155 }; 17156 17157 unsigned BitWidth = Context.getTypeSize(T); 17158 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 17159 : UnsignedIntegralTypes; 17160 for (unsigned I = 0; I != NumTypes; ++I) 17161 if (Context.getTypeSize(Types[I]) > BitWidth) 17162 return Types[I]; 17163 17164 return QualType(); 17165 } 17166 17167 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 17168 EnumConstantDecl *LastEnumConst, 17169 SourceLocation IdLoc, 17170 IdentifierInfo *Id, 17171 Expr *Val) { 17172 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 17173 llvm::APSInt EnumVal(IntWidth); 17174 QualType EltTy; 17175 17176 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 17177 Val = nullptr; 17178 17179 if (Val) 17180 Val = DefaultLvalueConversion(Val).get(); 17181 17182 if (Val) { 17183 if (Enum->isDependentType() || Val->isTypeDependent()) 17184 EltTy = Context.DependentTy; 17185 else { 17186 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) { 17187 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 17188 // constant-expression in the enumerator-definition shall be a converted 17189 // constant expression of the underlying type. 17190 EltTy = Enum->getIntegerType(); 17191 ExprResult Converted = 17192 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 17193 CCEK_Enumerator); 17194 if (Converted.isInvalid()) 17195 Val = nullptr; 17196 else 17197 Val = Converted.get(); 17198 } else if (!Val->isValueDependent() && 17199 !(Val = VerifyIntegerConstantExpression(Val, 17200 &EnumVal).get())) { 17201 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 17202 } else { 17203 if (Enum->isComplete()) { 17204 EltTy = Enum->getIntegerType(); 17205 17206 // In Obj-C and Microsoft mode, require the enumeration value to be 17207 // representable in the underlying type of the enumeration. In C++11, 17208 // we perform a non-narrowing conversion as part of converted constant 17209 // expression checking. 17210 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 17211 if (Context.getTargetInfo() 17212 .getTriple() 17213 .isWindowsMSVCEnvironment()) { 17214 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 17215 } else { 17216 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 17217 } 17218 } 17219 17220 // Cast to the underlying type. 17221 Val = ImpCastExprToType(Val, EltTy, 17222 EltTy->isBooleanType() ? CK_IntegralToBoolean 17223 : CK_IntegralCast) 17224 .get(); 17225 } else if (getLangOpts().CPlusPlus) { 17226 // C++11 [dcl.enum]p5: 17227 // If the underlying type is not fixed, the type of each enumerator 17228 // is the type of its initializing value: 17229 // - If an initializer is specified for an enumerator, the 17230 // initializing value has the same type as the expression. 17231 EltTy = Val->getType(); 17232 } else { 17233 // C99 6.7.2.2p2: 17234 // The expression that defines the value of an enumeration constant 17235 // shall be an integer constant expression that has a value 17236 // representable as an int. 17237 17238 // Complain if the value is not representable in an int. 17239 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 17240 Diag(IdLoc, diag::ext_enum_value_not_int) 17241 << EnumVal.toString(10) << Val->getSourceRange() 17242 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 17243 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 17244 // Force the type of the expression to 'int'. 17245 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 17246 } 17247 EltTy = Val->getType(); 17248 } 17249 } 17250 } 17251 } 17252 17253 if (!Val) { 17254 if (Enum->isDependentType()) 17255 EltTy = Context.DependentTy; 17256 else if (!LastEnumConst) { 17257 // C++0x [dcl.enum]p5: 17258 // If the underlying type is not fixed, the type of each enumerator 17259 // is the type of its initializing value: 17260 // - If no initializer is specified for the first enumerator, the 17261 // initializing value has an unspecified integral type. 17262 // 17263 // GCC uses 'int' for its unspecified integral type, as does 17264 // C99 6.7.2.2p3. 17265 if (Enum->isFixed()) { 17266 EltTy = Enum->getIntegerType(); 17267 } 17268 else { 17269 EltTy = Context.IntTy; 17270 } 17271 } else { 17272 // Assign the last value + 1. 17273 EnumVal = LastEnumConst->getInitVal(); 17274 ++EnumVal; 17275 EltTy = LastEnumConst->getType(); 17276 17277 // Check for overflow on increment. 17278 if (EnumVal < LastEnumConst->getInitVal()) { 17279 // C++0x [dcl.enum]p5: 17280 // If the underlying type is not fixed, the type of each enumerator 17281 // is the type of its initializing value: 17282 // 17283 // - Otherwise the type of the initializing value is the same as 17284 // the type of the initializing value of the preceding enumerator 17285 // unless the incremented value is not representable in that type, 17286 // in which case the type is an unspecified integral type 17287 // sufficient to contain the incremented value. If no such type 17288 // exists, the program is ill-formed. 17289 QualType T = getNextLargerIntegralType(Context, EltTy); 17290 if (T.isNull() || Enum->isFixed()) { 17291 // There is no integral type larger enough to represent this 17292 // value. Complain, then allow the value to wrap around. 17293 EnumVal = LastEnumConst->getInitVal(); 17294 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 17295 ++EnumVal; 17296 if (Enum->isFixed()) 17297 // When the underlying type is fixed, this is ill-formed. 17298 Diag(IdLoc, diag::err_enumerator_wrapped) 17299 << EnumVal.toString(10) 17300 << EltTy; 17301 else 17302 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 17303 << EnumVal.toString(10); 17304 } else { 17305 EltTy = T; 17306 } 17307 17308 // Retrieve the last enumerator's value, extent that type to the 17309 // type that is supposed to be large enough to represent the incremented 17310 // value, then increment. 17311 EnumVal = LastEnumConst->getInitVal(); 17312 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 17313 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 17314 ++EnumVal; 17315 17316 // If we're not in C++, diagnose the overflow of enumerator values, 17317 // which in C99 means that the enumerator value is not representable in 17318 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 17319 // permits enumerator values that are representable in some larger 17320 // integral type. 17321 if (!getLangOpts().CPlusPlus && !T.isNull()) 17322 Diag(IdLoc, diag::warn_enum_value_overflow); 17323 } else if (!getLangOpts().CPlusPlus && 17324 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 17325 // Enforce C99 6.7.2.2p2 even when we compute the next value. 17326 Diag(IdLoc, diag::ext_enum_value_not_int) 17327 << EnumVal.toString(10) << 1; 17328 } 17329 } 17330 } 17331 17332 if (!EltTy->isDependentType()) { 17333 // Make the enumerator value match the signedness and size of the 17334 // enumerator's type. 17335 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 17336 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 17337 } 17338 17339 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 17340 Val, EnumVal); 17341 } 17342 17343 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 17344 SourceLocation IILoc) { 17345 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 17346 !getLangOpts().CPlusPlus) 17347 return SkipBodyInfo(); 17348 17349 // We have an anonymous enum definition. Look up the first enumerator to 17350 // determine if we should merge the definition with an existing one and 17351 // skip the body. 17352 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 17353 forRedeclarationInCurContext()); 17354 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 17355 if (!PrevECD) 17356 return SkipBodyInfo(); 17357 17358 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 17359 NamedDecl *Hidden; 17360 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 17361 SkipBodyInfo Skip; 17362 Skip.Previous = Hidden; 17363 return Skip; 17364 } 17365 17366 return SkipBodyInfo(); 17367 } 17368 17369 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 17370 SourceLocation IdLoc, IdentifierInfo *Id, 17371 const ParsedAttributesView &Attrs, 17372 SourceLocation EqualLoc, Expr *Val) { 17373 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 17374 EnumConstantDecl *LastEnumConst = 17375 cast_or_null<EnumConstantDecl>(lastEnumConst); 17376 17377 // The scope passed in may not be a decl scope. Zip up the scope tree until 17378 // we find one that is. 17379 S = getNonFieldDeclScope(S); 17380 17381 // Verify that there isn't already something declared with this name in this 17382 // scope. 17383 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration); 17384 LookupName(R, S); 17385 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>(); 17386 17387 if (PrevDecl && PrevDecl->isTemplateParameter()) { 17388 // Maybe we will complain about the shadowed template parameter. 17389 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 17390 // Just pretend that we didn't see the previous declaration. 17391 PrevDecl = nullptr; 17392 } 17393 17394 // C++ [class.mem]p15: 17395 // If T is the name of a class, then each of the following shall have a name 17396 // different from T: 17397 // - every enumerator of every member of class T that is an unscoped 17398 // enumerated type 17399 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) 17400 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 17401 DeclarationNameInfo(Id, IdLoc)); 17402 17403 EnumConstantDecl *New = 17404 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 17405 if (!New) 17406 return nullptr; 17407 17408 if (PrevDecl) { 17409 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) { 17410 // Check for other kinds of shadowing not already handled. 17411 CheckShadow(New, PrevDecl, R); 17412 } 17413 17414 // When in C++, we may get a TagDecl with the same name; in this case the 17415 // enum constant will 'hide' the tag. 17416 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 17417 "Received TagDecl when not in C++!"); 17418 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 17419 if (isa<EnumConstantDecl>(PrevDecl)) 17420 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 17421 else 17422 Diag(IdLoc, diag::err_redefinition) << Id; 17423 notePreviousDefinition(PrevDecl, IdLoc); 17424 return nullptr; 17425 } 17426 } 17427 17428 // Process attributes. 17429 ProcessDeclAttributeList(S, New, Attrs); 17430 AddPragmaAttributes(S, New); 17431 17432 // Register this decl in the current scope stack. 17433 New->setAccess(TheEnumDecl->getAccess()); 17434 PushOnScopeChains(New, S); 17435 17436 ActOnDocumentableDecl(New); 17437 17438 return New; 17439 } 17440 17441 // Returns true when the enum initial expression does not trigger the 17442 // duplicate enum warning. A few common cases are exempted as follows: 17443 // Element2 = Element1 17444 // Element2 = Element1 + 1 17445 // Element2 = Element1 - 1 17446 // Where Element2 and Element1 are from the same enum. 17447 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 17448 Expr *InitExpr = ECD->getInitExpr(); 17449 if (!InitExpr) 17450 return true; 17451 InitExpr = InitExpr->IgnoreImpCasts(); 17452 17453 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 17454 if (!BO->isAdditiveOp()) 17455 return true; 17456 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 17457 if (!IL) 17458 return true; 17459 if (IL->getValue() != 1) 17460 return true; 17461 17462 InitExpr = BO->getLHS(); 17463 } 17464 17465 // This checks if the elements are from the same enum. 17466 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 17467 if (!DRE) 17468 return true; 17469 17470 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 17471 if (!EnumConstant) 17472 return true; 17473 17474 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 17475 Enum) 17476 return true; 17477 17478 return false; 17479 } 17480 17481 // Emits a warning when an element is implicitly set a value that 17482 // a previous element has already been set to. 17483 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 17484 EnumDecl *Enum, QualType EnumType) { 17485 // Avoid anonymous enums 17486 if (!Enum->getIdentifier()) 17487 return; 17488 17489 // Only check for small enums. 17490 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 17491 return; 17492 17493 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 17494 return; 17495 17496 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 17497 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; 17498 17499 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 17500 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap; 17501 17502 // Use int64_t as a key to avoid needing special handling for DenseMap keys. 17503 auto EnumConstantToKey = [](const EnumConstantDecl *D) { 17504 llvm::APSInt Val = D->getInitVal(); 17505 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); 17506 }; 17507 17508 DuplicatesVector DupVector; 17509 ValueToVectorMap EnumMap; 17510 17511 // Populate the EnumMap with all values represented by enum constants without 17512 // an initializer. 17513 for (auto *Element : Elements) { 17514 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); 17515 17516 // Null EnumConstantDecl means a previous diagnostic has been emitted for 17517 // this constant. Skip this enum since it may be ill-formed. 17518 if (!ECD) { 17519 return; 17520 } 17521 17522 // Constants with initalizers are handled in the next loop. 17523 if (ECD->getInitExpr()) 17524 continue; 17525 17526 // Duplicate values are handled in the next loop. 17527 EnumMap.insert({EnumConstantToKey(ECD), ECD}); 17528 } 17529 17530 if (EnumMap.size() == 0) 17531 return; 17532 17533 // Create vectors for any values that has duplicates. 17534 for (auto *Element : Elements) { 17535 // The last loop returned if any constant was null. 17536 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); 17537 if (!ValidDuplicateEnum(ECD, Enum)) 17538 continue; 17539 17540 auto Iter = EnumMap.find(EnumConstantToKey(ECD)); 17541 if (Iter == EnumMap.end()) 17542 continue; 17543 17544 DeclOrVector& Entry = Iter->second; 17545 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 17546 // Ensure constants are different. 17547 if (D == ECD) 17548 continue; 17549 17550 // Create new vector and push values onto it. 17551 auto Vec = std::make_unique<ECDVector>(); 17552 Vec->push_back(D); 17553 Vec->push_back(ECD); 17554 17555 // Update entry to point to the duplicates vector. 17556 Entry = Vec.get(); 17557 17558 // Store the vector somewhere we can consult later for quick emission of 17559 // diagnostics. 17560 DupVector.emplace_back(std::move(Vec)); 17561 continue; 17562 } 17563 17564 ECDVector *Vec = Entry.get<ECDVector*>(); 17565 // Make sure constants are not added more than once. 17566 if (*Vec->begin() == ECD) 17567 continue; 17568 17569 Vec->push_back(ECD); 17570 } 17571 17572 // Emit diagnostics. 17573 for (const auto &Vec : DupVector) { 17574 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 17575 17576 // Emit warning for one enum constant. 17577 auto *FirstECD = Vec->front(); 17578 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) 17579 << FirstECD << FirstECD->getInitVal().toString(10) 17580 << FirstECD->getSourceRange(); 17581 17582 // Emit one note for each of the remaining enum constants with 17583 // the same value. 17584 for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end())) 17585 S.Diag(ECD->getLocation(), diag::note_duplicate_element) 17586 << ECD << ECD->getInitVal().toString(10) 17587 << ECD->getSourceRange(); 17588 } 17589 } 17590 17591 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 17592 bool AllowMask) const { 17593 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 17594 assert(ED->isCompleteDefinition() && "expected enum definition"); 17595 17596 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 17597 llvm::APInt &FlagBits = R.first->second; 17598 17599 if (R.second) { 17600 for (auto *E : ED->enumerators()) { 17601 const auto &EVal = E->getInitVal(); 17602 // Only single-bit enumerators introduce new flag values. 17603 if (EVal.isPowerOf2()) 17604 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 17605 } 17606 } 17607 17608 // A value is in a flag enum if either its bits are a subset of the enum's 17609 // flag bits (the first condition) or we are allowing masks and the same is 17610 // true of its complement (the second condition). When masks are allowed, we 17611 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 17612 // 17613 // While it's true that any value could be used as a mask, the assumption is 17614 // that a mask will have all of the insignificant bits set. Anything else is 17615 // likely a logic error. 17616 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 17617 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 17618 } 17619 17620 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 17621 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S, 17622 const ParsedAttributesView &Attrs) { 17623 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 17624 QualType EnumType = Context.getTypeDeclType(Enum); 17625 17626 ProcessDeclAttributeList(S, Enum, Attrs); 17627 17628 if (Enum->isDependentType()) { 17629 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 17630 EnumConstantDecl *ECD = 17631 cast_or_null<EnumConstantDecl>(Elements[i]); 17632 if (!ECD) continue; 17633 17634 ECD->setType(EnumType); 17635 } 17636 17637 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 17638 return; 17639 } 17640 17641 // TODO: If the result value doesn't fit in an int, it must be a long or long 17642 // long value. ISO C does not support this, but GCC does as an extension, 17643 // emit a warning. 17644 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 17645 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 17646 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 17647 17648 // Verify that all the values are okay, compute the size of the values, and 17649 // reverse the list. 17650 unsigned NumNegativeBits = 0; 17651 unsigned NumPositiveBits = 0; 17652 17653 // Keep track of whether all elements have type int. 17654 bool AllElementsInt = true; 17655 17656 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 17657 EnumConstantDecl *ECD = 17658 cast_or_null<EnumConstantDecl>(Elements[i]); 17659 if (!ECD) continue; // Already issued a diagnostic. 17660 17661 const llvm::APSInt &InitVal = ECD->getInitVal(); 17662 17663 // Keep track of the size of positive and negative values. 17664 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 17665 NumPositiveBits = std::max(NumPositiveBits, 17666 (unsigned)InitVal.getActiveBits()); 17667 else 17668 NumNegativeBits = std::max(NumNegativeBits, 17669 (unsigned)InitVal.getMinSignedBits()); 17670 17671 // Keep track of whether every enum element has type int (very common). 17672 if (AllElementsInt) 17673 AllElementsInt = ECD->getType() == Context.IntTy; 17674 } 17675 17676 // Figure out the type that should be used for this enum. 17677 QualType BestType; 17678 unsigned BestWidth; 17679 17680 // C++0x N3000 [conv.prom]p3: 17681 // An rvalue of an unscoped enumeration type whose underlying 17682 // type is not fixed can be converted to an rvalue of the first 17683 // of the following types that can represent all the values of 17684 // the enumeration: int, unsigned int, long int, unsigned long 17685 // int, long long int, or unsigned long long int. 17686 // C99 6.4.4.3p2: 17687 // An identifier declared as an enumeration constant has type int. 17688 // The C99 rule is modified by a gcc extension 17689 QualType BestPromotionType; 17690 17691 bool Packed = Enum->hasAttr<PackedAttr>(); 17692 // -fshort-enums is the equivalent to specifying the packed attribute on all 17693 // enum definitions. 17694 if (LangOpts.ShortEnums) 17695 Packed = true; 17696 17697 // If the enum already has a type because it is fixed or dictated by the 17698 // target, promote that type instead of analyzing the enumerators. 17699 if (Enum->isComplete()) { 17700 BestType = Enum->getIntegerType(); 17701 if (BestType->isPromotableIntegerType()) 17702 BestPromotionType = Context.getPromotedIntegerType(BestType); 17703 else 17704 BestPromotionType = BestType; 17705 17706 BestWidth = Context.getIntWidth(BestType); 17707 } 17708 else if (NumNegativeBits) { 17709 // If there is a negative value, figure out the smallest integer type (of 17710 // int/long/longlong) that fits. 17711 // If it's packed, check also if it fits a char or a short. 17712 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 17713 BestType = Context.SignedCharTy; 17714 BestWidth = CharWidth; 17715 } else if (Packed && NumNegativeBits <= ShortWidth && 17716 NumPositiveBits < ShortWidth) { 17717 BestType = Context.ShortTy; 17718 BestWidth = ShortWidth; 17719 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 17720 BestType = Context.IntTy; 17721 BestWidth = IntWidth; 17722 } else { 17723 BestWidth = Context.getTargetInfo().getLongWidth(); 17724 17725 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 17726 BestType = Context.LongTy; 17727 } else { 17728 BestWidth = Context.getTargetInfo().getLongLongWidth(); 17729 17730 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 17731 Diag(Enum->getLocation(), diag::ext_enum_too_large); 17732 BestType = Context.LongLongTy; 17733 } 17734 } 17735 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 17736 } else { 17737 // If there is no negative value, figure out the smallest type that fits 17738 // all of the enumerator values. 17739 // If it's packed, check also if it fits a char or a short. 17740 if (Packed && NumPositiveBits <= CharWidth) { 17741 BestType = Context.UnsignedCharTy; 17742 BestPromotionType = Context.IntTy; 17743 BestWidth = CharWidth; 17744 } else if (Packed && NumPositiveBits <= ShortWidth) { 17745 BestType = Context.UnsignedShortTy; 17746 BestPromotionType = Context.IntTy; 17747 BestWidth = ShortWidth; 17748 } else if (NumPositiveBits <= IntWidth) { 17749 BestType = Context.UnsignedIntTy; 17750 BestWidth = IntWidth; 17751 BestPromotionType 17752 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 17753 ? Context.UnsignedIntTy : Context.IntTy; 17754 } else if (NumPositiveBits <= 17755 (BestWidth = Context.getTargetInfo().getLongWidth())) { 17756 BestType = Context.UnsignedLongTy; 17757 BestPromotionType 17758 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 17759 ? Context.UnsignedLongTy : Context.LongTy; 17760 } else { 17761 BestWidth = Context.getTargetInfo().getLongLongWidth(); 17762 assert(NumPositiveBits <= BestWidth && 17763 "How could an initializer get larger than ULL?"); 17764 BestType = Context.UnsignedLongLongTy; 17765 BestPromotionType 17766 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 17767 ? Context.UnsignedLongLongTy : Context.LongLongTy; 17768 } 17769 } 17770 17771 // Loop over all of the enumerator constants, changing their types to match 17772 // the type of the enum if needed. 17773 for (auto *D : Elements) { 17774 auto *ECD = cast_or_null<EnumConstantDecl>(D); 17775 if (!ECD) continue; // Already issued a diagnostic. 17776 17777 // Standard C says the enumerators have int type, but we allow, as an 17778 // extension, the enumerators to be larger than int size. If each 17779 // enumerator value fits in an int, type it as an int, otherwise type it the 17780 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 17781 // that X has type 'int', not 'unsigned'. 17782 17783 // Determine whether the value fits into an int. 17784 llvm::APSInt InitVal = ECD->getInitVal(); 17785 17786 // If it fits into an integer type, force it. Otherwise force it to match 17787 // the enum decl type. 17788 QualType NewTy; 17789 unsigned NewWidth; 17790 bool NewSign; 17791 if (!getLangOpts().CPlusPlus && 17792 !Enum->isFixed() && 17793 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 17794 NewTy = Context.IntTy; 17795 NewWidth = IntWidth; 17796 NewSign = true; 17797 } else if (ECD->getType() == BestType) { 17798 // Already the right type! 17799 if (getLangOpts().CPlusPlus) 17800 // C++ [dcl.enum]p4: Following the closing brace of an 17801 // enum-specifier, each enumerator has the type of its 17802 // enumeration. 17803 ECD->setType(EnumType); 17804 continue; 17805 } else { 17806 NewTy = BestType; 17807 NewWidth = BestWidth; 17808 NewSign = BestType->isSignedIntegerOrEnumerationType(); 17809 } 17810 17811 // Adjust the APSInt value. 17812 InitVal = InitVal.extOrTrunc(NewWidth); 17813 InitVal.setIsSigned(NewSign); 17814 ECD->setInitVal(InitVal); 17815 17816 // Adjust the Expr initializer and type. 17817 if (ECD->getInitExpr() && 17818 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 17819 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 17820 CK_IntegralCast, 17821 ECD->getInitExpr(), 17822 /*base paths*/ nullptr, 17823 VK_RValue)); 17824 if (getLangOpts().CPlusPlus) 17825 // C++ [dcl.enum]p4: Following the closing brace of an 17826 // enum-specifier, each enumerator has the type of its 17827 // enumeration. 17828 ECD->setType(EnumType); 17829 else 17830 ECD->setType(NewTy); 17831 } 17832 17833 Enum->completeDefinition(BestType, BestPromotionType, 17834 NumPositiveBits, NumNegativeBits); 17835 17836 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 17837 17838 if (Enum->isClosedFlag()) { 17839 for (Decl *D : Elements) { 17840 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 17841 if (!ECD) continue; // Already issued a diagnostic. 17842 17843 llvm::APSInt InitVal = ECD->getInitVal(); 17844 if (InitVal != 0 && !InitVal.isPowerOf2() && 17845 !IsValueInFlagEnum(Enum, InitVal, true)) 17846 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 17847 << ECD << Enum; 17848 } 17849 } 17850 17851 // Now that the enum type is defined, ensure it's not been underaligned. 17852 if (Enum->hasAttrs()) 17853 CheckAlignasUnderalignment(Enum); 17854 } 17855 17856 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 17857 SourceLocation StartLoc, 17858 SourceLocation EndLoc) { 17859 StringLiteral *AsmString = cast<StringLiteral>(expr); 17860 17861 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 17862 AsmString, StartLoc, 17863 EndLoc); 17864 CurContext->addDecl(New); 17865 return New; 17866 } 17867 17868 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 17869 IdentifierInfo* AliasName, 17870 SourceLocation PragmaLoc, 17871 SourceLocation NameLoc, 17872 SourceLocation AliasNameLoc) { 17873 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 17874 LookupOrdinaryName); 17875 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc), 17876 AttributeCommonInfo::AS_Pragma); 17877 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit( 17878 Context, AliasName->getName(), /*LiteralLabel=*/true, Info); 17879 17880 // If a declaration that: 17881 // 1) declares a function or a variable 17882 // 2) has external linkage 17883 // already exists, add a label attribute to it. 17884 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 17885 if (isDeclExternC(PrevDecl)) 17886 PrevDecl->addAttr(Attr); 17887 else 17888 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 17889 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 17890 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 17891 } else 17892 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 17893 } 17894 17895 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 17896 SourceLocation PragmaLoc, 17897 SourceLocation NameLoc) { 17898 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 17899 17900 if (PrevDecl) { 17901 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma)); 17902 } else { 17903 (void)WeakUndeclaredIdentifiers.insert( 17904 std::pair<IdentifierInfo*,WeakInfo> 17905 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 17906 } 17907 } 17908 17909 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 17910 IdentifierInfo* AliasName, 17911 SourceLocation PragmaLoc, 17912 SourceLocation NameLoc, 17913 SourceLocation AliasNameLoc) { 17914 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 17915 LookupOrdinaryName); 17916 WeakInfo W = WeakInfo(Name, NameLoc); 17917 17918 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 17919 if (!PrevDecl->hasAttr<AliasAttr>()) 17920 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 17921 DeclApplyPragmaWeak(TUScope, ND, W); 17922 } else { 17923 (void)WeakUndeclaredIdentifiers.insert( 17924 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 17925 } 17926 } 17927 17928 Decl *Sema::getObjCDeclContext() const { 17929 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 17930 } 17931 17932 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD) { 17933 // Templates are emitted when they're instantiated. 17934 if (FD->isDependentContext()) 17935 return FunctionEmissionStatus::TemplateDiscarded; 17936 17937 FunctionEmissionStatus OMPES = FunctionEmissionStatus::Unknown; 17938 if (LangOpts.OpenMPIsDevice) { 17939 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 17940 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 17941 if (DevTy.hasValue()) { 17942 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host) 17943 OMPES = FunctionEmissionStatus::OMPDiscarded; 17944 else if (DeviceKnownEmittedFns.count(FD) > 0) 17945 OMPES = FunctionEmissionStatus::Emitted; 17946 } 17947 } else if (LangOpts.OpenMP) { 17948 // In OpenMP 4.5 all the functions are host functions. 17949 if (LangOpts.OpenMP <= 45) { 17950 OMPES = FunctionEmissionStatus::Emitted; 17951 } else { 17952 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 17953 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 17954 // In OpenMP 5.0 or above, DevTy may be changed later by 17955 // #pragma omp declare target to(*) device_type(*). Therefore DevTy 17956 // having no value does not imply host. The emission status will be 17957 // checked again at the end of compilation unit. 17958 if (DevTy.hasValue()) { 17959 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) { 17960 OMPES = FunctionEmissionStatus::OMPDiscarded; 17961 } else if (DeviceKnownEmittedFns.count(FD) > 0) { 17962 OMPES = FunctionEmissionStatus::Emitted; 17963 } 17964 } 17965 } 17966 } 17967 if (OMPES == FunctionEmissionStatus::OMPDiscarded || 17968 (OMPES == FunctionEmissionStatus::Emitted && !LangOpts.CUDA)) 17969 return OMPES; 17970 17971 if (LangOpts.CUDA) { 17972 // When compiling for device, host functions are never emitted. Similarly, 17973 // when compiling for host, device and global functions are never emitted. 17974 // (Technically, we do emit a host-side stub for global functions, but this 17975 // doesn't count for our purposes here.) 17976 Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD); 17977 if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host) 17978 return FunctionEmissionStatus::CUDADiscarded; 17979 if (!LangOpts.CUDAIsDevice && 17980 (T == Sema::CFT_Device || T == Sema::CFT_Global)) 17981 return FunctionEmissionStatus::CUDADiscarded; 17982 17983 // Check whether this function is externally visible -- if so, it's 17984 // known-emitted. 17985 // 17986 // We have to check the GVA linkage of the function's *definition* -- if we 17987 // only have a declaration, we don't know whether or not the function will 17988 // be emitted, because (say) the definition could include "inline". 17989 FunctionDecl *Def = FD->getDefinition(); 17990 17991 if (Def && 17992 !isDiscardableGVALinkage(getASTContext().GetGVALinkageForFunction(Def)) 17993 && (!LangOpts.OpenMP || OMPES == FunctionEmissionStatus::Emitted)) 17994 return FunctionEmissionStatus::Emitted; 17995 } 17996 17997 // Otherwise, the function is known-emitted if it's in our set of 17998 // known-emitted functions. 17999 return (DeviceKnownEmittedFns.count(FD) > 0) 18000 ? FunctionEmissionStatus::Emitted 18001 : FunctionEmissionStatus::Unknown; 18002 } 18003 18004 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) { 18005 // Host-side references to a __global__ function refer to the stub, so the 18006 // function itself is never emitted and therefore should not be marked. 18007 // If we have host fn calls kernel fn calls host+device, the HD function 18008 // does not get instantiated on the host. We model this by omitting at the 18009 // call to the kernel from the callgraph. This ensures that, when compiling 18010 // for host, only HD functions actually called from the host get marked as 18011 // known-emitted. 18012 return LangOpts.CUDA && !LangOpts.CUDAIsDevice && 18013 IdentifyCUDATarget(Callee) == CFT_Global; 18014 } 18015