1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements semantic analysis for declarations. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "TypeLocBuilder.h" 14 #include "clang/AST/ASTConsumer.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/ASTLambda.h" 17 #include "clang/AST/CXXInheritance.h" 18 #include "clang/AST/CharUnits.h" 19 #include "clang/AST/CommentDiagnostic.h" 20 #include "clang/AST/DeclCXX.h" 21 #include "clang/AST/DeclObjC.h" 22 #include "clang/AST/DeclTemplate.h" 23 #include "clang/AST/EvaluatedExprVisitor.h" 24 #include "clang/AST/Expr.h" 25 #include "clang/AST/ExprCXX.h" 26 #include "clang/AST/NonTrivialTypeVisitor.h" 27 #include "clang/AST/StmtCXX.h" 28 #include "clang/Basic/Builtins.h" 29 #include "clang/Basic/PartialDiagnostic.h" 30 #include "clang/Basic/SourceManager.h" 31 #include "clang/Basic/TargetInfo.h" 32 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex 33 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 34 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex 35 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled() 36 #include "clang/Sema/CXXFieldCollector.h" 37 #include "clang/Sema/DeclSpec.h" 38 #include "clang/Sema/DelayedDiagnostic.h" 39 #include "clang/Sema/Initialization.h" 40 #include "clang/Sema/Lookup.h" 41 #include "clang/Sema/ParsedTemplate.h" 42 #include "clang/Sema/Scope.h" 43 #include "clang/Sema/ScopeInfo.h" 44 #include "clang/Sema/SemaInternal.h" 45 #include "clang/Sema/Template.h" 46 #include "llvm/ADT/SmallString.h" 47 #include "llvm/ADT/Triple.h" 48 #include <algorithm> 49 #include <cstring> 50 #include <functional> 51 #include <unordered_map> 52 53 using namespace clang; 54 using namespace sema; 55 56 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { 57 if (OwnedType) { 58 Decl *Group[2] = { OwnedType, Ptr }; 59 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); 60 } 61 62 return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); 63 } 64 65 namespace { 66 67 class TypeNameValidatorCCC final : public CorrectionCandidateCallback { 68 public: 69 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false, 70 bool AllowTemplates = false, 71 bool AllowNonTemplates = true) 72 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass), 73 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) { 74 WantExpressionKeywords = false; 75 WantCXXNamedCasts = false; 76 WantRemainingKeywords = false; 77 } 78 79 bool ValidateCandidate(const TypoCorrection &candidate) override { 80 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 81 if (!AllowInvalidDecl && ND->isInvalidDecl()) 82 return false; 83 84 if (getAsTypeTemplateDecl(ND)) 85 return AllowTemplates; 86 87 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 88 if (!IsType) 89 return false; 90 91 if (AllowNonTemplates) 92 return true; 93 94 // An injected-class-name of a class template (specialization) is valid 95 // as a template or as a non-template. 96 if (AllowTemplates) { 97 auto *RD = dyn_cast<CXXRecordDecl>(ND); 98 if (!RD || !RD->isInjectedClassName()) 99 return false; 100 RD = cast<CXXRecordDecl>(RD->getDeclContext()); 101 return RD->getDescribedClassTemplate() || 102 isa<ClassTemplateSpecializationDecl>(RD); 103 } 104 105 return false; 106 } 107 108 return !WantClassName && candidate.isKeyword(); 109 } 110 111 std::unique_ptr<CorrectionCandidateCallback> clone() override { 112 return std::make_unique<TypeNameValidatorCCC>(*this); 113 } 114 115 private: 116 bool AllowInvalidDecl; 117 bool WantClassName; 118 bool AllowTemplates; 119 bool AllowNonTemplates; 120 }; 121 122 } // end anonymous namespace 123 124 /// Determine whether the token kind starts a simple-type-specifier. 125 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { 126 switch (Kind) { 127 // FIXME: Take into account the current language when deciding whether a 128 // token kind is a valid type specifier 129 case tok::kw_short: 130 case tok::kw_long: 131 case tok::kw___int64: 132 case tok::kw___int128: 133 case tok::kw_signed: 134 case tok::kw_unsigned: 135 case tok::kw_void: 136 case tok::kw_char: 137 case tok::kw_int: 138 case tok::kw_half: 139 case tok::kw_float: 140 case tok::kw_double: 141 case tok::kw___bf16: 142 case tok::kw__Float16: 143 case tok::kw___float128: 144 case tok::kw_wchar_t: 145 case tok::kw_bool: 146 case tok::kw___underlying_type: 147 case tok::kw___auto_type: 148 return true; 149 150 case tok::annot_typename: 151 case tok::kw_char16_t: 152 case tok::kw_char32_t: 153 case tok::kw_typeof: 154 case tok::annot_decltype: 155 case tok::kw_decltype: 156 return getLangOpts().CPlusPlus; 157 158 case tok::kw_char8_t: 159 return getLangOpts().Char8; 160 161 default: 162 break; 163 } 164 165 return false; 166 } 167 168 namespace { 169 enum class UnqualifiedTypeNameLookupResult { 170 NotFound, 171 FoundNonType, 172 FoundType 173 }; 174 } // end anonymous namespace 175 176 /// Tries to perform unqualified lookup of the type decls in bases for 177 /// dependent class. 178 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a 179 /// type decl, \a FoundType if only type decls are found. 180 static UnqualifiedTypeNameLookupResult 181 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, 182 SourceLocation NameLoc, 183 const CXXRecordDecl *RD) { 184 if (!RD->hasDefinition()) 185 return UnqualifiedTypeNameLookupResult::NotFound; 186 // Look for type decls in base classes. 187 UnqualifiedTypeNameLookupResult FoundTypeDecl = 188 UnqualifiedTypeNameLookupResult::NotFound; 189 for (const auto &Base : RD->bases()) { 190 const CXXRecordDecl *BaseRD = nullptr; 191 if (auto *BaseTT = Base.getType()->getAs<TagType>()) 192 BaseRD = BaseTT->getAsCXXRecordDecl(); 193 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { 194 // Look for type decls in dependent base classes that have known primary 195 // templates. 196 if (!TST || !TST->isDependentType()) 197 continue; 198 auto *TD = TST->getTemplateName().getAsTemplateDecl(); 199 if (!TD) 200 continue; 201 if (auto *BasePrimaryTemplate = 202 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) { 203 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl()) 204 BaseRD = BasePrimaryTemplate; 205 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) { 206 if (const ClassTemplatePartialSpecializationDecl *PS = 207 CTD->findPartialSpecialization(Base.getType())) 208 if (PS->getCanonicalDecl() != RD->getCanonicalDecl()) 209 BaseRD = PS; 210 } 211 } 212 } 213 if (BaseRD) { 214 for (NamedDecl *ND : BaseRD->lookup(&II)) { 215 if (!isa<TypeDecl>(ND)) 216 return UnqualifiedTypeNameLookupResult::FoundNonType; 217 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 218 } 219 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { 220 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { 221 case UnqualifiedTypeNameLookupResult::FoundNonType: 222 return UnqualifiedTypeNameLookupResult::FoundNonType; 223 case UnqualifiedTypeNameLookupResult::FoundType: 224 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 225 break; 226 case UnqualifiedTypeNameLookupResult::NotFound: 227 break; 228 } 229 } 230 } 231 } 232 233 return FoundTypeDecl; 234 } 235 236 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, 237 const IdentifierInfo &II, 238 SourceLocation NameLoc) { 239 // Lookup in the parent class template context, if any. 240 const CXXRecordDecl *RD = nullptr; 241 UnqualifiedTypeNameLookupResult FoundTypeDecl = 242 UnqualifiedTypeNameLookupResult::NotFound; 243 for (DeclContext *DC = S.CurContext; 244 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; 245 DC = DC->getParent()) { 246 // Look for type decls in dependent base classes that have known primary 247 // templates. 248 RD = dyn_cast<CXXRecordDecl>(DC); 249 if (RD && RD->getDescribedClassTemplate()) 250 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); 251 } 252 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) 253 return nullptr; 254 255 // We found some types in dependent base classes. Recover as if the user 256 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the 257 // lookup during template instantiation. 258 S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II; 259 260 ASTContext &Context = S.Context; 261 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, 262 cast<Type>(Context.getRecordType(RD))); 263 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); 264 265 CXXScopeSpec SS; 266 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 267 268 TypeLocBuilder Builder; 269 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 270 DepTL.setNameLoc(NameLoc); 271 DepTL.setElaboratedKeywordLoc(SourceLocation()); 272 DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); 273 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 274 } 275 276 /// If the identifier refers to a type name within this scope, 277 /// return the declaration of that type. 278 /// 279 /// This routine performs ordinary name lookup of the identifier II 280 /// within the given scope, with optional C++ scope specifier SS, to 281 /// determine whether the name refers to a type. If so, returns an 282 /// opaque pointer (actually a QualType) corresponding to that 283 /// type. Otherwise, returns NULL. 284 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 285 Scope *S, CXXScopeSpec *SS, 286 bool isClassName, bool HasTrailingDot, 287 ParsedType ObjectTypePtr, 288 bool IsCtorOrDtorName, 289 bool WantNontrivialTypeSourceInfo, 290 bool IsClassTemplateDeductionContext, 291 IdentifierInfo **CorrectedII) { 292 // FIXME: Consider allowing this outside C++1z mode as an extension. 293 bool AllowDeducedTemplate = IsClassTemplateDeductionContext && 294 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName && 295 !isClassName && !HasTrailingDot; 296 297 // Determine where we will perform name lookup. 298 DeclContext *LookupCtx = nullptr; 299 if (ObjectTypePtr) { 300 QualType ObjectType = ObjectTypePtr.get(); 301 if (ObjectType->isRecordType()) 302 LookupCtx = computeDeclContext(ObjectType); 303 } else if (SS && SS->isNotEmpty()) { 304 LookupCtx = computeDeclContext(*SS, false); 305 306 if (!LookupCtx) { 307 if (isDependentScopeSpecifier(*SS)) { 308 // C++ [temp.res]p3: 309 // A qualified-id that refers to a type and in which the 310 // nested-name-specifier depends on a template-parameter (14.6.2) 311 // shall be prefixed by the keyword typename to indicate that the 312 // qualified-id denotes a type, forming an 313 // elaborated-type-specifier (7.1.5.3). 314 // 315 // We therefore do not perform any name lookup if the result would 316 // refer to a member of an unknown specialization. 317 if (!isClassName && !IsCtorOrDtorName) 318 return nullptr; 319 320 // We know from the grammar that this name refers to a type, 321 // so build a dependent node to describe the type. 322 if (WantNontrivialTypeSourceInfo) 323 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 324 325 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 326 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 327 II, NameLoc); 328 return ParsedType::make(T); 329 } 330 331 return nullptr; 332 } 333 334 if (!LookupCtx->isDependentContext() && 335 RequireCompleteDeclContext(*SS, LookupCtx)) 336 return nullptr; 337 } 338 339 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 340 // lookup for class-names. 341 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 342 LookupOrdinaryName; 343 LookupResult Result(*this, &II, NameLoc, Kind); 344 if (LookupCtx) { 345 // Perform "qualified" name lookup into the declaration context we 346 // computed, which is either the type of the base of a member access 347 // expression or the declaration context associated with a prior 348 // nested-name-specifier. 349 LookupQualifiedName(Result, LookupCtx); 350 351 if (ObjectTypePtr && Result.empty()) { 352 // C++ [basic.lookup.classref]p3: 353 // If the unqualified-id is ~type-name, the type-name is looked up 354 // in the context of the entire postfix-expression. If the type T of 355 // the object expression is of a class type C, the type-name is also 356 // looked up in the scope of class C. At least one of the lookups shall 357 // find a name that refers to (possibly cv-qualified) T. 358 LookupName(Result, S); 359 } 360 } else { 361 // Perform unqualified name lookup. 362 LookupName(Result, S); 363 364 // For unqualified lookup in a class template in MSVC mode, look into 365 // dependent base classes where the primary class template is known. 366 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { 367 if (ParsedType TypeInBase = 368 recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) 369 return TypeInBase; 370 } 371 } 372 373 NamedDecl *IIDecl = nullptr; 374 switch (Result.getResultKind()) { 375 case LookupResult::NotFound: 376 case LookupResult::NotFoundInCurrentInstantiation: 377 if (CorrectedII) { 378 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName, 379 AllowDeducedTemplate); 380 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind, 381 S, SS, CCC, CTK_ErrorRecovery); 382 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 383 TemplateTy Template; 384 bool MemberOfUnknownSpecialization; 385 UnqualifiedId TemplateName; 386 TemplateName.setIdentifier(NewII, NameLoc); 387 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 388 CXXScopeSpec NewSS, *NewSSPtr = SS; 389 if (SS && NNS) { 390 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 391 NewSSPtr = &NewSS; 392 } 393 if (Correction && (NNS || NewII != &II) && 394 // Ignore a correction to a template type as the to-be-corrected 395 // identifier is not a template (typo correction for template names 396 // is handled elsewhere). 397 !(getLangOpts().CPlusPlus && NewSSPtr && 398 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false, 399 Template, MemberOfUnknownSpecialization))) { 400 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 401 isClassName, HasTrailingDot, ObjectTypePtr, 402 IsCtorOrDtorName, 403 WantNontrivialTypeSourceInfo, 404 IsClassTemplateDeductionContext); 405 if (Ty) { 406 diagnoseTypo(Correction, 407 PDiag(diag::err_unknown_type_or_class_name_suggest) 408 << Result.getLookupName() << isClassName); 409 if (SS && NNS) 410 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 411 *CorrectedII = NewII; 412 return Ty; 413 } 414 } 415 } 416 // If typo correction failed or was not performed, fall through 417 LLVM_FALLTHROUGH; 418 case LookupResult::FoundOverloaded: 419 case LookupResult::FoundUnresolvedValue: 420 Result.suppressDiagnostics(); 421 return nullptr; 422 423 case LookupResult::Ambiguous: 424 // Recover from type-hiding ambiguities by hiding the type. We'll 425 // do the lookup again when looking for an object, and we can 426 // diagnose the error then. If we don't do this, then the error 427 // about hiding the type will be immediately followed by an error 428 // that only makes sense if the identifier was treated like a type. 429 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 430 Result.suppressDiagnostics(); 431 return nullptr; 432 } 433 434 // Look to see if we have a type anywhere in the list of results. 435 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 436 Res != ResEnd; ++Res) { 437 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) || 438 (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) { 439 if (!IIDecl || 440 (*Res)->getLocation().getRawEncoding() < 441 IIDecl->getLocation().getRawEncoding()) 442 IIDecl = *Res; 443 } 444 } 445 446 if (!IIDecl) { 447 // None of the entities we found is a type, so there is no way 448 // to even assume that the result is a type. In this case, don't 449 // complain about the ambiguity. The parser will either try to 450 // perform this lookup again (e.g., as an object name), which 451 // will produce the ambiguity, or will complain that it expected 452 // a type name. 453 Result.suppressDiagnostics(); 454 return nullptr; 455 } 456 457 // We found a type within the ambiguous lookup; diagnose the 458 // ambiguity and then return that type. This might be the right 459 // answer, or it might not be, but it suppresses any attempt to 460 // perform the name lookup again. 461 break; 462 463 case LookupResult::Found: 464 IIDecl = Result.getFoundDecl(); 465 break; 466 } 467 468 assert(IIDecl && "Didn't find decl"); 469 470 QualType T; 471 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 472 // C++ [class.qual]p2: A lookup that would find the injected-class-name 473 // instead names the constructors of the class, except when naming a class. 474 // This is ill-formed when we're not actually forming a ctor or dtor name. 475 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); 476 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD); 477 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD && 478 FoundRD->isInjectedClassName() && 479 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) 480 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor) 481 << &II << /*Type*/1; 482 483 DiagnoseUseOfDecl(IIDecl, NameLoc); 484 485 T = Context.getTypeDeclType(TD); 486 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); 487 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 488 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 489 if (!HasTrailingDot) 490 T = Context.getObjCInterfaceType(IDecl); 491 } else if (AllowDeducedTemplate) { 492 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) 493 T = Context.getDeducedTemplateSpecializationType(TemplateName(TD), 494 QualType(), false); 495 } 496 497 if (T.isNull()) { 498 // If it's not plausibly a type, suppress diagnostics. 499 Result.suppressDiagnostics(); 500 return nullptr; 501 } 502 503 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 504 // constructor or destructor name (in such a case, the scope specifier 505 // will be attached to the enclosing Expr or Decl node). 506 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName && 507 !isa<ObjCInterfaceDecl>(IIDecl)) { 508 if (WantNontrivialTypeSourceInfo) { 509 // Construct a type with type-source information. 510 TypeLocBuilder Builder; 511 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 512 513 T = getElaboratedType(ETK_None, *SS, T); 514 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 515 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 516 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 517 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 518 } else { 519 T = getElaboratedType(ETK_None, *SS, T); 520 } 521 } 522 523 return ParsedType::make(T); 524 } 525 526 // Builds a fake NNS for the given decl context. 527 static NestedNameSpecifier * 528 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { 529 for (;; DC = DC->getLookupParent()) { 530 DC = DC->getPrimaryContext(); 531 auto *ND = dyn_cast<NamespaceDecl>(DC); 532 if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) 533 return NestedNameSpecifier::Create(Context, nullptr, ND); 534 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) 535 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 536 RD->getTypeForDecl()); 537 else if (isa<TranslationUnitDecl>(DC)) 538 return NestedNameSpecifier::GlobalSpecifier(Context); 539 } 540 llvm_unreachable("something isn't in TU scope?"); 541 } 542 543 /// Find the parent class with dependent bases of the innermost enclosing method 544 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end 545 /// up allowing unqualified dependent type names at class-level, which MSVC 546 /// correctly rejects. 547 static const CXXRecordDecl * 548 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) { 549 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) { 550 DC = DC->getPrimaryContext(); 551 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 552 if (MD->getParent()->hasAnyDependentBases()) 553 return MD->getParent(); 554 } 555 return nullptr; 556 } 557 558 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II, 559 SourceLocation NameLoc, 560 bool IsTemplateTypeArg) { 561 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode"); 562 563 NestedNameSpecifier *NNS = nullptr; 564 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) { 565 // If we weren't able to parse a default template argument, delay lookup 566 // until instantiation time by making a non-dependent DependentTypeName. We 567 // pretend we saw a NestedNameSpecifier referring to the current scope, and 568 // lookup is retried. 569 // FIXME: This hurts our diagnostic quality, since we get errors like "no 570 // type named 'Foo' in 'current_namespace'" when the user didn't write any 571 // name specifiers. 572 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext); 573 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; 574 } else if (const CXXRecordDecl *RD = 575 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) { 576 // Build a DependentNameType that will perform lookup into RD at 577 // instantiation time. 578 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 579 RD->getTypeForDecl()); 580 581 // Diagnose that this identifier was undeclared, and retry the lookup during 582 // template instantiation. 583 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II 584 << RD; 585 } else { 586 // This is not a situation that we should recover from. 587 return ParsedType(); 588 } 589 590 QualType T = Context.getDependentNameType(ETK_None, NNS, &II); 591 592 // Build type location information. We synthesized the qualifier, so we have 593 // to build a fake NestedNameSpecifierLoc. 594 NestedNameSpecifierLocBuilder NNSLocBuilder; 595 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 596 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); 597 598 TypeLocBuilder Builder; 599 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 600 DepTL.setNameLoc(NameLoc); 601 DepTL.setElaboratedKeywordLoc(SourceLocation()); 602 DepTL.setQualifierLoc(QualifierLoc); 603 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 604 } 605 606 /// isTagName() - This method is called *for error recovery purposes only* 607 /// to determine if the specified name is a valid tag name ("struct foo"). If 608 /// so, this returns the TST for the tag corresponding to it (TST_enum, 609 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 610 /// cases in C where the user forgot to specify the tag. 611 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 612 // Do a tag name lookup in this scope. 613 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 614 LookupName(R, S, false); 615 R.suppressDiagnostics(); 616 if (R.getResultKind() == LookupResult::Found) 617 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 618 switch (TD->getTagKind()) { 619 case TTK_Struct: return DeclSpec::TST_struct; 620 case TTK_Interface: return DeclSpec::TST_interface; 621 case TTK_Union: return DeclSpec::TST_union; 622 case TTK_Class: return DeclSpec::TST_class; 623 case TTK_Enum: return DeclSpec::TST_enum; 624 } 625 } 626 627 return DeclSpec::TST_unspecified; 628 } 629 630 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 631 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 632 /// then downgrade the missing typename error to a warning. 633 /// This is needed for MSVC compatibility; Example: 634 /// @code 635 /// template<class T> class A { 636 /// public: 637 /// typedef int TYPE; 638 /// }; 639 /// template<class T> class B : public A<T> { 640 /// public: 641 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 642 /// }; 643 /// @endcode 644 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 645 if (CurContext->isRecord()) { 646 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) 647 return true; 648 649 const Type *Ty = SS->getScopeRep()->getAsType(); 650 651 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 652 for (const auto &Base : RD->bases()) 653 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 654 return true; 655 return S->isFunctionPrototypeScope(); 656 } 657 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 658 } 659 660 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 661 SourceLocation IILoc, 662 Scope *S, 663 CXXScopeSpec *SS, 664 ParsedType &SuggestedType, 665 bool IsTemplateName) { 666 // Don't report typename errors for editor placeholders. 667 if (II->isEditorPlaceholder()) 668 return; 669 // We don't have anything to suggest (yet). 670 SuggestedType = nullptr; 671 672 // There may have been a typo in the name of the type. Look up typo 673 // results, in case we have something that we can suggest. 674 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false, 675 /*AllowTemplates=*/IsTemplateName, 676 /*AllowNonTemplates=*/!IsTemplateName); 677 if (TypoCorrection Corrected = 678 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, 679 CCC, CTK_ErrorRecovery)) { 680 // FIXME: Support error recovery for the template-name case. 681 bool CanRecover = !IsTemplateName; 682 if (Corrected.isKeyword()) { 683 // We corrected to a keyword. 684 diagnoseTypo(Corrected, 685 PDiag(IsTemplateName ? diag::err_no_template_suggest 686 : diag::err_unknown_typename_suggest) 687 << II); 688 II = Corrected.getCorrectionAsIdentifierInfo(); 689 } else { 690 // We found a similarly-named type or interface; suggest that. 691 if (!SS || !SS->isSet()) { 692 diagnoseTypo(Corrected, 693 PDiag(IsTemplateName ? diag::err_no_template_suggest 694 : diag::err_unknown_typename_suggest) 695 << II, CanRecover); 696 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 697 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 698 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 699 II->getName().equals(CorrectedStr); 700 diagnoseTypo(Corrected, 701 PDiag(IsTemplateName 702 ? diag::err_no_member_template_suggest 703 : diag::err_unknown_nested_typename_suggest) 704 << II << DC << DroppedSpecifier << SS->getRange(), 705 CanRecover); 706 } else { 707 llvm_unreachable("could not have corrected a typo here"); 708 } 709 710 if (!CanRecover) 711 return; 712 713 CXXScopeSpec tmpSS; 714 if (Corrected.getCorrectionSpecifier()) 715 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 716 SourceRange(IILoc)); 717 // FIXME: Support class template argument deduction here. 718 SuggestedType = 719 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S, 720 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr, 721 /*IsCtorOrDtorName=*/false, 722 /*WantNontrivialTypeSourceInfo=*/true); 723 } 724 return; 725 } 726 727 if (getLangOpts().CPlusPlus && !IsTemplateName) { 728 // See if II is a class template that the user forgot to pass arguments to. 729 UnqualifiedId Name; 730 Name.setIdentifier(II, IILoc); 731 CXXScopeSpec EmptySS; 732 TemplateTy TemplateResult; 733 bool MemberOfUnknownSpecialization; 734 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 735 Name, nullptr, true, TemplateResult, 736 MemberOfUnknownSpecialization) == TNK_Type_template) { 737 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc); 738 return; 739 } 740 } 741 742 // FIXME: Should we move the logic that tries to recover from a missing tag 743 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 744 745 if (!SS || (!SS->isSet() && !SS->isInvalid())) 746 Diag(IILoc, IsTemplateName ? diag::err_no_template 747 : diag::err_unknown_typename) 748 << II; 749 else if (DeclContext *DC = computeDeclContext(*SS, false)) 750 Diag(IILoc, IsTemplateName ? diag::err_no_member_template 751 : diag::err_typename_nested_not_found) 752 << II << DC << SS->getRange(); 753 else if (isDependentScopeSpecifier(*SS)) { 754 unsigned DiagID = diag::err_typename_missing; 755 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 756 DiagID = diag::ext_typename_missing; 757 758 Diag(SS->getRange().getBegin(), DiagID) 759 << SS->getScopeRep() << II->getName() 760 << SourceRange(SS->getRange().getBegin(), IILoc) 761 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 762 SuggestedType = ActOnTypenameType(S, SourceLocation(), 763 *SS, *II, IILoc).get(); 764 } else { 765 assert(SS && SS->isInvalid() && 766 "Invalid scope specifier has already been diagnosed"); 767 } 768 } 769 770 /// Determine whether the given result set contains either a type name 771 /// or 772 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 773 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 774 NextToken.is(tok::less); 775 776 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 777 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 778 return true; 779 780 if (CheckTemplate && isa<TemplateDecl>(*I)) 781 return true; 782 } 783 784 return false; 785 } 786 787 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 788 Scope *S, CXXScopeSpec &SS, 789 IdentifierInfo *&Name, 790 SourceLocation NameLoc) { 791 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 792 SemaRef.LookupParsedName(R, S, &SS); 793 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 794 StringRef FixItTagName; 795 switch (Tag->getTagKind()) { 796 case TTK_Class: 797 FixItTagName = "class "; 798 break; 799 800 case TTK_Enum: 801 FixItTagName = "enum "; 802 break; 803 804 case TTK_Struct: 805 FixItTagName = "struct "; 806 break; 807 808 case TTK_Interface: 809 FixItTagName = "__interface "; 810 break; 811 812 case TTK_Union: 813 FixItTagName = "union "; 814 break; 815 } 816 817 StringRef TagName = FixItTagName.drop_back(); 818 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 819 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 820 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 821 822 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 823 I != IEnd; ++I) 824 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 825 << Name << TagName; 826 827 // Replace lookup results with just the tag decl. 828 Result.clear(Sema::LookupTagName); 829 SemaRef.LookupParsedName(Result, S, &SS); 830 return true; 831 } 832 833 return false; 834 } 835 836 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 837 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 838 QualType T, SourceLocation NameLoc) { 839 ASTContext &Context = S.Context; 840 841 TypeLocBuilder Builder; 842 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 843 844 T = S.getElaboratedType(ETK_None, SS, T); 845 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 846 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 847 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 848 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 849 } 850 851 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, 852 IdentifierInfo *&Name, 853 SourceLocation NameLoc, 854 const Token &NextToken, 855 CorrectionCandidateCallback *CCC) { 856 DeclarationNameInfo NameInfo(Name, NameLoc); 857 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 858 859 assert(NextToken.isNot(tok::coloncolon) && 860 "parse nested name specifiers before calling ClassifyName"); 861 if (getLangOpts().CPlusPlus && SS.isSet() && 862 isCurrentClassName(*Name, S, &SS)) { 863 // Per [class.qual]p2, this names the constructors of SS, not the 864 // injected-class-name. We don't have a classification for that. 865 // There's not much point caching this result, since the parser 866 // will reject it later. 867 return NameClassification::Unknown(); 868 } 869 870 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 871 LookupParsedName(Result, S, &SS, !CurMethod); 872 873 if (SS.isInvalid()) 874 return NameClassification::Error(); 875 876 // For unqualified lookup in a class template in MSVC mode, look into 877 // dependent base classes where the primary class template is known. 878 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { 879 if (ParsedType TypeInBase = 880 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) 881 return TypeInBase; 882 } 883 884 // Perform lookup for Objective-C instance variables (including automatically 885 // synthesized instance variables), if we're in an Objective-C method. 886 // FIXME: This lookup really, really needs to be folded in to the normal 887 // unqualified lookup mechanism. 888 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 889 DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name); 890 if (Ivar.isInvalid()) 891 return NameClassification::Error(); 892 if (Ivar.isUsable()) 893 return NameClassification::NonType(cast<NamedDecl>(Ivar.get())); 894 895 // We defer builtin creation until after ivar lookup inside ObjC methods. 896 if (Result.empty()) 897 LookupBuiltin(Result); 898 } 899 900 bool SecondTry = false; 901 bool IsFilteredTemplateName = false; 902 903 Corrected: 904 switch (Result.getResultKind()) { 905 case LookupResult::NotFound: 906 // If an unqualified-id is followed by a '(', then we have a function 907 // call. 908 if (SS.isEmpty() && NextToken.is(tok::l_paren)) { 909 // In C++, this is an ADL-only call. 910 // FIXME: Reference? 911 if (getLangOpts().CPlusPlus) 912 return NameClassification::UndeclaredNonType(); 913 914 // C90 6.3.2.2: 915 // If the expression that precedes the parenthesized argument list in a 916 // function call consists solely of an identifier, and if no 917 // declaration is visible for this identifier, the identifier is 918 // implicitly declared exactly as if, in the innermost block containing 919 // the function call, the declaration 920 // 921 // extern int identifier (); 922 // 923 // appeared. 924 // 925 // We also allow this in C99 as an extension. 926 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) 927 return NameClassification::NonType(D); 928 } 929 930 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) { 931 // In C++20 onwards, this could be an ADL-only call to a function 932 // template, and we're required to assume that this is a template name. 933 // 934 // FIXME: Find a way to still do typo correction in this case. 935 TemplateName Template = 936 Context.getAssumedTemplateName(NameInfo.getName()); 937 return NameClassification::UndeclaredTemplate(Template); 938 } 939 940 // In C, we first see whether there is a tag type by the same name, in 941 // which case it's likely that the user just forgot to write "enum", 942 // "struct", or "union". 943 if (!getLangOpts().CPlusPlus && !SecondTry && 944 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 945 break; 946 } 947 948 // Perform typo correction to determine if there is another name that is 949 // close to this name. 950 if (!SecondTry && CCC) { 951 SecondTry = true; 952 if (TypoCorrection Corrected = 953 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S, 954 &SS, *CCC, CTK_ErrorRecovery)) { 955 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 956 unsigned QualifiedDiag = diag::err_no_member_suggest; 957 958 NamedDecl *FirstDecl = Corrected.getFoundDecl(); 959 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); 960 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 961 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 962 UnqualifiedDiag = diag::err_no_template_suggest; 963 QualifiedDiag = diag::err_no_member_template_suggest; 964 } else if (UnderlyingFirstDecl && 965 (isa<TypeDecl>(UnderlyingFirstDecl) || 966 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 967 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 968 UnqualifiedDiag = diag::err_unknown_typename_suggest; 969 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 970 } 971 972 if (SS.isEmpty()) { 973 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 974 } else {// FIXME: is this even reachable? Test it. 975 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 976 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 977 Name->getName().equals(CorrectedStr); 978 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 979 << Name << computeDeclContext(SS, false) 980 << DroppedSpecifier << SS.getRange()); 981 } 982 983 // Update the name, so that the caller has the new name. 984 Name = Corrected.getCorrectionAsIdentifierInfo(); 985 986 // Typo correction corrected to a keyword. 987 if (Corrected.isKeyword()) 988 return Name; 989 990 // Also update the LookupResult... 991 // FIXME: This should probably go away at some point 992 Result.clear(); 993 Result.setLookupName(Corrected.getCorrection()); 994 if (FirstDecl) 995 Result.addDecl(FirstDecl); 996 997 // If we found an Objective-C instance variable, let 998 // LookupInObjCMethod build the appropriate expression to 999 // reference the ivar. 1000 // FIXME: This is a gross hack. 1001 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 1002 DeclResult R = 1003 LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier()); 1004 if (R.isInvalid()) 1005 return NameClassification::Error(); 1006 if (R.isUsable()) 1007 return NameClassification::NonType(Ivar); 1008 } 1009 1010 goto Corrected; 1011 } 1012 } 1013 1014 // We failed to correct; just fall through and let the parser deal with it. 1015 Result.suppressDiagnostics(); 1016 return NameClassification::Unknown(); 1017 1018 case LookupResult::NotFoundInCurrentInstantiation: { 1019 // We performed name lookup into the current instantiation, and there were 1020 // dependent bases, so we treat this result the same way as any other 1021 // dependent nested-name-specifier. 1022 1023 // C++ [temp.res]p2: 1024 // A name used in a template declaration or definition and that is 1025 // dependent on a template-parameter is assumed not to name a type 1026 // unless the applicable name lookup finds a type name or the name is 1027 // qualified by the keyword typename. 1028 // 1029 // FIXME: If the next token is '<', we might want to ask the parser to 1030 // perform some heroics to see if we actually have a 1031 // template-argument-list, which would indicate a missing 'template' 1032 // keyword here. 1033 return NameClassification::DependentNonType(); 1034 } 1035 1036 case LookupResult::Found: 1037 case LookupResult::FoundOverloaded: 1038 case LookupResult::FoundUnresolvedValue: 1039 break; 1040 1041 case LookupResult::Ambiguous: 1042 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1043 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true, 1044 /*AllowDependent=*/false)) { 1045 // C++ [temp.local]p3: 1046 // A lookup that finds an injected-class-name (10.2) can result in an 1047 // ambiguity in certain cases (for example, if it is found in more than 1048 // one base class). If all of the injected-class-names that are found 1049 // refer to specializations of the same class template, and if the name 1050 // is followed by a template-argument-list, the reference refers to the 1051 // class template itself and not a specialization thereof, and is not 1052 // ambiguous. 1053 // 1054 // This filtering can make an ambiguous result into an unambiguous one, 1055 // so try again after filtering out template names. 1056 FilterAcceptableTemplateNames(Result); 1057 if (!Result.isAmbiguous()) { 1058 IsFilteredTemplateName = true; 1059 break; 1060 } 1061 } 1062 1063 // Diagnose the ambiguity and return an error. 1064 return NameClassification::Error(); 1065 } 1066 1067 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1068 (IsFilteredTemplateName || 1069 hasAnyAcceptableTemplateNames( 1070 Result, /*AllowFunctionTemplates=*/true, 1071 /*AllowDependent=*/false, 1072 /*AllowNonTemplateFunctions*/ SS.isEmpty() && 1073 getLangOpts().CPlusPlus20))) { 1074 // C++ [temp.names]p3: 1075 // After name lookup (3.4) finds that a name is a template-name or that 1076 // an operator-function-id or a literal- operator-id refers to a set of 1077 // overloaded functions any member of which is a function template if 1078 // this is followed by a <, the < is always taken as the delimiter of a 1079 // template-argument-list and never as the less-than operator. 1080 // C++2a [temp.names]p2: 1081 // A name is also considered to refer to a template if it is an 1082 // unqualified-id followed by a < and name lookup finds either one 1083 // or more functions or finds nothing. 1084 if (!IsFilteredTemplateName) 1085 FilterAcceptableTemplateNames(Result); 1086 1087 bool IsFunctionTemplate; 1088 bool IsVarTemplate; 1089 TemplateName Template; 1090 if (Result.end() - Result.begin() > 1) { 1091 IsFunctionTemplate = true; 1092 Template = Context.getOverloadedTemplateName(Result.begin(), 1093 Result.end()); 1094 } else if (!Result.empty()) { 1095 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl( 1096 *Result.begin(), /*AllowFunctionTemplates=*/true, 1097 /*AllowDependent=*/false)); 1098 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 1099 IsVarTemplate = isa<VarTemplateDecl>(TD); 1100 1101 if (SS.isNotEmpty()) 1102 Template = 1103 Context.getQualifiedTemplateName(SS.getScopeRep(), 1104 /*TemplateKeyword=*/false, TD); 1105 else 1106 Template = TemplateName(TD); 1107 } else { 1108 // All results were non-template functions. This is a function template 1109 // name. 1110 IsFunctionTemplate = true; 1111 Template = Context.getAssumedTemplateName(NameInfo.getName()); 1112 } 1113 1114 if (IsFunctionTemplate) { 1115 // Function templates always go through overload resolution, at which 1116 // point we'll perform the various checks (e.g., accessibility) we need 1117 // to based on which function we selected. 1118 Result.suppressDiagnostics(); 1119 1120 return NameClassification::FunctionTemplate(Template); 1121 } 1122 1123 return IsVarTemplate ? NameClassification::VarTemplate(Template) 1124 : NameClassification::TypeTemplate(Template); 1125 } 1126 1127 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 1128 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 1129 DiagnoseUseOfDecl(Type, NameLoc); 1130 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 1131 QualType T = Context.getTypeDeclType(Type); 1132 if (SS.isNotEmpty()) 1133 return buildNestedType(*this, SS, T, NameLoc); 1134 return ParsedType::make(T); 1135 } 1136 1137 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 1138 if (!Class) { 1139 // FIXME: It's unfortunate that we don't have a Type node for handling this. 1140 if (ObjCCompatibleAliasDecl *Alias = 1141 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 1142 Class = Alias->getClassInterface(); 1143 } 1144 1145 if (Class) { 1146 DiagnoseUseOfDecl(Class, NameLoc); 1147 1148 if (NextToken.is(tok::period)) { 1149 // Interface. <something> is parsed as a property reference expression. 1150 // Just return "unknown" as a fall-through for now. 1151 Result.suppressDiagnostics(); 1152 return NameClassification::Unknown(); 1153 } 1154 1155 QualType T = Context.getObjCInterfaceType(Class); 1156 return ParsedType::make(T); 1157 } 1158 1159 if (isa<ConceptDecl>(FirstDecl)) 1160 return NameClassification::Concept( 1161 TemplateName(cast<TemplateDecl>(FirstDecl))); 1162 1163 // We can have a type template here if we're classifying a template argument. 1164 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) && 1165 !isa<VarTemplateDecl>(FirstDecl)) 1166 return NameClassification::TypeTemplate( 1167 TemplateName(cast<TemplateDecl>(FirstDecl))); 1168 1169 // Check for a tag type hidden by a non-type decl in a few cases where it 1170 // seems likely a type is wanted instead of the non-type that was found. 1171 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); 1172 if ((NextToken.is(tok::identifier) || 1173 (NextIsOp && 1174 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 1175 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 1176 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 1177 DiagnoseUseOfDecl(Type, NameLoc); 1178 QualType T = Context.getTypeDeclType(Type); 1179 if (SS.isNotEmpty()) 1180 return buildNestedType(*this, SS, T, NameLoc); 1181 return ParsedType::make(T); 1182 } 1183 1184 // FIXME: This is context-dependent. We need to defer building the member 1185 // expression until the classification is consumed. 1186 if (FirstDecl->isCXXClassMember()) 1187 return NameClassification::ContextIndependentExpr( 1188 BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, nullptr, 1189 S)); 1190 1191 // If we already know which single declaration is referenced, just annotate 1192 // that declaration directly. 1193 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1194 if (Result.isSingleResult() && !ADL) 1195 return NameClassification::NonType(Result.getRepresentativeDecl()); 1196 1197 // Build an UnresolvedLookupExpr. Note that this doesn't depend on the 1198 // context in which we performed classification, so it's safe to do now. 1199 return NameClassification::ContextIndependentExpr( 1200 BuildDeclarationNameExpr(SS, Result, ADL)); 1201 } 1202 1203 ExprResult 1204 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, 1205 SourceLocation NameLoc) { 1206 assert(getLangOpts().CPlusPlus && "ADL-only call in C?"); 1207 CXXScopeSpec SS; 1208 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 1209 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 1210 } 1211 1212 ExprResult 1213 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, 1214 IdentifierInfo *Name, 1215 SourceLocation NameLoc, 1216 bool IsAddressOfOperand) { 1217 DeclarationNameInfo NameInfo(Name, NameLoc); 1218 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 1219 NameInfo, IsAddressOfOperand, 1220 /*TemplateArgs=*/nullptr); 1221 } 1222 1223 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, 1224 NamedDecl *Found, 1225 SourceLocation NameLoc, 1226 const Token &NextToken) { 1227 if (getCurMethodDecl() && SS.isEmpty()) 1228 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl())) 1229 return BuildIvarRefExpr(S, NameLoc, Ivar); 1230 1231 // Reconstruct the lookup result. 1232 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName); 1233 Result.addDecl(Found); 1234 Result.resolveKind(); 1235 1236 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1237 return BuildDeclarationNameExpr(SS, Result, ADL); 1238 } 1239 1240 Sema::TemplateNameKindForDiagnostics 1241 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) { 1242 auto *TD = Name.getAsTemplateDecl(); 1243 if (!TD) 1244 return TemplateNameKindForDiagnostics::DependentTemplate; 1245 if (isa<ClassTemplateDecl>(TD)) 1246 return TemplateNameKindForDiagnostics::ClassTemplate; 1247 if (isa<FunctionTemplateDecl>(TD)) 1248 return TemplateNameKindForDiagnostics::FunctionTemplate; 1249 if (isa<VarTemplateDecl>(TD)) 1250 return TemplateNameKindForDiagnostics::VarTemplate; 1251 if (isa<TypeAliasTemplateDecl>(TD)) 1252 return TemplateNameKindForDiagnostics::AliasTemplate; 1253 if (isa<TemplateTemplateParmDecl>(TD)) 1254 return TemplateNameKindForDiagnostics::TemplateTemplateParam; 1255 if (isa<ConceptDecl>(TD)) 1256 return TemplateNameKindForDiagnostics::Concept; 1257 return TemplateNameKindForDiagnostics::DependentTemplate; 1258 } 1259 1260 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 1261 assert(DC->getLexicalParent() == CurContext && 1262 "The next DeclContext should be lexically contained in the current one."); 1263 CurContext = DC; 1264 S->setEntity(DC); 1265 } 1266 1267 void Sema::PopDeclContext() { 1268 assert(CurContext && "DeclContext imbalance!"); 1269 1270 CurContext = CurContext->getLexicalParent(); 1271 assert(CurContext && "Popped translation unit!"); 1272 } 1273 1274 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, 1275 Decl *D) { 1276 // Unlike PushDeclContext, the context to which we return is not necessarily 1277 // the containing DC of TD, because the new context will be some pre-existing 1278 // TagDecl definition instead of a fresh one. 1279 auto Result = static_cast<SkippedDefinitionContext>(CurContext); 1280 CurContext = cast<TagDecl>(D)->getDefinition(); 1281 assert(CurContext && "skipping definition of undefined tag"); 1282 // Start lookups from the parent of the current context; we don't want to look 1283 // into the pre-existing complete definition. 1284 S->setEntity(CurContext->getLookupParent()); 1285 return Result; 1286 } 1287 1288 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { 1289 CurContext = static_cast<decltype(CurContext)>(Context); 1290 } 1291 1292 /// EnterDeclaratorContext - Used when we must lookup names in the context 1293 /// of a declarator's nested name specifier. 1294 /// 1295 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1296 // C++0x [basic.lookup.unqual]p13: 1297 // A name used in the definition of a static data member of class 1298 // X (after the qualified-id of the static member) is looked up as 1299 // if the name was used in a member function of X. 1300 // C++0x [basic.lookup.unqual]p14: 1301 // If a variable member of a namespace is defined outside of the 1302 // scope of its namespace then any name used in the definition of 1303 // the variable member (after the declarator-id) is looked up as 1304 // if the definition of the variable member occurred in its 1305 // namespace. 1306 // Both of these imply that we should push a scope whose context 1307 // is the semantic context of the declaration. We can't use 1308 // PushDeclContext here because that context is not necessarily 1309 // lexically contained in the current context. Fortunately, 1310 // the containing scope should have the appropriate information. 1311 1312 assert(!S->getEntity() && "scope already has entity"); 1313 1314 #ifndef NDEBUG 1315 Scope *Ancestor = S->getParent(); 1316 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1317 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1318 #endif 1319 1320 CurContext = DC; 1321 S->setEntity(DC); 1322 1323 if (S->getParent()->isTemplateParamScope()) { 1324 // Also set the corresponding entities for all immediately-enclosing 1325 // template parameter scopes. 1326 EnterTemplatedContext(S->getParent(), DC); 1327 } 1328 } 1329 1330 void Sema::ExitDeclaratorContext(Scope *S) { 1331 assert(S->getEntity() == CurContext && "Context imbalance!"); 1332 1333 // Switch back to the lexical context. The safety of this is 1334 // enforced by an assert in EnterDeclaratorContext. 1335 Scope *Ancestor = S->getParent(); 1336 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1337 CurContext = Ancestor->getEntity(); 1338 1339 // We don't need to do anything with the scope, which is going to 1340 // disappear. 1341 } 1342 1343 void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) { 1344 assert(S->isTemplateParamScope() && 1345 "expected to be initializing a template parameter scope"); 1346 1347 // C++20 [temp.local]p7: 1348 // In the definition of a member of a class template that appears outside 1349 // of the class template definition, the name of a member of the class 1350 // template hides the name of a template-parameter of any enclosing class 1351 // templates (but not a template-parameter of the member if the member is a 1352 // class or function template). 1353 // C++20 [temp.local]p9: 1354 // In the definition of a class template or in the definition of a member 1355 // of such a template that appears outside of the template definition, for 1356 // each non-dependent base class (13.8.2.1), if the name of the base class 1357 // or the name of a member of the base class is the same as the name of a 1358 // template-parameter, the base class name or member name hides the 1359 // template-parameter name (6.4.10). 1360 // 1361 // This means that a template parameter scope should be searched immediately 1362 // after searching the DeclContext for which it is a template parameter 1363 // scope. For example, for 1364 // template<typename T> template<typename U> template<typename V> 1365 // void N::A<T>::B<U>::f(...) 1366 // we search V then B<U> (and base classes) then U then A<T> (and base 1367 // classes) then T then N then ::. 1368 unsigned ScopeDepth = getTemplateDepth(S); 1369 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) { 1370 DeclContext *SearchDCAfterScope = DC; 1371 for (; DC; DC = DC->getLookupParent()) { 1372 if (const TemplateParameterList *TPL = 1373 cast<Decl>(DC)->getDescribedTemplateParams()) { 1374 unsigned DCDepth = TPL->getDepth() + 1; 1375 if (DCDepth > ScopeDepth) 1376 continue; 1377 if (ScopeDepth == DCDepth) 1378 SearchDCAfterScope = DC = DC->getLookupParent(); 1379 break; 1380 } 1381 } 1382 S->setLookupEntity(SearchDCAfterScope); 1383 } 1384 } 1385 1386 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1387 // We assume that the caller has already called 1388 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1389 FunctionDecl *FD = D->getAsFunction(); 1390 if (!FD) 1391 return; 1392 1393 // Same implementation as PushDeclContext, but enters the context 1394 // from the lexical parent, rather than the top-level class. 1395 assert(CurContext == FD->getLexicalParent() && 1396 "The next DeclContext should be lexically contained in the current one."); 1397 CurContext = FD; 1398 S->setEntity(CurContext); 1399 1400 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1401 ParmVarDecl *Param = FD->getParamDecl(P); 1402 // If the parameter has an identifier, then add it to the scope 1403 if (Param->getIdentifier()) { 1404 S->AddDecl(Param); 1405 IdResolver.AddDecl(Param); 1406 } 1407 } 1408 } 1409 1410 void Sema::ActOnExitFunctionContext() { 1411 // Same implementation as PopDeclContext, but returns to the lexical parent, 1412 // rather than the top-level class. 1413 assert(CurContext && "DeclContext imbalance!"); 1414 CurContext = CurContext->getLexicalParent(); 1415 assert(CurContext && "Popped translation unit!"); 1416 } 1417 1418 /// Determine whether we allow overloading of the function 1419 /// PrevDecl with another declaration. 1420 /// 1421 /// This routine determines whether overloading is possible, not 1422 /// whether some new function is actually an overload. It will return 1423 /// true in C++ (where we can always provide overloads) or, as an 1424 /// extension, in C when the previous function is already an 1425 /// overloaded function declaration or has the "overloadable" 1426 /// attribute. 1427 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1428 ASTContext &Context, 1429 const FunctionDecl *New) { 1430 if (Context.getLangOpts().CPlusPlus) 1431 return true; 1432 1433 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1434 return true; 1435 1436 return Previous.getResultKind() == LookupResult::Found && 1437 (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() || 1438 New->hasAttr<OverloadableAttr>()); 1439 } 1440 1441 /// Add this decl to the scope shadowed decl chains. 1442 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1443 // Move up the scope chain until we find the nearest enclosing 1444 // non-transparent context. The declaration will be introduced into this 1445 // scope. 1446 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1447 S = S->getParent(); 1448 1449 // Add scoped declarations into their context, so that they can be 1450 // found later. Declarations without a context won't be inserted 1451 // into any context. 1452 if (AddToContext) 1453 CurContext->addDecl(D); 1454 1455 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1456 // are function-local declarations. 1457 if (getLangOpts().CPlusPlus && D->isOutOfLine() && 1458 !D->getDeclContext()->getRedeclContext()->Equals( 1459 D->getLexicalDeclContext()->getRedeclContext()) && 1460 !D->getLexicalDeclContext()->isFunctionOrMethod()) 1461 return; 1462 1463 // Template instantiations should also not be pushed into scope. 1464 if (isa<FunctionDecl>(D) && 1465 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1466 return; 1467 1468 // If this replaces anything in the current scope, 1469 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1470 IEnd = IdResolver.end(); 1471 for (; I != IEnd; ++I) { 1472 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1473 S->RemoveDecl(*I); 1474 IdResolver.RemoveDecl(*I); 1475 1476 // Should only need to replace one decl. 1477 break; 1478 } 1479 } 1480 1481 S->AddDecl(D); 1482 1483 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1484 // Implicitly-generated labels may end up getting generated in an order that 1485 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1486 // the label at the appropriate place in the identifier chain. 1487 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1488 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1489 if (IDC == CurContext) { 1490 if (!S->isDeclScope(*I)) 1491 continue; 1492 } else if (IDC->Encloses(CurContext)) 1493 break; 1494 } 1495 1496 IdResolver.InsertDeclAfter(I, D); 1497 } else { 1498 IdResolver.AddDecl(D); 1499 } 1500 } 1501 1502 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1503 bool AllowInlineNamespace) { 1504 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1505 } 1506 1507 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1508 DeclContext *TargetDC = DC->getPrimaryContext(); 1509 do { 1510 if (DeclContext *ScopeDC = S->getEntity()) 1511 if (ScopeDC->getPrimaryContext() == TargetDC) 1512 return S; 1513 } while ((S = S->getParent())); 1514 1515 return nullptr; 1516 } 1517 1518 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1519 DeclContext*, 1520 ASTContext&); 1521 1522 /// Filters out lookup results that don't fall within the given scope 1523 /// as determined by isDeclInScope. 1524 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1525 bool ConsiderLinkage, 1526 bool AllowInlineNamespace) { 1527 LookupResult::Filter F = R.makeFilter(); 1528 while (F.hasNext()) { 1529 NamedDecl *D = F.next(); 1530 1531 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1532 continue; 1533 1534 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1535 continue; 1536 1537 F.erase(); 1538 } 1539 1540 F.done(); 1541 } 1542 1543 /// We've determined that \p New is a redeclaration of \p Old. Check that they 1544 /// have compatible owning modules. 1545 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) { 1546 // FIXME: The Modules TS is not clear about how friend declarations are 1547 // to be treated. It's not meaningful to have different owning modules for 1548 // linkage in redeclarations of the same entity, so for now allow the 1549 // redeclaration and change the owning modules to match. 1550 if (New->getFriendObjectKind() && 1551 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) { 1552 New->setLocalOwningModule(Old->getOwningModule()); 1553 makeMergedDefinitionVisible(New); 1554 return false; 1555 } 1556 1557 Module *NewM = New->getOwningModule(); 1558 Module *OldM = Old->getOwningModule(); 1559 1560 if (NewM && NewM->Kind == Module::PrivateModuleFragment) 1561 NewM = NewM->Parent; 1562 if (OldM && OldM->Kind == Module::PrivateModuleFragment) 1563 OldM = OldM->Parent; 1564 1565 if (NewM == OldM) 1566 return false; 1567 1568 bool NewIsModuleInterface = NewM && NewM->isModulePurview(); 1569 bool OldIsModuleInterface = OldM && OldM->isModulePurview(); 1570 if (NewIsModuleInterface || OldIsModuleInterface) { 1571 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]: 1572 // if a declaration of D [...] appears in the purview of a module, all 1573 // other such declarations shall appear in the purview of the same module 1574 Diag(New->getLocation(), diag::err_mismatched_owning_module) 1575 << New 1576 << NewIsModuleInterface 1577 << (NewIsModuleInterface ? NewM->getFullModuleName() : "") 1578 << OldIsModuleInterface 1579 << (OldIsModuleInterface ? OldM->getFullModuleName() : ""); 1580 Diag(Old->getLocation(), diag::note_previous_declaration); 1581 New->setInvalidDecl(); 1582 return true; 1583 } 1584 1585 return false; 1586 } 1587 1588 static bool isUsingDecl(NamedDecl *D) { 1589 return isa<UsingShadowDecl>(D) || 1590 isa<UnresolvedUsingTypenameDecl>(D) || 1591 isa<UnresolvedUsingValueDecl>(D); 1592 } 1593 1594 /// Removes using shadow declarations from the lookup results. 1595 static void RemoveUsingDecls(LookupResult &R) { 1596 LookupResult::Filter F = R.makeFilter(); 1597 while (F.hasNext()) 1598 if (isUsingDecl(F.next())) 1599 F.erase(); 1600 1601 F.done(); 1602 } 1603 1604 /// Check for this common pattern: 1605 /// @code 1606 /// class S { 1607 /// S(const S&); // DO NOT IMPLEMENT 1608 /// void operator=(const S&); // DO NOT IMPLEMENT 1609 /// }; 1610 /// @endcode 1611 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1612 // FIXME: Should check for private access too but access is set after we get 1613 // the decl here. 1614 if (D->doesThisDeclarationHaveABody()) 1615 return false; 1616 1617 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1618 return CD->isCopyConstructor(); 1619 return D->isCopyAssignmentOperator(); 1620 } 1621 1622 // We need this to handle 1623 // 1624 // typedef struct { 1625 // void *foo() { return 0; } 1626 // } A; 1627 // 1628 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1629 // for example. If 'A', foo will have external linkage. If we have '*A', 1630 // foo will have no linkage. Since we can't know until we get to the end 1631 // of the typedef, this function finds out if D might have non-external linkage. 1632 // Callers should verify at the end of the TU if it D has external linkage or 1633 // not. 1634 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1635 const DeclContext *DC = D->getDeclContext(); 1636 while (!DC->isTranslationUnit()) { 1637 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1638 if (!RD->hasNameForLinkage()) 1639 return true; 1640 } 1641 DC = DC->getParent(); 1642 } 1643 1644 return !D->isExternallyVisible(); 1645 } 1646 1647 // FIXME: This needs to be refactored; some other isInMainFile users want 1648 // these semantics. 1649 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1650 if (S.TUKind != TU_Complete) 1651 return false; 1652 return S.SourceMgr.isInMainFile(Loc); 1653 } 1654 1655 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1656 assert(D); 1657 1658 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1659 return false; 1660 1661 // Ignore all entities declared within templates, and out-of-line definitions 1662 // of members of class templates. 1663 if (D->getDeclContext()->isDependentContext() || 1664 D->getLexicalDeclContext()->isDependentContext()) 1665 return false; 1666 1667 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1668 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1669 return false; 1670 // A non-out-of-line declaration of a member specialization was implicitly 1671 // instantiated; it's the out-of-line declaration that we're interested in. 1672 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1673 FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) 1674 return false; 1675 1676 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1677 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1678 return false; 1679 } else { 1680 // 'static inline' functions are defined in headers; don't warn. 1681 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1682 return false; 1683 } 1684 1685 if (FD->doesThisDeclarationHaveABody() && 1686 Context.DeclMustBeEmitted(FD)) 1687 return false; 1688 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1689 // Constants and utility variables are defined in headers with internal 1690 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1691 // like "inline".) 1692 if (!isMainFileLoc(*this, VD->getLocation())) 1693 return false; 1694 1695 if (Context.DeclMustBeEmitted(VD)) 1696 return false; 1697 1698 if (VD->isStaticDataMember() && 1699 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1700 return false; 1701 if (VD->isStaticDataMember() && 1702 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1703 VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) 1704 return false; 1705 1706 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) 1707 return false; 1708 } else { 1709 return false; 1710 } 1711 1712 // Only warn for unused decls internal to the translation unit. 1713 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1714 // for inline functions defined in the main source file, for instance. 1715 return mightHaveNonExternalLinkage(D); 1716 } 1717 1718 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1719 if (!D) 1720 return; 1721 1722 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1723 const FunctionDecl *First = FD->getFirstDecl(); 1724 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1725 return; // First should already be in the vector. 1726 } 1727 1728 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1729 const VarDecl *First = VD->getFirstDecl(); 1730 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1731 return; // First should already be in the vector. 1732 } 1733 1734 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1735 UnusedFileScopedDecls.push_back(D); 1736 } 1737 1738 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1739 if (D->isInvalidDecl()) 1740 return false; 1741 1742 bool Referenced = false; 1743 if (auto *DD = dyn_cast<DecompositionDecl>(D)) { 1744 // For a decomposition declaration, warn if none of the bindings are 1745 // referenced, instead of if the variable itself is referenced (which 1746 // it is, by the bindings' expressions). 1747 for (auto *BD : DD->bindings()) { 1748 if (BD->isReferenced()) { 1749 Referenced = true; 1750 break; 1751 } 1752 } 1753 } else if (!D->getDeclName()) { 1754 return false; 1755 } else if (D->isReferenced() || D->isUsed()) { 1756 Referenced = true; 1757 } 1758 1759 if (Referenced || D->hasAttr<UnusedAttr>() || 1760 D->hasAttr<ObjCPreciseLifetimeAttr>()) 1761 return false; 1762 1763 if (isa<LabelDecl>(D)) 1764 return true; 1765 1766 // Except for labels, we only care about unused decls that are local to 1767 // functions. 1768 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1769 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1770 // For dependent types, the diagnostic is deferred. 1771 WithinFunction = 1772 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1773 if (!WithinFunction) 1774 return false; 1775 1776 if (isa<TypedefNameDecl>(D)) 1777 return true; 1778 1779 // White-list anything that isn't a local variable. 1780 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1781 return false; 1782 1783 // Types of valid local variables should be complete, so this should succeed. 1784 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1785 1786 // White-list anything with an __attribute__((unused)) type. 1787 const auto *Ty = VD->getType().getTypePtr(); 1788 1789 // Only look at the outermost level of typedef. 1790 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1791 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1792 return false; 1793 } 1794 1795 // If we failed to complete the type for some reason, or if the type is 1796 // dependent, don't diagnose the variable. 1797 if (Ty->isIncompleteType() || Ty->isDependentType()) 1798 return false; 1799 1800 // Look at the element type to ensure that the warning behaviour is 1801 // consistent for both scalars and arrays. 1802 Ty = Ty->getBaseElementTypeUnsafe(); 1803 1804 if (const TagType *TT = Ty->getAs<TagType>()) { 1805 const TagDecl *Tag = TT->getDecl(); 1806 if (Tag->hasAttr<UnusedAttr>()) 1807 return false; 1808 1809 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1810 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1811 return false; 1812 1813 if (const Expr *Init = VD->getInit()) { 1814 if (const ExprWithCleanups *Cleanups = 1815 dyn_cast<ExprWithCleanups>(Init)) 1816 Init = Cleanups->getSubExpr(); 1817 const CXXConstructExpr *Construct = 1818 dyn_cast<CXXConstructExpr>(Init); 1819 if (Construct && !Construct->isElidable()) { 1820 CXXConstructorDecl *CD = Construct->getConstructor(); 1821 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() && 1822 (VD->getInit()->isValueDependent() || !VD->evaluateValue())) 1823 return false; 1824 } 1825 1826 // Suppress the warning if we don't know how this is constructed, and 1827 // it could possibly be non-trivial constructor. 1828 if (Init->isTypeDependent()) 1829 for (const CXXConstructorDecl *Ctor : RD->ctors()) 1830 if (!Ctor->isTrivial()) 1831 return false; 1832 } 1833 } 1834 } 1835 1836 // TODO: __attribute__((unused)) templates? 1837 } 1838 1839 return true; 1840 } 1841 1842 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1843 FixItHint &Hint) { 1844 if (isa<LabelDecl>(D)) { 1845 SourceLocation AfterColon = Lexer::findLocationAfterToken( 1846 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), 1847 true); 1848 if (AfterColon.isInvalid()) 1849 return; 1850 Hint = FixItHint::CreateRemoval( 1851 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon)); 1852 } 1853 } 1854 1855 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1856 if (D->getTypeForDecl()->isDependentType()) 1857 return; 1858 1859 for (auto *TmpD : D->decls()) { 1860 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1861 DiagnoseUnusedDecl(T); 1862 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1863 DiagnoseUnusedNestedTypedefs(R); 1864 } 1865 } 1866 1867 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1868 /// unless they are marked attr(unused). 1869 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1870 if (!ShouldDiagnoseUnusedDecl(D)) 1871 return; 1872 1873 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1874 // typedefs can be referenced later on, so the diagnostics are emitted 1875 // at end-of-translation-unit. 1876 UnusedLocalTypedefNameCandidates.insert(TD); 1877 return; 1878 } 1879 1880 FixItHint Hint; 1881 GenerateFixForUnusedDecl(D, Context, Hint); 1882 1883 unsigned DiagID; 1884 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1885 DiagID = diag::warn_unused_exception_param; 1886 else if (isa<LabelDecl>(D)) 1887 DiagID = diag::warn_unused_label; 1888 else 1889 DiagID = diag::warn_unused_variable; 1890 1891 Diag(D->getLocation(), DiagID) << D << Hint; 1892 } 1893 1894 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1895 // Verify that we have no forward references left. If so, there was a goto 1896 // or address of a label taken, but no definition of it. Label fwd 1897 // definitions are indicated with a null substmt which is also not a resolved 1898 // MS inline assembly label name. 1899 bool Diagnose = false; 1900 if (L->isMSAsmLabel()) 1901 Diagnose = !L->isResolvedMSAsmLabel(); 1902 else 1903 Diagnose = L->getStmt() == nullptr; 1904 if (Diagnose) 1905 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1906 } 1907 1908 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1909 S->mergeNRVOIntoParent(); 1910 1911 if (S->decl_empty()) return; 1912 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1913 "Scope shouldn't contain decls!"); 1914 1915 for (auto *TmpD : S->decls()) { 1916 assert(TmpD && "This decl didn't get pushed??"); 1917 1918 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1919 NamedDecl *D = cast<NamedDecl>(TmpD); 1920 1921 // Diagnose unused variables in this scope. 1922 if (!S->hasUnrecoverableErrorOccurred()) { 1923 DiagnoseUnusedDecl(D); 1924 if (const auto *RD = dyn_cast<RecordDecl>(D)) 1925 DiagnoseUnusedNestedTypedefs(RD); 1926 } 1927 1928 if (!D->getDeclName()) continue; 1929 1930 // If this was a forward reference to a label, verify it was defined. 1931 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1932 CheckPoppedLabel(LD, *this); 1933 1934 // Remove this name from our lexical scope, and warn on it if we haven't 1935 // already. 1936 IdResolver.RemoveDecl(D); 1937 auto ShadowI = ShadowingDecls.find(D); 1938 if (ShadowI != ShadowingDecls.end()) { 1939 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { 1940 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) 1941 << D << FD << FD->getParent(); 1942 Diag(FD->getLocation(), diag::note_previous_declaration); 1943 } 1944 ShadowingDecls.erase(ShadowI); 1945 } 1946 } 1947 } 1948 1949 /// Look for an Objective-C class in the translation unit. 1950 /// 1951 /// \param Id The name of the Objective-C class we're looking for. If 1952 /// typo-correction fixes this name, the Id will be updated 1953 /// to the fixed name. 1954 /// 1955 /// \param IdLoc The location of the name in the translation unit. 1956 /// 1957 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1958 /// if there is no class with the given name. 1959 /// 1960 /// \returns The declaration of the named Objective-C class, or NULL if the 1961 /// class could not be found. 1962 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1963 SourceLocation IdLoc, 1964 bool DoTypoCorrection) { 1965 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1966 // creation from this context. 1967 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1968 1969 if (!IDecl && DoTypoCorrection) { 1970 // Perform typo correction at the given location, but only if we 1971 // find an Objective-C class name. 1972 DeclFilterCCC<ObjCInterfaceDecl> CCC{}; 1973 if (TypoCorrection C = 1974 CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, 1975 TUScope, nullptr, CCC, CTK_ErrorRecovery)) { 1976 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1977 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1978 Id = IDecl->getIdentifier(); 1979 } 1980 } 1981 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1982 // This routine must always return a class definition, if any. 1983 if (Def && Def->getDefinition()) 1984 Def = Def->getDefinition(); 1985 return Def; 1986 } 1987 1988 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 1989 /// from S, where a non-field would be declared. This routine copes 1990 /// with the difference between C and C++ scoping rules in structs and 1991 /// unions. For example, the following code is well-formed in C but 1992 /// ill-formed in C++: 1993 /// @code 1994 /// struct S6 { 1995 /// enum { BAR } e; 1996 /// }; 1997 /// 1998 /// void test_S6() { 1999 /// struct S6 a; 2000 /// a.e = BAR; 2001 /// } 2002 /// @endcode 2003 /// For the declaration of BAR, this routine will return a different 2004 /// scope. The scope S will be the scope of the unnamed enumeration 2005 /// within S6. In C++, this routine will return the scope associated 2006 /// with S6, because the enumeration's scope is a transparent 2007 /// context but structures can contain non-field names. In C, this 2008 /// routine will return the translation unit scope, since the 2009 /// enumeration's scope is a transparent context and structures cannot 2010 /// contain non-field names. 2011 Scope *Sema::getNonFieldDeclScope(Scope *S) { 2012 while (((S->getFlags() & Scope::DeclScope) == 0) || 2013 (S->getEntity() && S->getEntity()->isTransparentContext()) || 2014 (S->isClassScope() && !getLangOpts().CPlusPlus)) 2015 S = S->getParent(); 2016 return S; 2017 } 2018 2019 /// Looks up the declaration of "struct objc_super" and 2020 /// saves it for later use in building builtin declaration of 2021 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such 2022 /// pre-existing declaration exists no action takes place. 2023 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, 2024 IdentifierInfo *II) { 2025 if (!II->isStr("objc_msgSendSuper")) 2026 return; 2027 ASTContext &Context = ThisSema.Context; 2028 2029 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), 2030 SourceLocation(), Sema::LookupTagName); 2031 ThisSema.LookupName(Result, S); 2032 if (Result.getResultKind() == LookupResult::Found) 2033 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 2034 Context.setObjCSuperType(Context.getTagDeclType(TD)); 2035 } 2036 2037 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, 2038 ASTContext::GetBuiltinTypeError Error) { 2039 switch (Error) { 2040 case ASTContext::GE_None: 2041 return ""; 2042 case ASTContext::GE_Missing_type: 2043 return BuiltinInfo.getHeaderName(ID); 2044 case ASTContext::GE_Missing_stdio: 2045 return "stdio.h"; 2046 case ASTContext::GE_Missing_setjmp: 2047 return "setjmp.h"; 2048 case ASTContext::GE_Missing_ucontext: 2049 return "ucontext.h"; 2050 } 2051 llvm_unreachable("unhandled error kind"); 2052 } 2053 2054 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 2055 /// file scope. lazily create a decl for it. ForRedeclaration is true 2056 /// if we're creating this built-in in anticipation of redeclaring the 2057 /// built-in. 2058 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 2059 Scope *S, bool ForRedeclaration, 2060 SourceLocation Loc) { 2061 LookupPredefedObjCSuperType(*this, S, II); 2062 2063 ASTContext::GetBuiltinTypeError Error; 2064 QualType R = Context.GetBuiltinType(ID, Error); 2065 if (Error) { 2066 if (!ForRedeclaration) 2067 return nullptr; 2068 2069 // If we have a builtin without an associated type we should not emit a 2070 // warning when we were not able to find a type for it. 2071 if (Error == ASTContext::GE_Missing_type) 2072 return nullptr; 2073 2074 // If we could not find a type for setjmp it is because the jmp_buf type was 2075 // not defined prior to the setjmp declaration. 2076 if (Error == ASTContext::GE_Missing_setjmp) { 2077 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf) 2078 << Context.BuiltinInfo.getName(ID); 2079 return nullptr; 2080 } 2081 2082 // Generally, we emit a warning that the declaration requires the 2083 // appropriate header. 2084 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 2085 << getHeaderName(Context.BuiltinInfo, ID, Error) 2086 << Context.BuiltinInfo.getName(ID); 2087 return nullptr; 2088 } 2089 2090 if (!ForRedeclaration && 2091 (Context.BuiltinInfo.isPredefinedLibFunction(ID) || 2092 Context.BuiltinInfo.isHeaderDependentFunction(ID))) { 2093 Diag(Loc, diag::ext_implicit_lib_function_decl) 2094 << Context.BuiltinInfo.getName(ID) << R; 2095 if (Context.BuiltinInfo.getHeaderName(ID) && 2096 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc)) 2097 Diag(Loc, diag::note_include_header_or_declare) 2098 << Context.BuiltinInfo.getHeaderName(ID) 2099 << Context.BuiltinInfo.getName(ID); 2100 } 2101 2102 if (R.isNull()) 2103 return nullptr; 2104 2105 DeclContext *Parent = Context.getTranslationUnitDecl(); 2106 if (getLangOpts().CPlusPlus) { 2107 LinkageSpecDecl *CLinkageDecl = 2108 LinkageSpecDecl::Create(Context, Parent, Loc, Loc, 2109 LinkageSpecDecl::lang_c, false); 2110 CLinkageDecl->setImplicit(); 2111 Parent->addDecl(CLinkageDecl); 2112 Parent = CLinkageDecl; 2113 } 2114 2115 FunctionDecl *New = FunctionDecl::Create(Context, 2116 Parent, 2117 Loc, Loc, II, R, /*TInfo=*/nullptr, 2118 SC_Extern, 2119 false, 2120 R->isFunctionProtoType()); 2121 New->setImplicit(); 2122 2123 // Create Decl objects for each parameter, adding them to the 2124 // FunctionDecl. 2125 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 2126 SmallVector<ParmVarDecl*, 16> Params; 2127 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 2128 ParmVarDecl *parm = 2129 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(), 2130 nullptr, FT->getParamType(i), /*TInfo=*/nullptr, 2131 SC_None, nullptr); 2132 parm->setScopeInfo(0, i); 2133 Params.push_back(parm); 2134 } 2135 New->setParams(Params); 2136 } 2137 2138 AddKnownFunctionAttributes(New); 2139 RegisterLocallyScopedExternCDecl(New, S); 2140 2141 // TUScope is the translation-unit scope to insert this function into. 2142 // FIXME: This is hideous. We need to teach PushOnScopeChains to 2143 // relate Scopes to DeclContexts, and probably eliminate CurContext 2144 // entirely, but we're not there yet. 2145 DeclContext *SavedContext = CurContext; 2146 CurContext = Parent; 2147 PushOnScopeChains(New, TUScope); 2148 CurContext = SavedContext; 2149 return New; 2150 } 2151 2152 /// Typedef declarations don't have linkage, but they still denote the same 2153 /// entity if their types are the same. 2154 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 2155 /// isSameEntity. 2156 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 2157 TypedefNameDecl *Decl, 2158 LookupResult &Previous) { 2159 // This is only interesting when modules are enabled. 2160 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 2161 return; 2162 2163 // Empty sets are uninteresting. 2164 if (Previous.empty()) 2165 return; 2166 2167 LookupResult::Filter Filter = Previous.makeFilter(); 2168 while (Filter.hasNext()) { 2169 NamedDecl *Old = Filter.next(); 2170 2171 // Non-hidden declarations are never ignored. 2172 if (S.isVisible(Old)) 2173 continue; 2174 2175 // Declarations of the same entity are not ignored, even if they have 2176 // different linkages. 2177 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2178 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 2179 Decl->getUnderlyingType())) 2180 continue; 2181 2182 // If both declarations give a tag declaration a typedef name for linkage 2183 // purposes, then they declare the same entity. 2184 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 2185 Decl->getAnonDeclWithTypedefName()) 2186 continue; 2187 } 2188 2189 Filter.erase(); 2190 } 2191 2192 Filter.done(); 2193 } 2194 2195 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 2196 QualType OldType; 2197 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 2198 OldType = OldTypedef->getUnderlyingType(); 2199 else 2200 OldType = Context.getTypeDeclType(Old); 2201 QualType NewType = New->getUnderlyingType(); 2202 2203 if (NewType->isVariablyModifiedType()) { 2204 // Must not redefine a typedef with a variably-modified type. 2205 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2206 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 2207 << Kind << NewType; 2208 if (Old->getLocation().isValid()) 2209 notePreviousDefinition(Old, New->getLocation()); 2210 New->setInvalidDecl(); 2211 return true; 2212 } 2213 2214 if (OldType != NewType && 2215 !OldType->isDependentType() && 2216 !NewType->isDependentType() && 2217 !Context.hasSameType(OldType, NewType)) { 2218 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2219 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 2220 << Kind << NewType << OldType; 2221 if (Old->getLocation().isValid()) 2222 notePreviousDefinition(Old, New->getLocation()); 2223 New->setInvalidDecl(); 2224 return true; 2225 } 2226 return false; 2227 } 2228 2229 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 2230 /// same name and scope as a previous declaration 'Old'. Figure out 2231 /// how to resolve this situation, merging decls or emitting 2232 /// diagnostics as appropriate. If there was an error, set New to be invalid. 2233 /// 2234 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 2235 LookupResult &OldDecls) { 2236 // If the new decl is known invalid already, don't bother doing any 2237 // merging checks. 2238 if (New->isInvalidDecl()) return; 2239 2240 // Allow multiple definitions for ObjC built-in typedefs. 2241 // FIXME: Verify the underlying types are equivalent! 2242 if (getLangOpts().ObjC) { 2243 const IdentifierInfo *TypeID = New->getIdentifier(); 2244 switch (TypeID->getLength()) { 2245 default: break; 2246 case 2: 2247 { 2248 if (!TypeID->isStr("id")) 2249 break; 2250 QualType T = New->getUnderlyingType(); 2251 if (!T->isPointerType()) 2252 break; 2253 if (!T->isVoidPointerType()) { 2254 QualType PT = T->castAs<PointerType>()->getPointeeType(); 2255 if (!PT->isStructureType()) 2256 break; 2257 } 2258 Context.setObjCIdRedefinitionType(T); 2259 // Install the built-in type for 'id', ignoring the current definition. 2260 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 2261 return; 2262 } 2263 case 5: 2264 if (!TypeID->isStr("Class")) 2265 break; 2266 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 2267 // Install the built-in type for 'Class', ignoring the current definition. 2268 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 2269 return; 2270 case 3: 2271 if (!TypeID->isStr("SEL")) 2272 break; 2273 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 2274 // Install the built-in type for 'SEL', ignoring the current definition. 2275 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 2276 return; 2277 } 2278 // Fall through - the typedef name was not a builtin type. 2279 } 2280 2281 // Verify the old decl was also a type. 2282 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 2283 if (!Old) { 2284 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2285 << New->getDeclName(); 2286 2287 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 2288 if (OldD->getLocation().isValid()) 2289 notePreviousDefinition(OldD, New->getLocation()); 2290 2291 return New->setInvalidDecl(); 2292 } 2293 2294 // If the old declaration is invalid, just give up here. 2295 if (Old->isInvalidDecl()) 2296 return New->setInvalidDecl(); 2297 2298 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2299 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2300 auto *NewTag = New->getAnonDeclWithTypedefName(); 2301 NamedDecl *Hidden = nullptr; 2302 if (OldTag && NewTag && 2303 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 2304 !hasVisibleDefinition(OldTag, &Hidden)) { 2305 // There is a definition of this tag, but it is not visible. Use it 2306 // instead of our tag. 2307 New->setTypeForDecl(OldTD->getTypeForDecl()); 2308 if (OldTD->isModed()) 2309 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 2310 OldTD->getUnderlyingType()); 2311 else 2312 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 2313 2314 // Make the old tag definition visible. 2315 makeMergedDefinitionVisible(Hidden); 2316 2317 // If this was an unscoped enumeration, yank all of its enumerators 2318 // out of the scope. 2319 if (isa<EnumDecl>(NewTag)) { 2320 Scope *EnumScope = getNonFieldDeclScope(S); 2321 for (auto *D : NewTag->decls()) { 2322 auto *ED = cast<EnumConstantDecl>(D); 2323 assert(EnumScope->isDeclScope(ED)); 2324 EnumScope->RemoveDecl(ED); 2325 IdResolver.RemoveDecl(ED); 2326 ED->getLexicalDeclContext()->removeDecl(ED); 2327 } 2328 } 2329 } 2330 } 2331 2332 // If the typedef types are not identical, reject them in all languages and 2333 // with any extensions enabled. 2334 if (isIncompatibleTypedef(Old, New)) 2335 return; 2336 2337 // The types match. Link up the redeclaration chain and merge attributes if 2338 // the old declaration was a typedef. 2339 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2340 New->setPreviousDecl(Typedef); 2341 mergeDeclAttributes(New, Old); 2342 } 2343 2344 if (getLangOpts().MicrosoftExt) 2345 return; 2346 2347 if (getLangOpts().CPlusPlus) { 2348 // C++ [dcl.typedef]p2: 2349 // In a given non-class scope, a typedef specifier can be used to 2350 // redefine the name of any type declared in that scope to refer 2351 // to the type to which it already refers. 2352 if (!isa<CXXRecordDecl>(CurContext)) 2353 return; 2354 2355 // C++0x [dcl.typedef]p4: 2356 // In a given class scope, a typedef specifier can be used to redefine 2357 // any class-name declared in that scope that is not also a typedef-name 2358 // to refer to the type to which it already refers. 2359 // 2360 // This wording came in via DR424, which was a correction to the 2361 // wording in DR56, which accidentally banned code like: 2362 // 2363 // struct S { 2364 // typedef struct A { } A; 2365 // }; 2366 // 2367 // in the C++03 standard. We implement the C++0x semantics, which 2368 // allow the above but disallow 2369 // 2370 // struct S { 2371 // typedef int I; 2372 // typedef int I; 2373 // }; 2374 // 2375 // since that was the intent of DR56. 2376 if (!isa<TypedefNameDecl>(Old)) 2377 return; 2378 2379 Diag(New->getLocation(), diag::err_redefinition) 2380 << New->getDeclName(); 2381 notePreviousDefinition(Old, New->getLocation()); 2382 return New->setInvalidDecl(); 2383 } 2384 2385 // Modules always permit redefinition of typedefs, as does C11. 2386 if (getLangOpts().Modules || getLangOpts().C11) 2387 return; 2388 2389 // If we have a redefinition of a typedef in C, emit a warning. This warning 2390 // is normally mapped to an error, but can be controlled with 2391 // -Wtypedef-redefinition. If either the original or the redefinition is 2392 // in a system header, don't emit this for compatibility with GCC. 2393 if (getDiagnostics().getSuppressSystemWarnings() && 2394 // Some standard types are defined implicitly in Clang (e.g. OpenCL). 2395 (Old->isImplicit() || 2396 Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2397 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2398 return; 2399 2400 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2401 << New->getDeclName(); 2402 notePreviousDefinition(Old, New->getLocation()); 2403 } 2404 2405 /// DeclhasAttr - returns true if decl Declaration already has the target 2406 /// attribute. 2407 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2408 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2409 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2410 for (const auto *i : D->attrs()) 2411 if (i->getKind() == A->getKind()) { 2412 if (Ann) { 2413 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2414 return true; 2415 continue; 2416 } 2417 // FIXME: Don't hardcode this check 2418 if (OA && isa<OwnershipAttr>(i)) 2419 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2420 return true; 2421 } 2422 2423 return false; 2424 } 2425 2426 static bool isAttributeTargetADefinition(Decl *D) { 2427 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2428 return VD->isThisDeclarationADefinition(); 2429 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2430 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2431 return true; 2432 } 2433 2434 /// Merge alignment attributes from \p Old to \p New, taking into account the 2435 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2436 /// 2437 /// \return \c true if any attributes were added to \p New. 2438 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2439 // Look for alignas attributes on Old, and pick out whichever attribute 2440 // specifies the strictest alignment requirement. 2441 AlignedAttr *OldAlignasAttr = nullptr; 2442 AlignedAttr *OldStrictestAlignAttr = nullptr; 2443 unsigned OldAlign = 0; 2444 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2445 // FIXME: We have no way of representing inherited dependent alignments 2446 // in a case like: 2447 // template<int A, int B> struct alignas(A) X; 2448 // template<int A, int B> struct alignas(B) X {}; 2449 // For now, we just ignore any alignas attributes which are not on the 2450 // definition in such a case. 2451 if (I->isAlignmentDependent()) 2452 return false; 2453 2454 if (I->isAlignas()) 2455 OldAlignasAttr = I; 2456 2457 unsigned Align = I->getAlignment(S.Context); 2458 if (Align > OldAlign) { 2459 OldAlign = Align; 2460 OldStrictestAlignAttr = I; 2461 } 2462 } 2463 2464 // Look for alignas attributes on New. 2465 AlignedAttr *NewAlignasAttr = nullptr; 2466 unsigned NewAlign = 0; 2467 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2468 if (I->isAlignmentDependent()) 2469 return false; 2470 2471 if (I->isAlignas()) 2472 NewAlignasAttr = I; 2473 2474 unsigned Align = I->getAlignment(S.Context); 2475 if (Align > NewAlign) 2476 NewAlign = Align; 2477 } 2478 2479 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2480 // Both declarations have 'alignas' attributes. We require them to match. 2481 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2482 // fall short. (If two declarations both have alignas, they must both match 2483 // every definition, and so must match each other if there is a definition.) 2484 2485 // If either declaration only contains 'alignas(0)' specifiers, then it 2486 // specifies the natural alignment for the type. 2487 if (OldAlign == 0 || NewAlign == 0) { 2488 QualType Ty; 2489 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2490 Ty = VD->getType(); 2491 else 2492 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2493 2494 if (OldAlign == 0) 2495 OldAlign = S.Context.getTypeAlign(Ty); 2496 if (NewAlign == 0) 2497 NewAlign = S.Context.getTypeAlign(Ty); 2498 } 2499 2500 if (OldAlign != NewAlign) { 2501 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2502 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2503 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2504 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2505 } 2506 } 2507 2508 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2509 // C++11 [dcl.align]p6: 2510 // if any declaration of an entity has an alignment-specifier, 2511 // every defining declaration of that entity shall specify an 2512 // equivalent alignment. 2513 // C11 6.7.5/7: 2514 // If the definition of an object does not have an alignment 2515 // specifier, any other declaration of that object shall also 2516 // have no alignment specifier. 2517 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2518 << OldAlignasAttr; 2519 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2520 << OldAlignasAttr; 2521 } 2522 2523 bool AnyAdded = false; 2524 2525 // Ensure we have an attribute representing the strictest alignment. 2526 if (OldAlign > NewAlign) { 2527 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2528 Clone->setInherited(true); 2529 New->addAttr(Clone); 2530 AnyAdded = true; 2531 } 2532 2533 // Ensure we have an alignas attribute if the old declaration had one. 2534 if (OldAlignasAttr && !NewAlignasAttr && 2535 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2536 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2537 Clone->setInherited(true); 2538 New->addAttr(Clone); 2539 AnyAdded = true; 2540 } 2541 2542 return AnyAdded; 2543 } 2544 2545 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2546 const InheritableAttr *Attr, 2547 Sema::AvailabilityMergeKind AMK) { 2548 // This function copies an attribute Attr from a previous declaration to the 2549 // new declaration D if the new declaration doesn't itself have that attribute 2550 // yet or if that attribute allows duplicates. 2551 // If you're adding a new attribute that requires logic different from 2552 // "use explicit attribute on decl if present, else use attribute from 2553 // previous decl", for example if the attribute needs to be consistent 2554 // between redeclarations, you need to call a custom merge function here. 2555 InheritableAttr *NewAttr = nullptr; 2556 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2557 NewAttr = S.mergeAvailabilityAttr( 2558 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(), 2559 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(), 2560 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK, 2561 AA->getPriority()); 2562 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2563 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility()); 2564 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2565 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility()); 2566 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2567 NewAttr = S.mergeDLLImportAttr(D, *ImportA); 2568 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2569 NewAttr = S.mergeDLLExportAttr(D, *ExportA); 2570 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2571 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(), 2572 FA->getFirstArg()); 2573 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2574 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName()); 2575 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr)) 2576 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName()); 2577 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2578 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(), 2579 IA->getInheritanceModel()); 2580 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2581 NewAttr = S.mergeAlwaysInlineAttr(D, *AA, 2582 &S.Context.Idents.get(AA->getSpelling())); 2583 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2584 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2585 isa<CUDAGlobalAttr>(Attr))) { 2586 // CUDA target attributes are part of function signature for 2587 // overloading purposes and must not be merged. 2588 return false; 2589 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2590 NewAttr = S.mergeMinSizeAttr(D, *MA); 2591 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2592 NewAttr = S.mergeOptimizeNoneAttr(D, *OA); 2593 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2594 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA); 2595 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr)) 2596 NewAttr = S.mergeCommonAttr(D, *CommonA); 2597 else if (isa<AlignedAttr>(Attr)) 2598 // AlignedAttrs are handled separately, because we need to handle all 2599 // such attributes on a declaration at the same time. 2600 NewAttr = nullptr; 2601 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2602 (AMK == Sema::AMK_Override || 2603 AMK == Sema::AMK_ProtocolImplementation)) 2604 NewAttr = nullptr; 2605 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2606 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl()); 2607 else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr)) 2608 NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA); 2609 else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr)) 2610 NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA); 2611 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr)) 2612 NewAttr = S.mergeImportModuleAttr(D, *IMA); 2613 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr)) 2614 NewAttr = S.mergeImportNameAttr(D, *INA); 2615 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr)) 2616 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2617 2618 if (NewAttr) { 2619 NewAttr->setInherited(true); 2620 D->addAttr(NewAttr); 2621 if (isa<MSInheritanceAttr>(NewAttr)) 2622 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2623 return true; 2624 } 2625 2626 return false; 2627 } 2628 2629 static const NamedDecl *getDefinition(const Decl *D) { 2630 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2631 return TD->getDefinition(); 2632 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2633 const VarDecl *Def = VD->getDefinition(); 2634 if (Def) 2635 return Def; 2636 return VD->getActingDefinition(); 2637 } 2638 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 2639 return FD->getDefinition(); 2640 return nullptr; 2641 } 2642 2643 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2644 for (const auto *Attribute : D->attrs()) 2645 if (Attribute->getKind() == Kind) 2646 return true; 2647 return false; 2648 } 2649 2650 /// checkNewAttributesAfterDef - If we already have a definition, check that 2651 /// there are no new attributes in this declaration. 2652 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2653 if (!New->hasAttrs()) 2654 return; 2655 2656 const NamedDecl *Def = getDefinition(Old); 2657 if (!Def || Def == New) 2658 return; 2659 2660 AttrVec &NewAttributes = New->getAttrs(); 2661 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2662 const Attr *NewAttribute = NewAttributes[I]; 2663 2664 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 2665 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2666 Sema::SkipBodyInfo SkipBody; 2667 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2668 2669 // If we're skipping this definition, drop the "alias" attribute. 2670 if (SkipBody.ShouldSkip) { 2671 NewAttributes.erase(NewAttributes.begin() + I); 2672 --E; 2673 continue; 2674 } 2675 } else { 2676 VarDecl *VD = cast<VarDecl>(New); 2677 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2678 VarDecl::TentativeDefinition 2679 ? diag::err_alias_after_tentative 2680 : diag::err_redefinition; 2681 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2682 if (Diag == diag::err_redefinition) 2683 S.notePreviousDefinition(Def, VD->getLocation()); 2684 else 2685 S.Diag(Def->getLocation(), diag::note_previous_definition); 2686 VD->setInvalidDecl(); 2687 } 2688 ++I; 2689 continue; 2690 } 2691 2692 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2693 // Tentative definitions are only interesting for the alias check above. 2694 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2695 ++I; 2696 continue; 2697 } 2698 } 2699 2700 if (hasAttribute(Def, NewAttribute->getKind())) { 2701 ++I; 2702 continue; // regular attr merging will take care of validating this. 2703 } 2704 2705 if (isa<C11NoReturnAttr>(NewAttribute)) { 2706 // C's _Noreturn is allowed to be added to a function after it is defined. 2707 ++I; 2708 continue; 2709 } else if (isa<UuidAttr>(NewAttribute)) { 2710 // msvc will allow a subsequent definition to add an uuid to a class 2711 ++I; 2712 continue; 2713 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2714 if (AA->isAlignas()) { 2715 // C++11 [dcl.align]p6: 2716 // if any declaration of an entity has an alignment-specifier, 2717 // every defining declaration of that entity shall specify an 2718 // equivalent alignment. 2719 // C11 6.7.5/7: 2720 // If the definition of an object does not have an alignment 2721 // specifier, any other declaration of that object shall also 2722 // have no alignment specifier. 2723 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2724 << AA; 2725 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2726 << AA; 2727 NewAttributes.erase(NewAttributes.begin() + I); 2728 --E; 2729 continue; 2730 } 2731 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) { 2732 // If there is a C definition followed by a redeclaration with this 2733 // attribute then there are two different definitions. In C++, prefer the 2734 // standard diagnostics. 2735 if (!S.getLangOpts().CPlusPlus) { 2736 S.Diag(NewAttribute->getLocation(), 2737 diag::err_loader_uninitialized_redeclaration); 2738 S.Diag(Def->getLocation(), diag::note_previous_definition); 2739 NewAttributes.erase(NewAttributes.begin() + I); 2740 --E; 2741 continue; 2742 } 2743 } else if (isa<SelectAnyAttr>(NewAttribute) && 2744 cast<VarDecl>(New)->isInline() && 2745 !cast<VarDecl>(New)->isInlineSpecified()) { 2746 // Don't warn about applying selectany to implicitly inline variables. 2747 // Older compilers and language modes would require the use of selectany 2748 // to make such variables inline, and it would have no effect if we 2749 // honored it. 2750 ++I; 2751 continue; 2752 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) { 2753 // We allow to add OMP[Begin]DeclareVariantAttr to be added to 2754 // declarations after defintions. 2755 ++I; 2756 continue; 2757 } 2758 2759 S.Diag(NewAttribute->getLocation(), 2760 diag::warn_attribute_precede_definition); 2761 S.Diag(Def->getLocation(), diag::note_previous_definition); 2762 NewAttributes.erase(NewAttributes.begin() + I); 2763 --E; 2764 } 2765 } 2766 2767 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, 2768 const ConstInitAttr *CIAttr, 2769 bool AttrBeforeInit) { 2770 SourceLocation InsertLoc = InitDecl->getInnerLocStart(); 2771 2772 // Figure out a good way to write this specifier on the old declaration. 2773 // FIXME: We should just use the spelling of CIAttr, but we don't preserve 2774 // enough of the attribute list spelling information to extract that without 2775 // heroics. 2776 std::string SuitableSpelling; 2777 if (S.getLangOpts().CPlusPlus20) 2778 SuitableSpelling = std::string( 2779 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit})); 2780 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2781 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2782 InsertLoc, {tok::l_square, tok::l_square, 2783 S.PP.getIdentifierInfo("clang"), tok::coloncolon, 2784 S.PP.getIdentifierInfo("require_constant_initialization"), 2785 tok::r_square, tok::r_square})); 2786 if (SuitableSpelling.empty()) 2787 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2788 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren, 2789 S.PP.getIdentifierInfo("require_constant_initialization"), 2790 tok::r_paren, tok::r_paren})); 2791 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20) 2792 SuitableSpelling = "constinit"; 2793 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2794 SuitableSpelling = "[[clang::require_constant_initialization]]"; 2795 if (SuitableSpelling.empty()) 2796 SuitableSpelling = "__attribute__((require_constant_initialization))"; 2797 SuitableSpelling += " "; 2798 2799 if (AttrBeforeInit) { 2800 // extern constinit int a; 2801 // int a = 0; // error (missing 'constinit'), accepted as extension 2802 assert(CIAttr->isConstinit() && "should not diagnose this for attribute"); 2803 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing) 2804 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 2805 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here); 2806 } else { 2807 // int a = 0; 2808 // constinit extern int a; // error (missing 'constinit') 2809 S.Diag(CIAttr->getLocation(), 2810 CIAttr->isConstinit() ? diag::err_constinit_added_too_late 2811 : diag::warn_require_const_init_added_too_late) 2812 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation())); 2813 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here) 2814 << CIAttr->isConstinit() 2815 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 2816 } 2817 } 2818 2819 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2820 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2821 AvailabilityMergeKind AMK) { 2822 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2823 UsedAttr *NewAttr = OldAttr->clone(Context); 2824 NewAttr->setInherited(true); 2825 New->addAttr(NewAttr); 2826 } 2827 2828 if (!Old->hasAttrs() && !New->hasAttrs()) 2829 return; 2830 2831 // [dcl.constinit]p1: 2832 // If the [constinit] specifier is applied to any declaration of a 2833 // variable, it shall be applied to the initializing declaration. 2834 const auto *OldConstInit = Old->getAttr<ConstInitAttr>(); 2835 const auto *NewConstInit = New->getAttr<ConstInitAttr>(); 2836 if (bool(OldConstInit) != bool(NewConstInit)) { 2837 const auto *OldVD = cast<VarDecl>(Old); 2838 auto *NewVD = cast<VarDecl>(New); 2839 2840 // Find the initializing declaration. Note that we might not have linked 2841 // the new declaration into the redeclaration chain yet. 2842 const VarDecl *InitDecl = OldVD->getInitializingDeclaration(); 2843 if (!InitDecl && 2844 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition())) 2845 InitDecl = NewVD; 2846 2847 if (InitDecl == NewVD) { 2848 // This is the initializing declaration. If it would inherit 'constinit', 2849 // that's ill-formed. (Note that we do not apply this to the attribute 2850 // form). 2851 if (OldConstInit && OldConstInit->isConstinit()) 2852 diagnoseMissingConstinit(*this, NewVD, OldConstInit, 2853 /*AttrBeforeInit=*/true); 2854 } else if (NewConstInit) { 2855 // This is the first time we've been told that this declaration should 2856 // have a constant initializer. If we already saw the initializing 2857 // declaration, this is too late. 2858 if (InitDecl && InitDecl != NewVD) { 2859 diagnoseMissingConstinit(*this, InitDecl, NewConstInit, 2860 /*AttrBeforeInit=*/false); 2861 NewVD->dropAttr<ConstInitAttr>(); 2862 } 2863 } 2864 } 2865 2866 // Attributes declared post-definition are currently ignored. 2867 checkNewAttributesAfterDef(*this, New, Old); 2868 2869 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 2870 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 2871 if (!OldA->isEquivalent(NewA)) { 2872 // This redeclaration changes __asm__ label. 2873 Diag(New->getLocation(), diag::err_different_asm_label); 2874 Diag(OldA->getLocation(), diag::note_previous_declaration); 2875 } 2876 } else if (Old->isUsed()) { 2877 // This redeclaration adds an __asm__ label to a declaration that has 2878 // already been ODR-used. 2879 Diag(New->getLocation(), diag::err_late_asm_label_name) 2880 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 2881 } 2882 } 2883 2884 // Re-declaration cannot add abi_tag's. 2885 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 2886 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 2887 for (const auto &NewTag : NewAbiTagAttr->tags()) { 2888 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(), 2889 NewTag) == OldAbiTagAttr->tags_end()) { 2890 Diag(NewAbiTagAttr->getLocation(), 2891 diag::err_new_abi_tag_on_redeclaration) 2892 << NewTag; 2893 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 2894 } 2895 } 2896 } else { 2897 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 2898 Diag(Old->getLocation(), diag::note_previous_declaration); 2899 } 2900 } 2901 2902 // This redeclaration adds a section attribute. 2903 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { 2904 if (auto *VD = dyn_cast<VarDecl>(New)) { 2905 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) { 2906 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration); 2907 Diag(Old->getLocation(), diag::note_previous_declaration); 2908 } 2909 } 2910 } 2911 2912 // Redeclaration adds code-seg attribute. 2913 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 2914 if (NewCSA && !Old->hasAttr<CodeSegAttr>() && 2915 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) { 2916 Diag(New->getLocation(), diag::warn_mismatched_section) 2917 << 0 /*codeseg*/; 2918 Diag(Old->getLocation(), diag::note_previous_declaration); 2919 } 2920 2921 if (!Old->hasAttrs()) 2922 return; 2923 2924 bool foundAny = New->hasAttrs(); 2925 2926 // Ensure that any moving of objects within the allocated map is done before 2927 // we process them. 2928 if (!foundAny) New->setAttrs(AttrVec()); 2929 2930 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2931 // Ignore deprecated/unavailable/availability attributes if requested. 2932 AvailabilityMergeKind LocalAMK = AMK_None; 2933 if (isa<DeprecatedAttr>(I) || 2934 isa<UnavailableAttr>(I) || 2935 isa<AvailabilityAttr>(I)) { 2936 switch (AMK) { 2937 case AMK_None: 2938 continue; 2939 2940 case AMK_Redeclaration: 2941 case AMK_Override: 2942 case AMK_ProtocolImplementation: 2943 LocalAMK = AMK; 2944 break; 2945 } 2946 } 2947 2948 // Already handled. 2949 if (isa<UsedAttr>(I)) 2950 continue; 2951 2952 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 2953 foundAny = true; 2954 } 2955 2956 if (mergeAlignedAttrs(*this, New, Old)) 2957 foundAny = true; 2958 2959 if (!foundAny) New->dropAttrs(); 2960 } 2961 2962 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2963 /// to the new one. 2964 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2965 const ParmVarDecl *oldDecl, 2966 Sema &S) { 2967 // C++11 [dcl.attr.depend]p2: 2968 // The first declaration of a function shall specify the 2969 // carries_dependency attribute for its declarator-id if any declaration 2970 // of the function specifies the carries_dependency attribute. 2971 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2972 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2973 S.Diag(CDA->getLocation(), 2974 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2975 // Find the first declaration of the parameter. 2976 // FIXME: Should we build redeclaration chains for function parameters? 2977 const FunctionDecl *FirstFD = 2978 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2979 const ParmVarDecl *FirstVD = 2980 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2981 S.Diag(FirstVD->getLocation(), 2982 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2983 } 2984 2985 if (!oldDecl->hasAttrs()) 2986 return; 2987 2988 bool foundAny = newDecl->hasAttrs(); 2989 2990 // Ensure that any moving of objects within the allocated map is 2991 // done before we process them. 2992 if (!foundAny) newDecl->setAttrs(AttrVec()); 2993 2994 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 2995 if (!DeclHasAttr(newDecl, I)) { 2996 InheritableAttr *newAttr = 2997 cast<InheritableParamAttr>(I->clone(S.Context)); 2998 newAttr->setInherited(true); 2999 newDecl->addAttr(newAttr); 3000 foundAny = true; 3001 } 3002 } 3003 3004 if (!foundAny) newDecl->dropAttrs(); 3005 } 3006 3007 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 3008 const ParmVarDecl *OldParam, 3009 Sema &S) { 3010 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 3011 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 3012 if (*Oldnullability != *Newnullability) { 3013 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 3014 << DiagNullabilityKind( 3015 *Newnullability, 3016 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3017 != 0)) 3018 << DiagNullabilityKind( 3019 *Oldnullability, 3020 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3021 != 0)); 3022 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 3023 } 3024 } else { 3025 QualType NewT = NewParam->getType(); 3026 NewT = S.Context.getAttributedType( 3027 AttributedType::getNullabilityAttrKind(*Oldnullability), 3028 NewT, NewT); 3029 NewParam->setType(NewT); 3030 } 3031 } 3032 } 3033 3034 namespace { 3035 3036 /// Used in MergeFunctionDecl to keep track of function parameters in 3037 /// C. 3038 struct GNUCompatibleParamWarning { 3039 ParmVarDecl *OldParm; 3040 ParmVarDecl *NewParm; 3041 QualType PromotedType; 3042 }; 3043 3044 } // end anonymous namespace 3045 3046 // Determine whether the previous declaration was a definition, implicit 3047 // declaration, or a declaration. 3048 template <typename T> 3049 static std::pair<diag::kind, SourceLocation> 3050 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 3051 diag::kind PrevDiag; 3052 SourceLocation OldLocation = Old->getLocation(); 3053 if (Old->isThisDeclarationADefinition()) 3054 PrevDiag = diag::note_previous_definition; 3055 else if (Old->isImplicit()) { 3056 PrevDiag = diag::note_previous_implicit_declaration; 3057 if (OldLocation.isInvalid()) 3058 OldLocation = New->getLocation(); 3059 } else 3060 PrevDiag = diag::note_previous_declaration; 3061 return std::make_pair(PrevDiag, OldLocation); 3062 } 3063 3064 /// canRedefineFunction - checks if a function can be redefined. Currently, 3065 /// only extern inline functions can be redefined, and even then only in 3066 /// GNU89 mode. 3067 static bool canRedefineFunction(const FunctionDecl *FD, 3068 const LangOptions& LangOpts) { 3069 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 3070 !LangOpts.CPlusPlus && 3071 FD->isInlineSpecified() && 3072 FD->getStorageClass() == SC_Extern); 3073 } 3074 3075 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 3076 const AttributedType *AT = T->getAs<AttributedType>(); 3077 while (AT && !AT->isCallingConv()) 3078 AT = AT->getModifiedType()->getAs<AttributedType>(); 3079 return AT; 3080 } 3081 3082 template <typename T> 3083 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 3084 const DeclContext *DC = Old->getDeclContext(); 3085 if (DC->isRecord()) 3086 return false; 3087 3088 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 3089 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 3090 return true; 3091 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 3092 return true; 3093 return false; 3094 } 3095 3096 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 3097 static bool isExternC(VarTemplateDecl *) { return false; } 3098 3099 /// Check whether a redeclaration of an entity introduced by a 3100 /// using-declaration is valid, given that we know it's not an overload 3101 /// (nor a hidden tag declaration). 3102 template<typename ExpectedDecl> 3103 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 3104 ExpectedDecl *New) { 3105 // C++11 [basic.scope.declarative]p4: 3106 // Given a set of declarations in a single declarative region, each of 3107 // which specifies the same unqualified name, 3108 // -- they shall all refer to the same entity, or all refer to functions 3109 // and function templates; or 3110 // -- exactly one declaration shall declare a class name or enumeration 3111 // name that is not a typedef name and the other declarations shall all 3112 // refer to the same variable or enumerator, or all refer to functions 3113 // and function templates; in this case the class name or enumeration 3114 // name is hidden (3.3.10). 3115 3116 // C++11 [namespace.udecl]p14: 3117 // If a function declaration in namespace scope or block scope has the 3118 // same name and the same parameter-type-list as a function introduced 3119 // by a using-declaration, and the declarations do not declare the same 3120 // function, the program is ill-formed. 3121 3122 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 3123 if (Old && 3124 !Old->getDeclContext()->getRedeclContext()->Equals( 3125 New->getDeclContext()->getRedeclContext()) && 3126 !(isExternC(Old) && isExternC(New))) 3127 Old = nullptr; 3128 3129 if (!Old) { 3130 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 3131 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 3132 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 3133 return true; 3134 } 3135 return false; 3136 } 3137 3138 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 3139 const FunctionDecl *B) { 3140 assert(A->getNumParams() == B->getNumParams()); 3141 3142 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 3143 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 3144 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 3145 if (AttrA == AttrB) 3146 return true; 3147 return AttrA && AttrB && AttrA->getType() == AttrB->getType() && 3148 AttrA->isDynamic() == AttrB->isDynamic(); 3149 }; 3150 3151 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 3152 } 3153 3154 /// If necessary, adjust the semantic declaration context for a qualified 3155 /// declaration to name the correct inline namespace within the qualifier. 3156 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, 3157 DeclaratorDecl *OldD) { 3158 // The only case where we need to update the DeclContext is when 3159 // redeclaration lookup for a qualified name finds a declaration 3160 // in an inline namespace within the context named by the qualifier: 3161 // 3162 // inline namespace N { int f(); } 3163 // int ::f(); // Sema DC needs adjusting from :: to N::. 3164 // 3165 // For unqualified declarations, the semantic context *can* change 3166 // along the redeclaration chain (for local extern declarations, 3167 // extern "C" declarations, and friend declarations in particular). 3168 if (!NewD->getQualifier()) 3169 return; 3170 3171 // NewD is probably already in the right context. 3172 auto *NamedDC = NewD->getDeclContext()->getRedeclContext(); 3173 auto *SemaDC = OldD->getDeclContext()->getRedeclContext(); 3174 if (NamedDC->Equals(SemaDC)) 3175 return; 3176 3177 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || 3178 NewD->isInvalidDecl() || OldD->isInvalidDecl()) && 3179 "unexpected context for redeclaration"); 3180 3181 auto *LexDC = NewD->getLexicalDeclContext(); 3182 auto FixSemaDC = [=](NamedDecl *D) { 3183 if (!D) 3184 return; 3185 D->setDeclContext(SemaDC); 3186 D->setLexicalDeclContext(LexDC); 3187 }; 3188 3189 FixSemaDC(NewD); 3190 if (auto *FD = dyn_cast<FunctionDecl>(NewD)) 3191 FixSemaDC(FD->getDescribedFunctionTemplate()); 3192 else if (auto *VD = dyn_cast<VarDecl>(NewD)) 3193 FixSemaDC(VD->getDescribedVarTemplate()); 3194 } 3195 3196 /// MergeFunctionDecl - We just parsed a function 'New' from 3197 /// declarator D which has the same name and scope as a previous 3198 /// declaration 'Old'. Figure out how to resolve this situation, 3199 /// merging decls or emitting diagnostics as appropriate. 3200 /// 3201 /// In C++, New and Old must be declarations that are not 3202 /// overloaded. Use IsOverload to determine whether New and Old are 3203 /// overloaded, and to select the Old declaration that New should be 3204 /// merged with. 3205 /// 3206 /// Returns true if there was an error, false otherwise. 3207 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 3208 Scope *S, bool MergeTypeWithOld) { 3209 // Verify the old decl was also a function. 3210 FunctionDecl *Old = OldD->getAsFunction(); 3211 if (!Old) { 3212 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 3213 if (New->getFriendObjectKind()) { 3214 Diag(New->getLocation(), diag::err_using_decl_friend); 3215 Diag(Shadow->getTargetDecl()->getLocation(), 3216 diag::note_using_decl_target); 3217 Diag(Shadow->getUsingDecl()->getLocation(), 3218 diag::note_using_decl) << 0; 3219 return true; 3220 } 3221 3222 // Check whether the two declarations might declare the same function. 3223 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 3224 return true; 3225 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 3226 } else { 3227 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3228 << New->getDeclName(); 3229 notePreviousDefinition(OldD, New->getLocation()); 3230 return true; 3231 } 3232 } 3233 3234 // If the old declaration is invalid, just give up here. 3235 if (Old->isInvalidDecl()) 3236 return true; 3237 3238 // Disallow redeclaration of some builtins. 3239 if (!getASTContext().canBuiltinBeRedeclared(Old)) { 3240 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName(); 3241 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 3242 << Old << Old->getType(); 3243 return true; 3244 } 3245 3246 diag::kind PrevDiag; 3247 SourceLocation OldLocation; 3248 std::tie(PrevDiag, OldLocation) = 3249 getNoteDiagForInvalidRedeclaration(Old, New); 3250 3251 // Don't complain about this if we're in GNU89 mode and the old function 3252 // is an extern inline function. 3253 // Don't complain about specializations. They are not supposed to have 3254 // storage classes. 3255 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 3256 New->getStorageClass() == SC_Static && 3257 Old->hasExternalFormalLinkage() && 3258 !New->getTemplateSpecializationInfo() && 3259 !canRedefineFunction(Old, getLangOpts())) { 3260 if (getLangOpts().MicrosoftExt) { 3261 Diag(New->getLocation(), diag::ext_static_non_static) << New; 3262 Diag(OldLocation, PrevDiag); 3263 } else { 3264 Diag(New->getLocation(), diag::err_static_non_static) << New; 3265 Diag(OldLocation, PrevDiag); 3266 return true; 3267 } 3268 } 3269 3270 if (New->hasAttr<InternalLinkageAttr>() && 3271 !Old->hasAttr<InternalLinkageAttr>()) { 3272 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3273 << New->getDeclName(); 3274 notePreviousDefinition(Old, New->getLocation()); 3275 New->dropAttr<InternalLinkageAttr>(); 3276 } 3277 3278 if (CheckRedeclarationModuleOwnership(New, Old)) 3279 return true; 3280 3281 if (!getLangOpts().CPlusPlus) { 3282 bool OldOvl = Old->hasAttr<OverloadableAttr>(); 3283 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { 3284 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) 3285 << New << OldOvl; 3286 3287 // Try our best to find a decl that actually has the overloadable 3288 // attribute for the note. In most cases (e.g. programs with only one 3289 // broken declaration/definition), this won't matter. 3290 // 3291 // FIXME: We could do this if we juggled some extra state in 3292 // OverloadableAttr, rather than just removing it. 3293 const Decl *DiagOld = Old; 3294 if (OldOvl) { 3295 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { 3296 const auto *A = D->getAttr<OverloadableAttr>(); 3297 return A && !A->isImplicit(); 3298 }); 3299 // If we've implicitly added *all* of the overloadable attrs to this 3300 // chain, emitting a "previous redecl" note is pointless. 3301 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; 3302 } 3303 3304 if (DiagOld) 3305 Diag(DiagOld->getLocation(), 3306 diag::note_attribute_overloadable_prev_overload) 3307 << OldOvl; 3308 3309 if (OldOvl) 3310 New->addAttr(OverloadableAttr::CreateImplicit(Context)); 3311 else 3312 New->dropAttr<OverloadableAttr>(); 3313 } 3314 } 3315 3316 // If a function is first declared with a calling convention, but is later 3317 // declared or defined without one, all following decls assume the calling 3318 // convention of the first. 3319 // 3320 // It's OK if a function is first declared without a calling convention, 3321 // but is later declared or defined with the default calling convention. 3322 // 3323 // To test if either decl has an explicit calling convention, we look for 3324 // AttributedType sugar nodes on the type as written. If they are missing or 3325 // were canonicalized away, we assume the calling convention was implicit. 3326 // 3327 // Note also that we DO NOT return at this point, because we still have 3328 // other tests to run. 3329 QualType OldQType = Context.getCanonicalType(Old->getType()); 3330 QualType NewQType = Context.getCanonicalType(New->getType()); 3331 const FunctionType *OldType = cast<FunctionType>(OldQType); 3332 const FunctionType *NewType = cast<FunctionType>(NewQType); 3333 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 3334 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 3335 bool RequiresAdjustment = false; 3336 3337 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 3338 FunctionDecl *First = Old->getFirstDecl(); 3339 const FunctionType *FT = 3340 First->getType().getCanonicalType()->castAs<FunctionType>(); 3341 FunctionType::ExtInfo FI = FT->getExtInfo(); 3342 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 3343 if (!NewCCExplicit) { 3344 // Inherit the CC from the previous declaration if it was specified 3345 // there but not here. 3346 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3347 RequiresAdjustment = true; 3348 } else if (New->getBuiltinID()) { 3349 // Calling Conventions on a Builtin aren't really useful and setting a 3350 // default calling convention and cdecl'ing some builtin redeclarations is 3351 // common, so warn and ignore the calling convention on the redeclaration. 3352 Diag(New->getLocation(), diag::warn_cconv_unsupported) 3353 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3354 << (int)CallingConventionIgnoredReason::BuiltinFunction; 3355 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3356 RequiresAdjustment = true; 3357 } else { 3358 // Calling conventions aren't compatible, so complain. 3359 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 3360 Diag(New->getLocation(), diag::err_cconv_change) 3361 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3362 << !FirstCCExplicit 3363 << (!FirstCCExplicit ? "" : 3364 FunctionType::getNameForCallConv(FI.getCC())); 3365 3366 // Put the note on the first decl, since it is the one that matters. 3367 Diag(First->getLocation(), diag::note_previous_declaration); 3368 return true; 3369 } 3370 } 3371 3372 // FIXME: diagnose the other way around? 3373 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 3374 NewTypeInfo = NewTypeInfo.withNoReturn(true); 3375 RequiresAdjustment = true; 3376 } 3377 3378 // Merge regparm attribute. 3379 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 3380 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 3381 if (NewTypeInfo.getHasRegParm()) { 3382 Diag(New->getLocation(), diag::err_regparm_mismatch) 3383 << NewType->getRegParmType() 3384 << OldType->getRegParmType(); 3385 Diag(OldLocation, diag::note_previous_declaration); 3386 return true; 3387 } 3388 3389 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 3390 RequiresAdjustment = true; 3391 } 3392 3393 // Merge ns_returns_retained attribute. 3394 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 3395 if (NewTypeInfo.getProducesResult()) { 3396 Diag(New->getLocation(), diag::err_function_attribute_mismatch) 3397 << "'ns_returns_retained'"; 3398 Diag(OldLocation, diag::note_previous_declaration); 3399 return true; 3400 } 3401 3402 NewTypeInfo = NewTypeInfo.withProducesResult(true); 3403 RequiresAdjustment = true; 3404 } 3405 3406 if (OldTypeInfo.getNoCallerSavedRegs() != 3407 NewTypeInfo.getNoCallerSavedRegs()) { 3408 if (NewTypeInfo.getNoCallerSavedRegs()) { 3409 AnyX86NoCallerSavedRegistersAttr *Attr = 3410 New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); 3411 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; 3412 Diag(OldLocation, diag::note_previous_declaration); 3413 return true; 3414 } 3415 3416 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); 3417 RequiresAdjustment = true; 3418 } 3419 3420 if (RequiresAdjustment) { 3421 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 3422 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 3423 New->setType(QualType(AdjustedType, 0)); 3424 NewQType = Context.getCanonicalType(New->getType()); 3425 } 3426 3427 // If this redeclaration makes the function inline, we may need to add it to 3428 // UndefinedButUsed. 3429 if (!Old->isInlined() && New->isInlined() && 3430 !New->hasAttr<GNUInlineAttr>() && 3431 !getLangOpts().GNUInline && 3432 Old->isUsed(false) && 3433 !Old->isDefined() && !New->isThisDeclarationADefinition()) 3434 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3435 SourceLocation())); 3436 3437 // If this redeclaration makes it newly gnu_inline, we don't want to warn 3438 // about it. 3439 if (New->hasAttr<GNUInlineAttr>() && 3440 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 3441 UndefinedButUsed.erase(Old->getCanonicalDecl()); 3442 } 3443 3444 // If pass_object_size params don't match up perfectly, this isn't a valid 3445 // redeclaration. 3446 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 3447 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 3448 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 3449 << New->getDeclName(); 3450 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3451 return true; 3452 } 3453 3454 if (getLangOpts().CPlusPlus) { 3455 // C++1z [over.load]p2 3456 // Certain function declarations cannot be overloaded: 3457 // -- Function declarations that differ only in the return type, 3458 // the exception specification, or both cannot be overloaded. 3459 3460 // Check the exception specifications match. This may recompute the type of 3461 // both Old and New if it resolved exception specifications, so grab the 3462 // types again after this. Because this updates the type, we do this before 3463 // any of the other checks below, which may update the "de facto" NewQType 3464 // but do not necessarily update the type of New. 3465 if (CheckEquivalentExceptionSpec(Old, New)) 3466 return true; 3467 OldQType = Context.getCanonicalType(Old->getType()); 3468 NewQType = Context.getCanonicalType(New->getType()); 3469 3470 // Go back to the type source info to compare the declared return types, 3471 // per C++1y [dcl.type.auto]p13: 3472 // Redeclarations or specializations of a function or function template 3473 // with a declared return type that uses a placeholder type shall also 3474 // use that placeholder, not a deduced type. 3475 QualType OldDeclaredReturnType = Old->getDeclaredReturnType(); 3476 QualType NewDeclaredReturnType = New->getDeclaredReturnType(); 3477 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 3478 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType, 3479 OldDeclaredReturnType)) { 3480 QualType ResQT; 3481 if (NewDeclaredReturnType->isObjCObjectPointerType() && 3482 OldDeclaredReturnType->isObjCObjectPointerType()) 3483 // FIXME: This does the wrong thing for a deduced return type. 3484 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 3485 if (ResQT.isNull()) { 3486 if (New->isCXXClassMember() && New->isOutOfLine()) 3487 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 3488 << New << New->getReturnTypeSourceRange(); 3489 else 3490 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 3491 << New->getReturnTypeSourceRange(); 3492 Diag(OldLocation, PrevDiag) << Old << Old->getType() 3493 << Old->getReturnTypeSourceRange(); 3494 return true; 3495 } 3496 else 3497 NewQType = ResQT; 3498 } 3499 3500 QualType OldReturnType = OldType->getReturnType(); 3501 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 3502 if (OldReturnType != NewReturnType) { 3503 // If this function has a deduced return type and has already been 3504 // defined, copy the deduced value from the old declaration. 3505 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 3506 if (OldAT && OldAT->isDeduced()) { 3507 New->setType( 3508 SubstAutoType(New->getType(), 3509 OldAT->isDependentType() ? Context.DependentTy 3510 : OldAT->getDeducedType())); 3511 NewQType = Context.getCanonicalType( 3512 SubstAutoType(NewQType, 3513 OldAT->isDependentType() ? Context.DependentTy 3514 : OldAT->getDeducedType())); 3515 } 3516 } 3517 3518 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 3519 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 3520 if (OldMethod && NewMethod) { 3521 // Preserve triviality. 3522 NewMethod->setTrivial(OldMethod->isTrivial()); 3523 3524 // MSVC allows explicit template specialization at class scope: 3525 // 2 CXXMethodDecls referring to the same function will be injected. 3526 // We don't want a redeclaration error. 3527 bool IsClassScopeExplicitSpecialization = 3528 OldMethod->isFunctionTemplateSpecialization() && 3529 NewMethod->isFunctionTemplateSpecialization(); 3530 bool isFriend = NewMethod->getFriendObjectKind(); 3531 3532 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 3533 !IsClassScopeExplicitSpecialization) { 3534 // -- Member function declarations with the same name and the 3535 // same parameter types cannot be overloaded if any of them 3536 // is a static member function declaration. 3537 if (OldMethod->isStatic() != NewMethod->isStatic()) { 3538 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 3539 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3540 return true; 3541 } 3542 3543 // C++ [class.mem]p1: 3544 // [...] A member shall not be declared twice in the 3545 // member-specification, except that a nested class or member 3546 // class template can be declared and then later defined. 3547 if (!inTemplateInstantiation()) { 3548 unsigned NewDiag; 3549 if (isa<CXXConstructorDecl>(OldMethod)) 3550 NewDiag = diag::err_constructor_redeclared; 3551 else if (isa<CXXDestructorDecl>(NewMethod)) 3552 NewDiag = diag::err_destructor_redeclared; 3553 else if (isa<CXXConversionDecl>(NewMethod)) 3554 NewDiag = diag::err_conv_function_redeclared; 3555 else 3556 NewDiag = diag::err_member_redeclared; 3557 3558 Diag(New->getLocation(), NewDiag); 3559 } else { 3560 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 3561 << New << New->getType(); 3562 } 3563 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3564 return true; 3565 3566 // Complain if this is an explicit declaration of a special 3567 // member that was initially declared implicitly. 3568 // 3569 // As an exception, it's okay to befriend such methods in order 3570 // to permit the implicit constructor/destructor/operator calls. 3571 } else if (OldMethod->isImplicit()) { 3572 if (isFriend) { 3573 NewMethod->setImplicit(); 3574 } else { 3575 Diag(NewMethod->getLocation(), 3576 diag::err_definition_of_implicitly_declared_member) 3577 << New << getSpecialMember(OldMethod); 3578 return true; 3579 } 3580 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 3581 Diag(NewMethod->getLocation(), 3582 diag::err_definition_of_explicitly_defaulted_member) 3583 << getSpecialMember(OldMethod); 3584 return true; 3585 } 3586 } 3587 3588 // C++11 [dcl.attr.noreturn]p1: 3589 // The first declaration of a function shall specify the noreturn 3590 // attribute if any declaration of that function specifies the noreturn 3591 // attribute. 3592 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 3593 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 3594 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 3595 Diag(Old->getFirstDecl()->getLocation(), 3596 diag::note_noreturn_missing_first_decl); 3597 } 3598 3599 // C++11 [dcl.attr.depend]p2: 3600 // The first declaration of a function shall specify the 3601 // carries_dependency attribute for its declarator-id if any declaration 3602 // of the function specifies the carries_dependency attribute. 3603 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 3604 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 3605 Diag(CDA->getLocation(), 3606 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 3607 Diag(Old->getFirstDecl()->getLocation(), 3608 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 3609 } 3610 3611 // (C++98 8.3.5p3): 3612 // All declarations for a function shall agree exactly in both the 3613 // return type and the parameter-type-list. 3614 // We also want to respect all the extended bits except noreturn. 3615 3616 // noreturn should now match unless the old type info didn't have it. 3617 QualType OldQTypeForComparison = OldQType; 3618 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3619 auto *OldType = OldQType->castAs<FunctionProtoType>(); 3620 const FunctionType *OldTypeForComparison 3621 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3622 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3623 assert(OldQTypeForComparison.isCanonical()); 3624 } 3625 3626 if (haveIncompatibleLanguageLinkages(Old, New)) { 3627 // As a special case, retain the language linkage from previous 3628 // declarations of a friend function as an extension. 3629 // 3630 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3631 // and is useful because there's otherwise no way to specify language 3632 // linkage within class scope. 3633 // 3634 // Check cautiously as the friend object kind isn't yet complete. 3635 if (New->getFriendObjectKind() != Decl::FOK_None) { 3636 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3637 Diag(OldLocation, PrevDiag); 3638 } else { 3639 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3640 Diag(OldLocation, PrevDiag); 3641 return true; 3642 } 3643 } 3644 3645 // If the function types are compatible, merge the declarations. Ignore the 3646 // exception specifier because it was already checked above in 3647 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics 3648 // about incompatible types under -fms-compatibility. 3649 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison, 3650 NewQType)) 3651 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3652 3653 // If the types are imprecise (due to dependent constructs in friends or 3654 // local extern declarations), it's OK if they differ. We'll check again 3655 // during instantiation. 3656 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType)) 3657 return false; 3658 3659 // Fall through for conflicting redeclarations and redefinitions. 3660 } 3661 3662 // C: Function types need to be compatible, not identical. This handles 3663 // duplicate function decls like "void f(int); void f(enum X);" properly. 3664 if (!getLangOpts().CPlusPlus && 3665 Context.typesAreCompatible(OldQType, NewQType)) { 3666 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 3667 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 3668 const FunctionProtoType *OldProto = nullptr; 3669 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 3670 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 3671 // The old declaration provided a function prototype, but the 3672 // new declaration does not. Merge in the prototype. 3673 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 3674 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 3675 NewQType = 3676 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 3677 OldProto->getExtProtoInfo()); 3678 New->setType(NewQType); 3679 New->setHasInheritedPrototype(); 3680 3681 // Synthesize parameters with the same types. 3682 SmallVector<ParmVarDecl*, 16> Params; 3683 for (const auto &ParamType : OldProto->param_types()) { 3684 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 3685 SourceLocation(), nullptr, 3686 ParamType, /*TInfo=*/nullptr, 3687 SC_None, nullptr); 3688 Param->setScopeInfo(0, Params.size()); 3689 Param->setImplicit(); 3690 Params.push_back(Param); 3691 } 3692 3693 New->setParams(Params); 3694 } 3695 3696 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3697 } 3698 3699 // Check if the function types are compatible when pointer size address 3700 // spaces are ignored. 3701 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType)) 3702 return false; 3703 3704 // GNU C permits a K&R definition to follow a prototype declaration 3705 // if the declared types of the parameters in the K&R definition 3706 // match the types in the prototype declaration, even when the 3707 // promoted types of the parameters from the K&R definition differ 3708 // from the types in the prototype. GCC then keeps the types from 3709 // the prototype. 3710 // 3711 // If a variadic prototype is followed by a non-variadic K&R definition, 3712 // the K&R definition becomes variadic. This is sort of an edge case, but 3713 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 3714 // C99 6.9.1p8. 3715 if (!getLangOpts().CPlusPlus && 3716 Old->hasPrototype() && !New->hasPrototype() && 3717 New->getType()->getAs<FunctionProtoType>() && 3718 Old->getNumParams() == New->getNumParams()) { 3719 SmallVector<QualType, 16> ArgTypes; 3720 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 3721 const FunctionProtoType *OldProto 3722 = Old->getType()->getAs<FunctionProtoType>(); 3723 const FunctionProtoType *NewProto 3724 = New->getType()->getAs<FunctionProtoType>(); 3725 3726 // Determine whether this is the GNU C extension. 3727 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 3728 NewProto->getReturnType()); 3729 bool LooseCompatible = !MergedReturn.isNull(); 3730 for (unsigned Idx = 0, End = Old->getNumParams(); 3731 LooseCompatible && Idx != End; ++Idx) { 3732 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 3733 ParmVarDecl *NewParm = New->getParamDecl(Idx); 3734 if (Context.typesAreCompatible(OldParm->getType(), 3735 NewProto->getParamType(Idx))) { 3736 ArgTypes.push_back(NewParm->getType()); 3737 } else if (Context.typesAreCompatible(OldParm->getType(), 3738 NewParm->getType(), 3739 /*CompareUnqualified=*/true)) { 3740 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 3741 NewProto->getParamType(Idx) }; 3742 Warnings.push_back(Warn); 3743 ArgTypes.push_back(NewParm->getType()); 3744 } else 3745 LooseCompatible = false; 3746 } 3747 3748 if (LooseCompatible) { 3749 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 3750 Diag(Warnings[Warn].NewParm->getLocation(), 3751 diag::ext_param_promoted_not_compatible_with_prototype) 3752 << Warnings[Warn].PromotedType 3753 << Warnings[Warn].OldParm->getType(); 3754 if (Warnings[Warn].OldParm->getLocation().isValid()) 3755 Diag(Warnings[Warn].OldParm->getLocation(), 3756 diag::note_previous_declaration); 3757 } 3758 3759 if (MergeTypeWithOld) 3760 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 3761 OldProto->getExtProtoInfo())); 3762 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3763 } 3764 3765 // Fall through to diagnose conflicting types. 3766 } 3767 3768 // A function that has already been declared has been redeclared or 3769 // defined with a different type; show an appropriate diagnostic. 3770 3771 // If the previous declaration was an implicitly-generated builtin 3772 // declaration, then at the very least we should use a specialized note. 3773 unsigned BuiltinID; 3774 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3775 // If it's actually a library-defined builtin function like 'malloc' 3776 // or 'printf', just warn about the incompatible redeclaration. 3777 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3778 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3779 Diag(OldLocation, diag::note_previous_builtin_declaration) 3780 << Old << Old->getType(); 3781 3782 // If this is a global redeclaration, just forget hereafter 3783 // about the "builtin-ness" of the function. 3784 // 3785 // Doing this for local extern declarations is problematic. If 3786 // the builtin declaration remains visible, a second invalid 3787 // local declaration will produce a hard error; if it doesn't 3788 // remain visible, a single bogus local redeclaration (which is 3789 // actually only a warning) could break all the downstream code. 3790 if (!New->getLexicalDeclContext()->isFunctionOrMethod()) 3791 New->getIdentifier()->revertBuiltin(); 3792 3793 return false; 3794 } 3795 3796 PrevDiag = diag::note_previous_builtin_declaration; 3797 } 3798 3799 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3800 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3801 return true; 3802 } 3803 3804 /// Completes the merge of two function declarations that are 3805 /// known to be compatible. 3806 /// 3807 /// This routine handles the merging of attributes and other 3808 /// properties of function declarations from the old declaration to 3809 /// the new declaration, once we know that New is in fact a 3810 /// redeclaration of Old. 3811 /// 3812 /// \returns false 3813 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3814 Scope *S, bool MergeTypeWithOld) { 3815 // Merge the attributes 3816 mergeDeclAttributes(New, Old); 3817 3818 // Merge "pure" flag. 3819 if (Old->isPure()) 3820 New->setPure(); 3821 3822 // Merge "used" flag. 3823 if (Old->getMostRecentDecl()->isUsed(false)) 3824 New->setIsUsed(); 3825 3826 // Merge attributes from the parameters. These can mismatch with K&R 3827 // declarations. 3828 if (New->getNumParams() == Old->getNumParams()) 3829 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 3830 ParmVarDecl *NewParam = New->getParamDecl(i); 3831 ParmVarDecl *OldParam = Old->getParamDecl(i); 3832 mergeParamDeclAttributes(NewParam, OldParam, *this); 3833 mergeParamDeclTypes(NewParam, OldParam, *this); 3834 } 3835 3836 if (getLangOpts().CPlusPlus) 3837 return MergeCXXFunctionDecl(New, Old, S); 3838 3839 // Merge the function types so the we get the composite types for the return 3840 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3841 // was visible. 3842 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3843 if (!Merged.isNull() && MergeTypeWithOld) 3844 New->setType(Merged); 3845 3846 return false; 3847 } 3848 3849 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3850 ObjCMethodDecl *oldMethod) { 3851 // Merge the attributes, including deprecated/unavailable 3852 AvailabilityMergeKind MergeKind = 3853 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 3854 ? AMK_ProtocolImplementation 3855 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3856 : AMK_Override; 3857 3858 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3859 3860 // Merge attributes from the parameters. 3861 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3862 oe = oldMethod->param_end(); 3863 for (ObjCMethodDecl::param_iterator 3864 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3865 ni != ne && oi != oe; ++ni, ++oi) 3866 mergeParamDeclAttributes(*ni, *oi, *this); 3867 3868 CheckObjCMethodOverride(newMethod, oldMethod); 3869 } 3870 3871 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 3872 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 3873 3874 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 3875 ? diag::err_redefinition_different_type 3876 : diag::err_redeclaration_different_type) 3877 << New->getDeclName() << New->getType() << Old->getType(); 3878 3879 diag::kind PrevDiag; 3880 SourceLocation OldLocation; 3881 std::tie(PrevDiag, OldLocation) 3882 = getNoteDiagForInvalidRedeclaration(Old, New); 3883 S.Diag(OldLocation, PrevDiag); 3884 New->setInvalidDecl(); 3885 } 3886 3887 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3888 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3889 /// emitting diagnostics as appropriate. 3890 /// 3891 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3892 /// to here in AddInitializerToDecl. We can't check them before the initializer 3893 /// is attached. 3894 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3895 bool MergeTypeWithOld) { 3896 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3897 return; 3898 3899 QualType MergedT; 3900 if (getLangOpts().CPlusPlus) { 3901 if (New->getType()->isUndeducedType()) { 3902 // We don't know what the new type is until the initializer is attached. 3903 return; 3904 } else if (Context.hasSameType(New->getType(), Old->getType())) { 3905 // These could still be something that needs exception specs checked. 3906 return MergeVarDeclExceptionSpecs(New, Old); 3907 } 3908 // C++ [basic.link]p10: 3909 // [...] the types specified by all declarations referring to a given 3910 // object or function shall be identical, except that declarations for an 3911 // array object can specify array types that differ by the presence or 3912 // absence of a major array bound (8.3.4). 3913 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 3914 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3915 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3916 3917 // We are merging a variable declaration New into Old. If it has an array 3918 // bound, and that bound differs from Old's bound, we should diagnose the 3919 // mismatch. 3920 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 3921 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 3922 PrevVD = PrevVD->getPreviousDecl()) { 3923 QualType PrevVDTy = PrevVD->getType(); 3924 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 3925 continue; 3926 3927 if (!Context.hasSameType(New->getType(), PrevVDTy)) 3928 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 3929 } 3930 } 3931 3932 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 3933 if (Context.hasSameType(OldArray->getElementType(), 3934 NewArray->getElementType())) 3935 MergedT = New->getType(); 3936 } 3937 // FIXME: Check visibility. New is hidden but has a complete type. If New 3938 // has no array bound, it should not inherit one from Old, if Old is not 3939 // visible. 3940 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 3941 if (Context.hasSameType(OldArray->getElementType(), 3942 NewArray->getElementType())) 3943 MergedT = Old->getType(); 3944 } 3945 } 3946 else if (New->getType()->isObjCObjectPointerType() && 3947 Old->getType()->isObjCObjectPointerType()) { 3948 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 3949 Old->getType()); 3950 } 3951 } else { 3952 // C 6.2.7p2: 3953 // All declarations that refer to the same object or function shall have 3954 // compatible type. 3955 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 3956 } 3957 if (MergedT.isNull()) { 3958 // It's OK if we couldn't merge types if either type is dependent, for a 3959 // block-scope variable. In other cases (static data members of class 3960 // templates, variable templates, ...), we require the types to be 3961 // equivalent. 3962 // FIXME: The C++ standard doesn't say anything about this. 3963 if ((New->getType()->isDependentType() || 3964 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 3965 // If the old type was dependent, we can't merge with it, so the new type 3966 // becomes dependent for now. We'll reproduce the original type when we 3967 // instantiate the TypeSourceInfo for the variable. 3968 if (!New->getType()->isDependentType() && MergeTypeWithOld) 3969 New->setType(Context.DependentTy); 3970 return; 3971 } 3972 return diagnoseVarDeclTypeMismatch(*this, New, Old); 3973 } 3974 3975 // Don't actually update the type on the new declaration if the old 3976 // declaration was an extern declaration in a different scope. 3977 if (MergeTypeWithOld) 3978 New->setType(MergedT); 3979 } 3980 3981 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 3982 LookupResult &Previous) { 3983 // C11 6.2.7p4: 3984 // For an identifier with internal or external linkage declared 3985 // in a scope in which a prior declaration of that identifier is 3986 // visible, if the prior declaration specifies internal or 3987 // external linkage, the type of the identifier at the later 3988 // declaration becomes the composite type. 3989 // 3990 // If the variable isn't visible, we do not merge with its type. 3991 if (Previous.isShadowed()) 3992 return false; 3993 3994 if (S.getLangOpts().CPlusPlus) { 3995 // C++11 [dcl.array]p3: 3996 // If there is a preceding declaration of the entity in the same 3997 // scope in which the bound was specified, an omitted array bound 3998 // is taken to be the same as in that earlier declaration. 3999 return NewVD->isPreviousDeclInSameBlockScope() || 4000 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 4001 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 4002 } else { 4003 // If the old declaration was function-local, don't merge with its 4004 // type unless we're in the same function. 4005 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 4006 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 4007 } 4008 } 4009 4010 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 4011 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 4012 /// situation, merging decls or emitting diagnostics as appropriate. 4013 /// 4014 /// Tentative definition rules (C99 6.9.2p2) are checked by 4015 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 4016 /// definitions here, since the initializer hasn't been attached. 4017 /// 4018 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 4019 // If the new decl is already invalid, don't do any other checking. 4020 if (New->isInvalidDecl()) 4021 return; 4022 4023 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 4024 return; 4025 4026 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 4027 4028 // Verify the old decl was also a variable or variable template. 4029 VarDecl *Old = nullptr; 4030 VarTemplateDecl *OldTemplate = nullptr; 4031 if (Previous.isSingleResult()) { 4032 if (NewTemplate) { 4033 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 4034 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 4035 4036 if (auto *Shadow = 4037 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4038 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 4039 return New->setInvalidDecl(); 4040 } else { 4041 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 4042 4043 if (auto *Shadow = 4044 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4045 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 4046 return New->setInvalidDecl(); 4047 } 4048 } 4049 if (!Old) { 4050 Diag(New->getLocation(), diag::err_redefinition_different_kind) 4051 << New->getDeclName(); 4052 notePreviousDefinition(Previous.getRepresentativeDecl(), 4053 New->getLocation()); 4054 return New->setInvalidDecl(); 4055 } 4056 4057 // Ensure the template parameters are compatible. 4058 if (NewTemplate && 4059 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 4060 OldTemplate->getTemplateParameters(), 4061 /*Complain=*/true, TPL_TemplateMatch)) 4062 return New->setInvalidDecl(); 4063 4064 // C++ [class.mem]p1: 4065 // A member shall not be declared twice in the member-specification [...] 4066 // 4067 // Here, we need only consider static data members. 4068 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 4069 Diag(New->getLocation(), diag::err_duplicate_member) 4070 << New->getIdentifier(); 4071 Diag(Old->getLocation(), diag::note_previous_declaration); 4072 New->setInvalidDecl(); 4073 } 4074 4075 mergeDeclAttributes(New, Old); 4076 // Warn if an already-declared variable is made a weak_import in a subsequent 4077 // declaration 4078 if (New->hasAttr<WeakImportAttr>() && 4079 Old->getStorageClass() == SC_None && 4080 !Old->hasAttr<WeakImportAttr>()) { 4081 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 4082 notePreviousDefinition(Old, New->getLocation()); 4083 // Remove weak_import attribute on new declaration. 4084 New->dropAttr<WeakImportAttr>(); 4085 } 4086 4087 if (New->hasAttr<InternalLinkageAttr>() && 4088 !Old->hasAttr<InternalLinkageAttr>()) { 4089 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 4090 << New->getDeclName(); 4091 notePreviousDefinition(Old, New->getLocation()); 4092 New->dropAttr<InternalLinkageAttr>(); 4093 } 4094 4095 // Merge the types. 4096 VarDecl *MostRecent = Old->getMostRecentDecl(); 4097 if (MostRecent != Old) { 4098 MergeVarDeclTypes(New, MostRecent, 4099 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 4100 if (New->isInvalidDecl()) 4101 return; 4102 } 4103 4104 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 4105 if (New->isInvalidDecl()) 4106 return; 4107 4108 diag::kind PrevDiag; 4109 SourceLocation OldLocation; 4110 std::tie(PrevDiag, OldLocation) = 4111 getNoteDiagForInvalidRedeclaration(Old, New); 4112 4113 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 4114 if (New->getStorageClass() == SC_Static && 4115 !New->isStaticDataMember() && 4116 Old->hasExternalFormalLinkage()) { 4117 if (getLangOpts().MicrosoftExt) { 4118 Diag(New->getLocation(), diag::ext_static_non_static) 4119 << New->getDeclName(); 4120 Diag(OldLocation, PrevDiag); 4121 } else { 4122 Diag(New->getLocation(), diag::err_static_non_static) 4123 << New->getDeclName(); 4124 Diag(OldLocation, PrevDiag); 4125 return New->setInvalidDecl(); 4126 } 4127 } 4128 // C99 6.2.2p4: 4129 // For an identifier declared with the storage-class specifier 4130 // extern in a scope in which a prior declaration of that 4131 // identifier is visible,23) if the prior declaration specifies 4132 // internal or external linkage, the linkage of the identifier at 4133 // the later declaration is the same as the linkage specified at 4134 // the prior declaration. If no prior declaration is visible, or 4135 // if the prior declaration specifies no linkage, then the 4136 // identifier has external linkage. 4137 if (New->hasExternalStorage() && Old->hasLinkage()) 4138 /* Okay */; 4139 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 4140 !New->isStaticDataMember() && 4141 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 4142 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 4143 Diag(OldLocation, PrevDiag); 4144 return New->setInvalidDecl(); 4145 } 4146 4147 // Check if extern is followed by non-extern and vice-versa. 4148 if (New->hasExternalStorage() && 4149 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 4150 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 4151 Diag(OldLocation, PrevDiag); 4152 return New->setInvalidDecl(); 4153 } 4154 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 4155 !New->hasExternalStorage()) { 4156 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 4157 Diag(OldLocation, PrevDiag); 4158 return New->setInvalidDecl(); 4159 } 4160 4161 if (CheckRedeclarationModuleOwnership(New, Old)) 4162 return; 4163 4164 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 4165 4166 // FIXME: The test for external storage here seems wrong? We still 4167 // need to check for mismatches. 4168 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 4169 // Don't complain about out-of-line definitions of static members. 4170 !(Old->getLexicalDeclContext()->isRecord() && 4171 !New->getLexicalDeclContext()->isRecord())) { 4172 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 4173 Diag(OldLocation, PrevDiag); 4174 return New->setInvalidDecl(); 4175 } 4176 4177 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 4178 if (VarDecl *Def = Old->getDefinition()) { 4179 // C++1z [dcl.fcn.spec]p4: 4180 // If the definition of a variable appears in a translation unit before 4181 // its first declaration as inline, the program is ill-formed. 4182 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 4183 Diag(Def->getLocation(), diag::note_previous_definition); 4184 } 4185 } 4186 4187 // If this redeclaration makes the variable inline, we may need to add it to 4188 // UndefinedButUsed. 4189 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 4190 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 4191 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 4192 SourceLocation())); 4193 4194 if (New->getTLSKind() != Old->getTLSKind()) { 4195 if (!Old->getTLSKind()) { 4196 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 4197 Diag(OldLocation, PrevDiag); 4198 } else if (!New->getTLSKind()) { 4199 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 4200 Diag(OldLocation, PrevDiag); 4201 } else { 4202 // Do not allow redeclaration to change the variable between requiring 4203 // static and dynamic initialization. 4204 // FIXME: GCC allows this, but uses the TLS keyword on the first 4205 // declaration to determine the kind. Do we need to be compatible here? 4206 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 4207 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 4208 Diag(OldLocation, PrevDiag); 4209 } 4210 } 4211 4212 // C++ doesn't have tentative definitions, so go right ahead and check here. 4213 if (getLangOpts().CPlusPlus && 4214 New->isThisDeclarationADefinition() == VarDecl::Definition) { 4215 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 4216 Old->getCanonicalDecl()->isConstexpr()) { 4217 // This definition won't be a definition any more once it's been merged. 4218 Diag(New->getLocation(), 4219 diag::warn_deprecated_redundant_constexpr_static_def); 4220 } else if (VarDecl *Def = Old->getDefinition()) { 4221 if (checkVarDeclRedefinition(Def, New)) 4222 return; 4223 } 4224 } 4225 4226 if (haveIncompatibleLanguageLinkages(Old, New)) { 4227 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 4228 Diag(OldLocation, PrevDiag); 4229 New->setInvalidDecl(); 4230 return; 4231 } 4232 4233 // Merge "used" flag. 4234 if (Old->getMostRecentDecl()->isUsed(false)) 4235 New->setIsUsed(); 4236 4237 // Keep a chain of previous declarations. 4238 New->setPreviousDecl(Old); 4239 if (NewTemplate) 4240 NewTemplate->setPreviousDecl(OldTemplate); 4241 adjustDeclContextForDeclaratorDecl(New, Old); 4242 4243 // Inherit access appropriately. 4244 New->setAccess(Old->getAccess()); 4245 if (NewTemplate) 4246 NewTemplate->setAccess(New->getAccess()); 4247 4248 if (Old->isInline()) 4249 New->setImplicitlyInline(); 4250 } 4251 4252 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { 4253 SourceManager &SrcMgr = getSourceManager(); 4254 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); 4255 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); 4256 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); 4257 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); 4258 auto &HSI = PP.getHeaderSearchInfo(); 4259 StringRef HdrFilename = 4260 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); 4261 4262 auto noteFromModuleOrInclude = [&](Module *Mod, 4263 SourceLocation IncLoc) -> bool { 4264 // Redefinition errors with modules are common with non modular mapped 4265 // headers, example: a non-modular header H in module A that also gets 4266 // included directly in a TU. Pointing twice to the same header/definition 4267 // is confusing, try to get better diagnostics when modules is on. 4268 if (IncLoc.isValid()) { 4269 if (Mod) { 4270 Diag(IncLoc, diag::note_redefinition_modules_same_file) 4271 << HdrFilename.str() << Mod->getFullModuleName(); 4272 if (!Mod->DefinitionLoc.isInvalid()) 4273 Diag(Mod->DefinitionLoc, diag::note_defined_here) 4274 << Mod->getFullModuleName(); 4275 } else { 4276 Diag(IncLoc, diag::note_redefinition_include_same_file) 4277 << HdrFilename.str(); 4278 } 4279 return true; 4280 } 4281 4282 return false; 4283 }; 4284 4285 // Is it the same file and same offset? Provide more information on why 4286 // this leads to a redefinition error. 4287 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { 4288 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); 4289 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); 4290 bool EmittedDiag = 4291 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); 4292 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); 4293 4294 // If the header has no guards, emit a note suggesting one. 4295 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) 4296 Diag(Old->getLocation(), diag::note_use_ifdef_guards); 4297 4298 if (EmittedDiag) 4299 return; 4300 } 4301 4302 // Redefinition coming from different files or couldn't do better above. 4303 if (Old->getLocation().isValid()) 4304 Diag(Old->getLocation(), diag::note_previous_definition); 4305 } 4306 4307 /// We've just determined that \p Old and \p New both appear to be definitions 4308 /// of the same variable. Either diagnose or fix the problem. 4309 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 4310 if (!hasVisibleDefinition(Old) && 4311 (New->getFormalLinkage() == InternalLinkage || 4312 New->isInline() || 4313 New->getDescribedVarTemplate() || 4314 New->getNumTemplateParameterLists() || 4315 New->getDeclContext()->isDependentContext())) { 4316 // The previous definition is hidden, and multiple definitions are 4317 // permitted (in separate TUs). Demote this to a declaration. 4318 New->demoteThisDefinitionToDeclaration(); 4319 4320 // Make the canonical definition visible. 4321 if (auto *OldTD = Old->getDescribedVarTemplate()) 4322 makeMergedDefinitionVisible(OldTD); 4323 makeMergedDefinitionVisible(Old); 4324 return false; 4325 } else { 4326 Diag(New->getLocation(), diag::err_redefinition) << New; 4327 notePreviousDefinition(Old, New->getLocation()); 4328 New->setInvalidDecl(); 4329 return true; 4330 } 4331 } 4332 4333 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4334 /// no declarator (e.g. "struct foo;") is parsed. 4335 Decl * 4336 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4337 RecordDecl *&AnonRecord) { 4338 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, 4339 AnonRecord); 4340 } 4341 4342 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 4343 // disambiguate entities defined in different scopes. 4344 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 4345 // compatibility. 4346 // We will pick our mangling number depending on which version of MSVC is being 4347 // targeted. 4348 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 4349 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 4350 ? S->getMSCurManglingNumber() 4351 : S->getMSLastManglingNumber(); 4352 } 4353 4354 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 4355 if (!Context.getLangOpts().CPlusPlus) 4356 return; 4357 4358 if (isa<CXXRecordDecl>(Tag->getParent())) { 4359 // If this tag is the direct child of a class, number it if 4360 // it is anonymous. 4361 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 4362 return; 4363 MangleNumberingContext &MCtx = 4364 Context.getManglingNumberContext(Tag->getParent()); 4365 Context.setManglingNumber( 4366 Tag, MCtx.getManglingNumber( 4367 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4368 return; 4369 } 4370 4371 // If this tag isn't a direct child of a class, number it if it is local. 4372 MangleNumberingContext *MCtx; 4373 Decl *ManglingContextDecl; 4374 std::tie(MCtx, ManglingContextDecl) = 4375 getCurrentMangleNumberContext(Tag->getDeclContext()); 4376 if (MCtx) { 4377 Context.setManglingNumber( 4378 Tag, MCtx->getManglingNumber( 4379 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4380 } 4381 } 4382 4383 namespace { 4384 struct NonCLikeKind { 4385 enum { 4386 None, 4387 BaseClass, 4388 DefaultMemberInit, 4389 Lambda, 4390 Friend, 4391 OtherMember, 4392 Invalid, 4393 } Kind = None; 4394 SourceRange Range; 4395 4396 explicit operator bool() { return Kind != None; } 4397 }; 4398 } 4399 4400 /// Determine whether a class is C-like, according to the rules of C++ 4401 /// [dcl.typedef] for anonymous classes with typedef names for linkage. 4402 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) { 4403 if (RD->isInvalidDecl()) 4404 return {NonCLikeKind::Invalid, {}}; 4405 4406 // C++ [dcl.typedef]p9: [P1766R1] 4407 // An unnamed class with a typedef name for linkage purposes shall not 4408 // 4409 // -- have any base classes 4410 if (RD->getNumBases()) 4411 return {NonCLikeKind::BaseClass, 4412 SourceRange(RD->bases_begin()->getBeginLoc(), 4413 RD->bases_end()[-1].getEndLoc())}; 4414 bool Invalid = false; 4415 for (Decl *D : RD->decls()) { 4416 // Don't complain about things we already diagnosed. 4417 if (D->isInvalidDecl()) { 4418 Invalid = true; 4419 continue; 4420 } 4421 4422 // -- have any [...] default member initializers 4423 if (auto *FD = dyn_cast<FieldDecl>(D)) { 4424 if (FD->hasInClassInitializer()) { 4425 auto *Init = FD->getInClassInitializer(); 4426 return {NonCLikeKind::DefaultMemberInit, 4427 Init ? Init->getSourceRange() : D->getSourceRange()}; 4428 } 4429 continue; 4430 } 4431 4432 // FIXME: We don't allow friend declarations. This violates the wording of 4433 // P1766, but not the intent. 4434 if (isa<FriendDecl>(D)) 4435 return {NonCLikeKind::Friend, D->getSourceRange()}; 4436 4437 // -- declare any members other than non-static data members, member 4438 // enumerations, or member classes, 4439 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) || 4440 isa<EnumDecl>(D)) 4441 continue; 4442 auto *MemberRD = dyn_cast<CXXRecordDecl>(D); 4443 if (!MemberRD) { 4444 if (D->isImplicit()) 4445 continue; 4446 return {NonCLikeKind::OtherMember, D->getSourceRange()}; 4447 } 4448 4449 // -- contain a lambda-expression, 4450 if (MemberRD->isLambda()) 4451 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()}; 4452 4453 // and all member classes shall also satisfy these requirements 4454 // (recursively). 4455 if (MemberRD->isThisDeclarationADefinition()) { 4456 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD)) 4457 return Kind; 4458 } 4459 } 4460 4461 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}}; 4462 } 4463 4464 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 4465 TypedefNameDecl *NewTD) { 4466 if (TagFromDeclSpec->isInvalidDecl()) 4467 return; 4468 4469 // Do nothing if the tag already has a name for linkage purposes. 4470 if (TagFromDeclSpec->hasNameForLinkage()) 4471 return; 4472 4473 // A well-formed anonymous tag must always be a TUK_Definition. 4474 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 4475 4476 // The type must match the tag exactly; no qualifiers allowed. 4477 if (!Context.hasSameType(NewTD->getUnderlyingType(), 4478 Context.getTagDeclType(TagFromDeclSpec))) { 4479 if (getLangOpts().CPlusPlus) 4480 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 4481 return; 4482 } 4483 4484 // C++ [dcl.typedef]p9: [P1766R1, applied as DR] 4485 // An unnamed class with a typedef name for linkage purposes shall [be 4486 // C-like]. 4487 // 4488 // FIXME: Also diagnose if we've already computed the linkage. That ideally 4489 // shouldn't happen, but there are constructs that the language rule doesn't 4490 // disallow for which we can't reasonably avoid computing linkage early. 4491 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec); 4492 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD) 4493 : NonCLikeKind(); 4494 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed(); 4495 if (NonCLike || ChangesLinkage) { 4496 if (NonCLike.Kind == NonCLikeKind::Invalid) 4497 return; 4498 4499 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef; 4500 if (ChangesLinkage) { 4501 // If the linkage changes, we can't accept this as an extension. 4502 if (NonCLike.Kind == NonCLikeKind::None) 4503 DiagID = diag::err_typedef_changes_linkage; 4504 else 4505 DiagID = diag::err_non_c_like_anon_struct_in_typedef; 4506 } 4507 4508 SourceLocation FixitLoc = 4509 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart()); 4510 llvm::SmallString<40> TextToInsert; 4511 TextToInsert += ' '; 4512 TextToInsert += NewTD->getIdentifier()->getName(); 4513 4514 Diag(FixitLoc, DiagID) 4515 << isa<TypeAliasDecl>(NewTD) 4516 << FixItHint::CreateInsertion(FixitLoc, TextToInsert); 4517 if (NonCLike.Kind != NonCLikeKind::None) { 4518 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct) 4519 << NonCLike.Kind - 1 << NonCLike.Range; 4520 } 4521 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here) 4522 << NewTD << isa<TypeAliasDecl>(NewTD); 4523 4524 if (ChangesLinkage) 4525 return; 4526 } 4527 4528 // Otherwise, set this as the anon-decl typedef for the tag. 4529 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 4530 } 4531 4532 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 4533 switch (T) { 4534 case DeclSpec::TST_class: 4535 return 0; 4536 case DeclSpec::TST_struct: 4537 return 1; 4538 case DeclSpec::TST_interface: 4539 return 2; 4540 case DeclSpec::TST_union: 4541 return 3; 4542 case DeclSpec::TST_enum: 4543 return 4; 4544 default: 4545 llvm_unreachable("unexpected type specifier"); 4546 } 4547 } 4548 4549 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4550 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 4551 /// parameters to cope with template friend declarations. 4552 Decl * 4553 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4554 MultiTemplateParamsArg TemplateParams, 4555 bool IsExplicitInstantiation, 4556 RecordDecl *&AnonRecord) { 4557 Decl *TagD = nullptr; 4558 TagDecl *Tag = nullptr; 4559 if (DS.getTypeSpecType() == DeclSpec::TST_class || 4560 DS.getTypeSpecType() == DeclSpec::TST_struct || 4561 DS.getTypeSpecType() == DeclSpec::TST_interface || 4562 DS.getTypeSpecType() == DeclSpec::TST_union || 4563 DS.getTypeSpecType() == DeclSpec::TST_enum) { 4564 TagD = DS.getRepAsDecl(); 4565 4566 if (!TagD) // We probably had an error 4567 return nullptr; 4568 4569 // Note that the above type specs guarantee that the 4570 // type rep is a Decl, whereas in many of the others 4571 // it's a Type. 4572 if (isa<TagDecl>(TagD)) 4573 Tag = cast<TagDecl>(TagD); 4574 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 4575 Tag = CTD->getTemplatedDecl(); 4576 } 4577 4578 if (Tag) { 4579 handleTagNumbering(Tag, S); 4580 Tag->setFreeStanding(); 4581 if (Tag->isInvalidDecl()) 4582 return Tag; 4583 } 4584 4585 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 4586 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 4587 // or incomplete types shall not be restrict-qualified." 4588 if (TypeQuals & DeclSpec::TQ_restrict) 4589 Diag(DS.getRestrictSpecLoc(), 4590 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 4591 << DS.getSourceRange(); 4592 } 4593 4594 if (DS.isInlineSpecified()) 4595 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 4596 << getLangOpts().CPlusPlus17; 4597 4598 if (DS.hasConstexprSpecifier()) { 4599 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 4600 // and definitions of functions and variables. 4601 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to 4602 // the declaration of a function or function template 4603 if (Tag) 4604 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 4605 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) 4606 << DS.getConstexprSpecifier(); 4607 else 4608 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind) 4609 << DS.getConstexprSpecifier(); 4610 // Don't emit warnings after this error. 4611 return TagD; 4612 } 4613 4614 DiagnoseFunctionSpecifiers(DS); 4615 4616 if (DS.isFriendSpecified()) { 4617 // If we're dealing with a decl but not a TagDecl, assume that 4618 // whatever routines created it handled the friendship aspect. 4619 if (TagD && !Tag) 4620 return nullptr; 4621 return ActOnFriendTypeDecl(S, DS, TemplateParams); 4622 } 4623 4624 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 4625 bool IsExplicitSpecialization = 4626 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 4627 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 4628 !IsExplicitInstantiation && !IsExplicitSpecialization && 4629 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 4630 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 4631 // nested-name-specifier unless it is an explicit instantiation 4632 // or an explicit specialization. 4633 // 4634 // FIXME: We allow class template partial specializations here too, per the 4635 // obvious intent of DR1819. 4636 // 4637 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 4638 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 4639 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 4640 return nullptr; 4641 } 4642 4643 // Track whether this decl-specifier declares anything. 4644 bool DeclaresAnything = true; 4645 4646 // Handle anonymous struct definitions. 4647 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 4648 if (!Record->getDeclName() && Record->isCompleteDefinition() && 4649 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 4650 if (getLangOpts().CPlusPlus || 4651 Record->getDeclContext()->isRecord()) { 4652 // If CurContext is a DeclContext that can contain statements, 4653 // RecursiveASTVisitor won't visit the decls that 4654 // BuildAnonymousStructOrUnion() will put into CurContext. 4655 // Also store them here so that they can be part of the 4656 // DeclStmt that gets created in this case. 4657 // FIXME: Also return the IndirectFieldDecls created by 4658 // BuildAnonymousStructOr union, for the same reason? 4659 if (CurContext->isFunctionOrMethod()) 4660 AnonRecord = Record; 4661 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 4662 Context.getPrintingPolicy()); 4663 } 4664 4665 DeclaresAnything = false; 4666 } 4667 } 4668 4669 // C11 6.7.2.1p2: 4670 // A struct-declaration that does not declare an anonymous structure or 4671 // anonymous union shall contain a struct-declarator-list. 4672 // 4673 // This rule also existed in C89 and C99; the grammar for struct-declaration 4674 // did not permit a struct-declaration without a struct-declarator-list. 4675 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 4676 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 4677 // Check for Microsoft C extension: anonymous struct/union member. 4678 // Handle 2 kinds of anonymous struct/union: 4679 // struct STRUCT; 4680 // union UNION; 4681 // and 4682 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 4683 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 4684 if ((Tag && Tag->getDeclName()) || 4685 DS.getTypeSpecType() == DeclSpec::TST_typename) { 4686 RecordDecl *Record = nullptr; 4687 if (Tag) 4688 Record = dyn_cast<RecordDecl>(Tag); 4689 else if (const RecordType *RT = 4690 DS.getRepAsType().get()->getAsStructureType()) 4691 Record = RT->getDecl(); 4692 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 4693 Record = UT->getDecl(); 4694 4695 if (Record && getLangOpts().MicrosoftExt) { 4696 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record) 4697 << Record->isUnion() << DS.getSourceRange(); 4698 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 4699 } 4700 4701 DeclaresAnything = false; 4702 } 4703 } 4704 4705 // Skip all the checks below if we have a type error. 4706 if (DS.getTypeSpecType() == DeclSpec::TST_error || 4707 (TagD && TagD->isInvalidDecl())) 4708 return TagD; 4709 4710 if (getLangOpts().CPlusPlus && 4711 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 4712 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 4713 if (Enum->enumerator_begin() == Enum->enumerator_end() && 4714 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 4715 DeclaresAnything = false; 4716 4717 if (!DS.isMissingDeclaratorOk()) { 4718 // Customize diagnostic for a typedef missing a name. 4719 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 4720 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name) 4721 << DS.getSourceRange(); 4722 else 4723 DeclaresAnything = false; 4724 } 4725 4726 if (DS.isModulePrivateSpecified() && 4727 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 4728 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 4729 << Tag->getTagKind() 4730 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 4731 4732 ActOnDocumentableDecl(TagD); 4733 4734 // C 6.7/2: 4735 // A declaration [...] shall declare at least a declarator [...], a tag, 4736 // or the members of an enumeration. 4737 // C++ [dcl.dcl]p3: 4738 // [If there are no declarators], and except for the declaration of an 4739 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 4740 // names into the program, or shall redeclare a name introduced by a 4741 // previous declaration. 4742 if (!DeclaresAnything) { 4743 // In C, we allow this as a (popular) extension / bug. Don't bother 4744 // producing further diagnostics for redundant qualifiers after this. 4745 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); 4746 return TagD; 4747 } 4748 4749 // C++ [dcl.stc]p1: 4750 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 4751 // init-declarator-list of the declaration shall not be empty. 4752 // C++ [dcl.fct.spec]p1: 4753 // If a cv-qualifier appears in a decl-specifier-seq, the 4754 // init-declarator-list of the declaration shall not be empty. 4755 // 4756 // Spurious qualifiers here appear to be valid in C. 4757 unsigned DiagID = diag::warn_standalone_specifier; 4758 if (getLangOpts().CPlusPlus) 4759 DiagID = diag::ext_standalone_specifier; 4760 4761 // Note that a linkage-specification sets a storage class, but 4762 // 'extern "C" struct foo;' is actually valid and not theoretically 4763 // useless. 4764 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 4765 if (SCS == DeclSpec::SCS_mutable) 4766 // Since mutable is not a viable storage class specifier in C, there is 4767 // no reason to treat it as an extension. Instead, diagnose as an error. 4768 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 4769 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 4770 Diag(DS.getStorageClassSpecLoc(), DiagID) 4771 << DeclSpec::getSpecifierName(SCS); 4772 } 4773 4774 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 4775 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 4776 << DeclSpec::getSpecifierName(TSCS); 4777 if (DS.getTypeQualifiers()) { 4778 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4779 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 4780 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4781 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 4782 // Restrict is covered above. 4783 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4784 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 4785 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4786 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 4787 } 4788 4789 // Warn about ignored type attributes, for example: 4790 // __attribute__((aligned)) struct A; 4791 // Attributes should be placed after tag to apply to type declaration. 4792 if (!DS.getAttributes().empty()) { 4793 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 4794 if (TypeSpecType == DeclSpec::TST_class || 4795 TypeSpecType == DeclSpec::TST_struct || 4796 TypeSpecType == DeclSpec::TST_interface || 4797 TypeSpecType == DeclSpec::TST_union || 4798 TypeSpecType == DeclSpec::TST_enum) { 4799 for (const ParsedAttr &AL : DS.getAttributes()) 4800 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored) 4801 << AL << GetDiagnosticTypeSpecifierID(TypeSpecType); 4802 } 4803 } 4804 4805 return TagD; 4806 } 4807 4808 /// We are trying to inject an anonymous member into the given scope; 4809 /// check if there's an existing declaration that can't be overloaded. 4810 /// 4811 /// \return true if this is a forbidden redeclaration 4812 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 4813 Scope *S, 4814 DeclContext *Owner, 4815 DeclarationName Name, 4816 SourceLocation NameLoc, 4817 bool IsUnion) { 4818 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 4819 Sema::ForVisibleRedeclaration); 4820 if (!SemaRef.LookupName(R, S)) return false; 4821 4822 // Pick a representative declaration. 4823 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 4824 assert(PrevDecl && "Expected a non-null Decl"); 4825 4826 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 4827 return false; 4828 4829 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 4830 << IsUnion << Name; 4831 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4832 4833 return true; 4834 } 4835 4836 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 4837 /// anonymous struct or union AnonRecord into the owning context Owner 4838 /// and scope S. This routine will be invoked just after we realize 4839 /// that an unnamed union or struct is actually an anonymous union or 4840 /// struct, e.g., 4841 /// 4842 /// @code 4843 /// union { 4844 /// int i; 4845 /// float f; 4846 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 4847 /// // f into the surrounding scope.x 4848 /// @endcode 4849 /// 4850 /// This routine is recursive, injecting the names of nested anonymous 4851 /// structs/unions into the owning context and scope as well. 4852 static bool 4853 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 4854 RecordDecl *AnonRecord, AccessSpecifier AS, 4855 SmallVectorImpl<NamedDecl *> &Chaining) { 4856 bool Invalid = false; 4857 4858 // Look every FieldDecl and IndirectFieldDecl with a name. 4859 for (auto *D : AnonRecord->decls()) { 4860 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 4861 cast<NamedDecl>(D)->getDeclName()) { 4862 ValueDecl *VD = cast<ValueDecl>(D); 4863 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 4864 VD->getLocation(), 4865 AnonRecord->isUnion())) { 4866 // C++ [class.union]p2: 4867 // The names of the members of an anonymous union shall be 4868 // distinct from the names of any other entity in the 4869 // scope in which the anonymous union is declared. 4870 Invalid = true; 4871 } else { 4872 // C++ [class.union]p2: 4873 // For the purpose of name lookup, after the anonymous union 4874 // definition, the members of the anonymous union are 4875 // considered to have been defined in the scope in which the 4876 // anonymous union is declared. 4877 unsigned OldChainingSize = Chaining.size(); 4878 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 4879 Chaining.append(IF->chain_begin(), IF->chain_end()); 4880 else 4881 Chaining.push_back(VD); 4882 4883 assert(Chaining.size() >= 2); 4884 NamedDecl **NamedChain = 4885 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 4886 for (unsigned i = 0; i < Chaining.size(); i++) 4887 NamedChain[i] = Chaining[i]; 4888 4889 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 4890 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 4891 VD->getType(), {NamedChain, Chaining.size()}); 4892 4893 for (const auto *Attr : VD->attrs()) 4894 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 4895 4896 IndirectField->setAccess(AS); 4897 IndirectField->setImplicit(); 4898 SemaRef.PushOnScopeChains(IndirectField, S); 4899 4900 // That includes picking up the appropriate access specifier. 4901 if (AS != AS_none) IndirectField->setAccess(AS); 4902 4903 Chaining.resize(OldChainingSize); 4904 } 4905 } 4906 } 4907 4908 return Invalid; 4909 } 4910 4911 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 4912 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 4913 /// illegal input values are mapped to SC_None. 4914 static StorageClass 4915 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 4916 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 4917 assert(StorageClassSpec != DeclSpec::SCS_typedef && 4918 "Parser allowed 'typedef' as storage class VarDecl."); 4919 switch (StorageClassSpec) { 4920 case DeclSpec::SCS_unspecified: return SC_None; 4921 case DeclSpec::SCS_extern: 4922 if (DS.isExternInLinkageSpec()) 4923 return SC_None; 4924 return SC_Extern; 4925 case DeclSpec::SCS_static: return SC_Static; 4926 case DeclSpec::SCS_auto: return SC_Auto; 4927 case DeclSpec::SCS_register: return SC_Register; 4928 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 4929 // Illegal SCSs map to None: error reporting is up to the caller. 4930 case DeclSpec::SCS_mutable: // Fall through. 4931 case DeclSpec::SCS_typedef: return SC_None; 4932 } 4933 llvm_unreachable("unknown storage class specifier"); 4934 } 4935 4936 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 4937 assert(Record->hasInClassInitializer()); 4938 4939 for (const auto *I : Record->decls()) { 4940 const auto *FD = dyn_cast<FieldDecl>(I); 4941 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 4942 FD = IFD->getAnonField(); 4943 if (FD && FD->hasInClassInitializer()) 4944 return FD->getLocation(); 4945 } 4946 4947 llvm_unreachable("couldn't find in-class initializer"); 4948 } 4949 4950 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4951 SourceLocation DefaultInitLoc) { 4952 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4953 return; 4954 4955 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 4956 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 4957 } 4958 4959 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4960 CXXRecordDecl *AnonUnion) { 4961 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4962 return; 4963 4964 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 4965 } 4966 4967 /// BuildAnonymousStructOrUnion - Handle the declaration of an 4968 /// anonymous structure or union. Anonymous unions are a C++ feature 4969 /// (C++ [class.union]) and a C11 feature; anonymous structures 4970 /// are a C11 feature and GNU C++ extension. 4971 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 4972 AccessSpecifier AS, 4973 RecordDecl *Record, 4974 const PrintingPolicy &Policy) { 4975 DeclContext *Owner = Record->getDeclContext(); 4976 4977 // Diagnose whether this anonymous struct/union is an extension. 4978 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 4979 Diag(Record->getLocation(), diag::ext_anonymous_union); 4980 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 4981 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 4982 else if (!Record->isUnion() && !getLangOpts().C11) 4983 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 4984 4985 // C and C++ require different kinds of checks for anonymous 4986 // structs/unions. 4987 bool Invalid = false; 4988 if (getLangOpts().CPlusPlus) { 4989 const char *PrevSpec = nullptr; 4990 if (Record->isUnion()) { 4991 // C++ [class.union]p6: 4992 // C++17 [class.union.anon]p2: 4993 // Anonymous unions declared in a named namespace or in the 4994 // global namespace shall be declared static. 4995 unsigned DiagID; 4996 DeclContext *OwnerScope = Owner->getRedeclContext(); 4997 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 4998 (OwnerScope->isTranslationUnit() || 4999 (OwnerScope->isNamespace() && 5000 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) { 5001 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 5002 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 5003 5004 // Recover by adding 'static'. 5005 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 5006 PrevSpec, DiagID, Policy); 5007 } 5008 // C++ [class.union]p6: 5009 // A storage class is not allowed in a declaration of an 5010 // anonymous union in a class scope. 5011 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 5012 isa<RecordDecl>(Owner)) { 5013 Diag(DS.getStorageClassSpecLoc(), 5014 diag::err_anonymous_union_with_storage_spec) 5015 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 5016 5017 // Recover by removing the storage specifier. 5018 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 5019 SourceLocation(), 5020 PrevSpec, DiagID, Context.getPrintingPolicy()); 5021 } 5022 } 5023 5024 // Ignore const/volatile/restrict qualifiers. 5025 if (DS.getTypeQualifiers()) { 5026 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 5027 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 5028 << Record->isUnion() << "const" 5029 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 5030 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 5031 Diag(DS.getVolatileSpecLoc(), 5032 diag::ext_anonymous_struct_union_qualified) 5033 << Record->isUnion() << "volatile" 5034 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 5035 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 5036 Diag(DS.getRestrictSpecLoc(), 5037 diag::ext_anonymous_struct_union_qualified) 5038 << Record->isUnion() << "restrict" 5039 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 5040 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 5041 Diag(DS.getAtomicSpecLoc(), 5042 diag::ext_anonymous_struct_union_qualified) 5043 << Record->isUnion() << "_Atomic" 5044 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 5045 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 5046 Diag(DS.getUnalignedSpecLoc(), 5047 diag::ext_anonymous_struct_union_qualified) 5048 << Record->isUnion() << "__unaligned" 5049 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 5050 5051 DS.ClearTypeQualifiers(); 5052 } 5053 5054 // C++ [class.union]p2: 5055 // The member-specification of an anonymous union shall only 5056 // define non-static data members. [Note: nested types and 5057 // functions cannot be declared within an anonymous union. ] 5058 for (auto *Mem : Record->decls()) { 5059 // Ignore invalid declarations; we already diagnosed them. 5060 if (Mem->isInvalidDecl()) 5061 continue; 5062 5063 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 5064 // C++ [class.union]p3: 5065 // An anonymous union shall not have private or protected 5066 // members (clause 11). 5067 assert(FD->getAccess() != AS_none); 5068 if (FD->getAccess() != AS_public) { 5069 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 5070 << Record->isUnion() << (FD->getAccess() == AS_protected); 5071 Invalid = true; 5072 } 5073 5074 // C++ [class.union]p1 5075 // An object of a class with a non-trivial constructor, a non-trivial 5076 // copy constructor, a non-trivial destructor, or a non-trivial copy 5077 // assignment operator cannot be a member of a union, nor can an 5078 // array of such objects. 5079 if (CheckNontrivialField(FD)) 5080 Invalid = true; 5081 } else if (Mem->isImplicit()) { 5082 // Any implicit members are fine. 5083 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 5084 // This is a type that showed up in an 5085 // elaborated-type-specifier inside the anonymous struct or 5086 // union, but which actually declares a type outside of the 5087 // anonymous struct or union. It's okay. 5088 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 5089 if (!MemRecord->isAnonymousStructOrUnion() && 5090 MemRecord->getDeclName()) { 5091 // Visual C++ allows type definition in anonymous struct or union. 5092 if (getLangOpts().MicrosoftExt) 5093 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 5094 << Record->isUnion(); 5095 else { 5096 // This is a nested type declaration. 5097 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 5098 << Record->isUnion(); 5099 Invalid = true; 5100 } 5101 } else { 5102 // This is an anonymous type definition within another anonymous type. 5103 // This is a popular extension, provided by Plan9, MSVC and GCC, but 5104 // not part of standard C++. 5105 Diag(MemRecord->getLocation(), 5106 diag::ext_anonymous_record_with_anonymous_type) 5107 << Record->isUnion(); 5108 } 5109 } else if (isa<AccessSpecDecl>(Mem)) { 5110 // Any access specifier is fine. 5111 } else if (isa<StaticAssertDecl>(Mem)) { 5112 // In C++1z, static_assert declarations are also fine. 5113 } else { 5114 // We have something that isn't a non-static data 5115 // member. Complain about it. 5116 unsigned DK = diag::err_anonymous_record_bad_member; 5117 if (isa<TypeDecl>(Mem)) 5118 DK = diag::err_anonymous_record_with_type; 5119 else if (isa<FunctionDecl>(Mem)) 5120 DK = diag::err_anonymous_record_with_function; 5121 else if (isa<VarDecl>(Mem)) 5122 DK = diag::err_anonymous_record_with_static; 5123 5124 // Visual C++ allows type definition in anonymous struct or union. 5125 if (getLangOpts().MicrosoftExt && 5126 DK == diag::err_anonymous_record_with_type) 5127 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 5128 << Record->isUnion(); 5129 else { 5130 Diag(Mem->getLocation(), DK) << Record->isUnion(); 5131 Invalid = true; 5132 } 5133 } 5134 } 5135 5136 // C++11 [class.union]p8 (DR1460): 5137 // At most one variant member of a union may have a 5138 // brace-or-equal-initializer. 5139 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 5140 Owner->isRecord()) 5141 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 5142 cast<CXXRecordDecl>(Record)); 5143 } 5144 5145 if (!Record->isUnion() && !Owner->isRecord()) { 5146 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 5147 << getLangOpts().CPlusPlus; 5148 Invalid = true; 5149 } 5150 5151 // C++ [dcl.dcl]p3: 5152 // [If there are no declarators], and except for the declaration of an 5153 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 5154 // names into the program 5155 // C++ [class.mem]p2: 5156 // each such member-declaration shall either declare at least one member 5157 // name of the class or declare at least one unnamed bit-field 5158 // 5159 // For C this is an error even for a named struct, and is diagnosed elsewhere. 5160 if (getLangOpts().CPlusPlus && Record->field_empty()) 5161 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); 5162 5163 // Mock up a declarator. 5164 Declarator Dc(DS, DeclaratorContext::MemberContext); 5165 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5166 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 5167 5168 // Create a declaration for this anonymous struct/union. 5169 NamedDecl *Anon = nullptr; 5170 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 5171 Anon = FieldDecl::Create( 5172 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(), 5173 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo, 5174 /*BitWidth=*/nullptr, /*Mutable=*/false, 5175 /*InitStyle=*/ICIS_NoInit); 5176 Anon->setAccess(AS); 5177 ProcessDeclAttributes(S, Anon, Dc); 5178 5179 if (getLangOpts().CPlusPlus) 5180 FieldCollector->Add(cast<FieldDecl>(Anon)); 5181 } else { 5182 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 5183 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 5184 if (SCSpec == DeclSpec::SCS_mutable) { 5185 // mutable can only appear on non-static class members, so it's always 5186 // an error here 5187 Diag(Record->getLocation(), diag::err_mutable_nonmember); 5188 Invalid = true; 5189 SC = SC_None; 5190 } 5191 5192 assert(DS.getAttributes().empty() && "No attribute expected"); 5193 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(), 5194 Record->getLocation(), /*IdentifierInfo=*/nullptr, 5195 Context.getTypeDeclType(Record), TInfo, SC); 5196 5197 // Default-initialize the implicit variable. This initialization will be 5198 // trivial in almost all cases, except if a union member has an in-class 5199 // initializer: 5200 // union { int n = 0; }; 5201 ActOnUninitializedDecl(Anon); 5202 } 5203 Anon->setImplicit(); 5204 5205 // Mark this as an anonymous struct/union type. 5206 Record->setAnonymousStructOrUnion(true); 5207 5208 // Add the anonymous struct/union object to the current 5209 // context. We'll be referencing this object when we refer to one of 5210 // its members. 5211 Owner->addDecl(Anon); 5212 5213 // Inject the members of the anonymous struct/union into the owning 5214 // context and into the identifier resolver chain for name lookup 5215 // purposes. 5216 SmallVector<NamedDecl*, 2> Chain; 5217 Chain.push_back(Anon); 5218 5219 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 5220 Invalid = true; 5221 5222 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 5223 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 5224 MangleNumberingContext *MCtx; 5225 Decl *ManglingContextDecl; 5226 std::tie(MCtx, ManglingContextDecl) = 5227 getCurrentMangleNumberContext(NewVD->getDeclContext()); 5228 if (MCtx) { 5229 Context.setManglingNumber( 5230 NewVD, MCtx->getManglingNumber( 5231 NewVD, getMSManglingNumber(getLangOpts(), S))); 5232 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 5233 } 5234 } 5235 } 5236 5237 if (Invalid) 5238 Anon->setInvalidDecl(); 5239 5240 return Anon; 5241 } 5242 5243 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 5244 /// Microsoft C anonymous structure. 5245 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 5246 /// Example: 5247 /// 5248 /// struct A { int a; }; 5249 /// struct B { struct A; int b; }; 5250 /// 5251 /// void foo() { 5252 /// B var; 5253 /// var.a = 3; 5254 /// } 5255 /// 5256 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 5257 RecordDecl *Record) { 5258 assert(Record && "expected a record!"); 5259 5260 // Mock up a declarator. 5261 Declarator Dc(DS, DeclaratorContext::TypeNameContext); 5262 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5263 assert(TInfo && "couldn't build declarator info for anonymous struct"); 5264 5265 auto *ParentDecl = cast<RecordDecl>(CurContext); 5266 QualType RecTy = Context.getTypeDeclType(Record); 5267 5268 // Create a declaration for this anonymous struct. 5269 NamedDecl *Anon = 5270 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(), 5271 /*IdentifierInfo=*/nullptr, RecTy, TInfo, 5272 /*BitWidth=*/nullptr, /*Mutable=*/false, 5273 /*InitStyle=*/ICIS_NoInit); 5274 Anon->setImplicit(); 5275 5276 // Add the anonymous struct object to the current context. 5277 CurContext->addDecl(Anon); 5278 5279 // Inject the members of the anonymous struct into the current 5280 // context and into the identifier resolver chain for name lookup 5281 // purposes. 5282 SmallVector<NamedDecl*, 2> Chain; 5283 Chain.push_back(Anon); 5284 5285 RecordDecl *RecordDef = Record->getDefinition(); 5286 if (RequireCompleteSizedType(Anon->getLocation(), RecTy, 5287 diag::err_field_incomplete_or_sizeless) || 5288 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 5289 AS_none, Chain)) { 5290 Anon->setInvalidDecl(); 5291 ParentDecl->setInvalidDecl(); 5292 } 5293 5294 return Anon; 5295 } 5296 5297 /// GetNameForDeclarator - Determine the full declaration name for the 5298 /// given Declarator. 5299 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 5300 return GetNameFromUnqualifiedId(D.getName()); 5301 } 5302 5303 /// Retrieves the declaration name from a parsed unqualified-id. 5304 DeclarationNameInfo 5305 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 5306 DeclarationNameInfo NameInfo; 5307 NameInfo.setLoc(Name.StartLocation); 5308 5309 switch (Name.getKind()) { 5310 5311 case UnqualifiedIdKind::IK_ImplicitSelfParam: 5312 case UnqualifiedIdKind::IK_Identifier: 5313 NameInfo.setName(Name.Identifier); 5314 return NameInfo; 5315 5316 case UnqualifiedIdKind::IK_DeductionGuideName: { 5317 // C++ [temp.deduct.guide]p3: 5318 // The simple-template-id shall name a class template specialization. 5319 // The template-name shall be the same identifier as the template-name 5320 // of the simple-template-id. 5321 // These together intend to imply that the template-name shall name a 5322 // class template. 5323 // FIXME: template<typename T> struct X {}; 5324 // template<typename T> using Y = X<T>; 5325 // Y(int) -> Y<int>; 5326 // satisfies these rules but does not name a class template. 5327 TemplateName TN = Name.TemplateName.get().get(); 5328 auto *Template = TN.getAsTemplateDecl(); 5329 if (!Template || !isa<ClassTemplateDecl>(Template)) { 5330 Diag(Name.StartLocation, 5331 diag::err_deduction_guide_name_not_class_template) 5332 << (int)getTemplateNameKindForDiagnostics(TN) << TN; 5333 if (Template) 5334 Diag(Template->getLocation(), diag::note_template_decl_here); 5335 return DeclarationNameInfo(); 5336 } 5337 5338 NameInfo.setName( 5339 Context.DeclarationNames.getCXXDeductionGuideName(Template)); 5340 return NameInfo; 5341 } 5342 5343 case UnqualifiedIdKind::IK_OperatorFunctionId: 5344 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 5345 Name.OperatorFunctionId.Operator)); 5346 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 5347 = Name.OperatorFunctionId.SymbolLocations[0]; 5348 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 5349 = Name.EndLocation.getRawEncoding(); 5350 return NameInfo; 5351 5352 case UnqualifiedIdKind::IK_LiteralOperatorId: 5353 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 5354 Name.Identifier)); 5355 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 5356 return NameInfo; 5357 5358 case UnqualifiedIdKind::IK_ConversionFunctionId: { 5359 TypeSourceInfo *TInfo; 5360 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 5361 if (Ty.isNull()) 5362 return DeclarationNameInfo(); 5363 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 5364 Context.getCanonicalType(Ty))); 5365 NameInfo.setNamedTypeInfo(TInfo); 5366 return NameInfo; 5367 } 5368 5369 case UnqualifiedIdKind::IK_ConstructorName: { 5370 TypeSourceInfo *TInfo; 5371 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 5372 if (Ty.isNull()) 5373 return DeclarationNameInfo(); 5374 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5375 Context.getCanonicalType(Ty))); 5376 NameInfo.setNamedTypeInfo(TInfo); 5377 return NameInfo; 5378 } 5379 5380 case UnqualifiedIdKind::IK_ConstructorTemplateId: { 5381 // In well-formed code, we can only have a constructor 5382 // template-id that refers to the current context, so go there 5383 // to find the actual type being constructed. 5384 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 5385 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 5386 return DeclarationNameInfo(); 5387 5388 // Determine the type of the class being constructed. 5389 QualType CurClassType = Context.getTypeDeclType(CurClass); 5390 5391 // FIXME: Check two things: that the template-id names the same type as 5392 // CurClassType, and that the template-id does not occur when the name 5393 // was qualified. 5394 5395 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5396 Context.getCanonicalType(CurClassType))); 5397 // FIXME: should we retrieve TypeSourceInfo? 5398 NameInfo.setNamedTypeInfo(nullptr); 5399 return NameInfo; 5400 } 5401 5402 case UnqualifiedIdKind::IK_DestructorName: { 5403 TypeSourceInfo *TInfo; 5404 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 5405 if (Ty.isNull()) 5406 return DeclarationNameInfo(); 5407 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 5408 Context.getCanonicalType(Ty))); 5409 NameInfo.setNamedTypeInfo(TInfo); 5410 return NameInfo; 5411 } 5412 5413 case UnqualifiedIdKind::IK_TemplateId: { 5414 TemplateName TName = Name.TemplateId->Template.get(); 5415 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 5416 return Context.getNameForTemplate(TName, TNameLoc); 5417 } 5418 5419 } // switch (Name.getKind()) 5420 5421 llvm_unreachable("Unknown name kind"); 5422 } 5423 5424 static QualType getCoreType(QualType Ty) { 5425 do { 5426 if (Ty->isPointerType() || Ty->isReferenceType()) 5427 Ty = Ty->getPointeeType(); 5428 else if (Ty->isArrayType()) 5429 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 5430 else 5431 return Ty.withoutLocalFastQualifiers(); 5432 } while (true); 5433 } 5434 5435 /// hasSimilarParameters - Determine whether the C++ functions Declaration 5436 /// and Definition have "nearly" matching parameters. This heuristic is 5437 /// used to improve diagnostics in the case where an out-of-line function 5438 /// definition doesn't match any declaration within the class or namespace. 5439 /// Also sets Params to the list of indices to the parameters that differ 5440 /// between the declaration and the definition. If hasSimilarParameters 5441 /// returns true and Params is empty, then all of the parameters match. 5442 static bool hasSimilarParameters(ASTContext &Context, 5443 FunctionDecl *Declaration, 5444 FunctionDecl *Definition, 5445 SmallVectorImpl<unsigned> &Params) { 5446 Params.clear(); 5447 if (Declaration->param_size() != Definition->param_size()) 5448 return false; 5449 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 5450 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 5451 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 5452 5453 // The parameter types are identical 5454 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy)) 5455 continue; 5456 5457 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 5458 QualType DefParamBaseTy = getCoreType(DefParamTy); 5459 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 5460 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 5461 5462 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 5463 (DeclTyName && DeclTyName == DefTyName)) 5464 Params.push_back(Idx); 5465 else // The two parameters aren't even close 5466 return false; 5467 } 5468 5469 return true; 5470 } 5471 5472 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 5473 /// declarator needs to be rebuilt in the current instantiation. 5474 /// Any bits of declarator which appear before the name are valid for 5475 /// consideration here. That's specifically the type in the decl spec 5476 /// and the base type in any member-pointer chunks. 5477 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 5478 DeclarationName Name) { 5479 // The types we specifically need to rebuild are: 5480 // - typenames, typeofs, and decltypes 5481 // - types which will become injected class names 5482 // Of course, we also need to rebuild any type referencing such a 5483 // type. It's safest to just say "dependent", but we call out a 5484 // few cases here. 5485 5486 DeclSpec &DS = D.getMutableDeclSpec(); 5487 switch (DS.getTypeSpecType()) { 5488 case DeclSpec::TST_typename: 5489 case DeclSpec::TST_typeofType: 5490 case DeclSpec::TST_underlyingType: 5491 case DeclSpec::TST_atomic: { 5492 // Grab the type from the parser. 5493 TypeSourceInfo *TSI = nullptr; 5494 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 5495 if (T.isNull() || !T->isDependentType()) break; 5496 5497 // Make sure there's a type source info. This isn't really much 5498 // of a waste; most dependent types should have type source info 5499 // attached already. 5500 if (!TSI) 5501 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 5502 5503 // Rebuild the type in the current instantiation. 5504 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 5505 if (!TSI) return true; 5506 5507 // Store the new type back in the decl spec. 5508 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 5509 DS.UpdateTypeRep(LocType); 5510 break; 5511 } 5512 5513 case DeclSpec::TST_decltype: 5514 case DeclSpec::TST_typeofExpr: { 5515 Expr *E = DS.getRepAsExpr(); 5516 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 5517 if (Result.isInvalid()) return true; 5518 DS.UpdateExprRep(Result.get()); 5519 break; 5520 } 5521 5522 default: 5523 // Nothing to do for these decl specs. 5524 break; 5525 } 5526 5527 // It doesn't matter what order we do this in. 5528 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 5529 DeclaratorChunk &Chunk = D.getTypeObject(I); 5530 5531 // The only type information in the declarator which can come 5532 // before the declaration name is the base type of a member 5533 // pointer. 5534 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 5535 continue; 5536 5537 // Rebuild the scope specifier in-place. 5538 CXXScopeSpec &SS = Chunk.Mem.Scope(); 5539 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 5540 return true; 5541 } 5542 5543 return false; 5544 } 5545 5546 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 5547 D.setFunctionDefinitionKind(FDK_Declaration); 5548 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 5549 5550 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 5551 Dcl && Dcl->getDeclContext()->isFileContext()) 5552 Dcl->setTopLevelDeclInObjCContainer(); 5553 5554 if (getLangOpts().OpenCL) 5555 setCurrentOpenCLExtensionForDecl(Dcl); 5556 5557 return Dcl; 5558 } 5559 5560 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 5561 /// If T is the name of a class, then each of the following shall have a 5562 /// name different from T: 5563 /// - every static data member of class T; 5564 /// - every member function of class T 5565 /// - every member of class T that is itself a type; 5566 /// \returns true if the declaration name violates these rules. 5567 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 5568 DeclarationNameInfo NameInfo) { 5569 DeclarationName Name = NameInfo.getName(); 5570 5571 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 5572 while (Record && Record->isAnonymousStructOrUnion()) 5573 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 5574 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 5575 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 5576 return true; 5577 } 5578 5579 return false; 5580 } 5581 5582 /// Diagnose a declaration whose declarator-id has the given 5583 /// nested-name-specifier. 5584 /// 5585 /// \param SS The nested-name-specifier of the declarator-id. 5586 /// 5587 /// \param DC The declaration context to which the nested-name-specifier 5588 /// resolves. 5589 /// 5590 /// \param Name The name of the entity being declared. 5591 /// 5592 /// \param Loc The location of the name of the entity being declared. 5593 /// 5594 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus 5595 /// we're declaring an explicit / partial specialization / instantiation. 5596 /// 5597 /// \returns true if we cannot safely recover from this error, false otherwise. 5598 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 5599 DeclarationName Name, 5600 SourceLocation Loc, bool IsTemplateId) { 5601 DeclContext *Cur = CurContext; 5602 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 5603 Cur = Cur->getParent(); 5604 5605 // If the user provided a superfluous scope specifier that refers back to the 5606 // class in which the entity is already declared, diagnose and ignore it. 5607 // 5608 // class X { 5609 // void X::f(); 5610 // }; 5611 // 5612 // Note, it was once ill-formed to give redundant qualification in all 5613 // contexts, but that rule was removed by DR482. 5614 if (Cur->Equals(DC)) { 5615 if (Cur->isRecord()) { 5616 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 5617 : diag::err_member_extra_qualification) 5618 << Name << FixItHint::CreateRemoval(SS.getRange()); 5619 SS.clear(); 5620 } else { 5621 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 5622 } 5623 return false; 5624 } 5625 5626 // Check whether the qualifying scope encloses the scope of the original 5627 // declaration. For a template-id, we perform the checks in 5628 // CheckTemplateSpecializationScope. 5629 if (!Cur->Encloses(DC) && !IsTemplateId) { 5630 if (Cur->isRecord()) 5631 Diag(Loc, diag::err_member_qualification) 5632 << Name << SS.getRange(); 5633 else if (isa<TranslationUnitDecl>(DC)) 5634 Diag(Loc, diag::err_invalid_declarator_global_scope) 5635 << Name << SS.getRange(); 5636 else if (isa<FunctionDecl>(Cur)) 5637 Diag(Loc, diag::err_invalid_declarator_in_function) 5638 << Name << SS.getRange(); 5639 else if (isa<BlockDecl>(Cur)) 5640 Diag(Loc, diag::err_invalid_declarator_in_block) 5641 << Name << SS.getRange(); 5642 else 5643 Diag(Loc, diag::err_invalid_declarator_scope) 5644 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 5645 5646 return true; 5647 } 5648 5649 if (Cur->isRecord()) { 5650 // Cannot qualify members within a class. 5651 Diag(Loc, diag::err_member_qualification) 5652 << Name << SS.getRange(); 5653 SS.clear(); 5654 5655 // C++ constructors and destructors with incorrect scopes can break 5656 // our AST invariants by having the wrong underlying types. If 5657 // that's the case, then drop this declaration entirely. 5658 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 5659 Name.getNameKind() == DeclarationName::CXXDestructorName) && 5660 !Context.hasSameType(Name.getCXXNameType(), 5661 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 5662 return true; 5663 5664 return false; 5665 } 5666 5667 // C++11 [dcl.meaning]p1: 5668 // [...] "The nested-name-specifier of the qualified declarator-id shall 5669 // not begin with a decltype-specifer" 5670 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 5671 while (SpecLoc.getPrefix()) 5672 SpecLoc = SpecLoc.getPrefix(); 5673 if (dyn_cast_or_null<DecltypeType>( 5674 SpecLoc.getNestedNameSpecifier()->getAsType())) 5675 Diag(Loc, diag::err_decltype_in_declarator) 5676 << SpecLoc.getTypeLoc().getSourceRange(); 5677 5678 return false; 5679 } 5680 5681 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 5682 MultiTemplateParamsArg TemplateParamLists) { 5683 // TODO: consider using NameInfo for diagnostic. 5684 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5685 DeclarationName Name = NameInfo.getName(); 5686 5687 // All of these full declarators require an identifier. If it doesn't have 5688 // one, the ParsedFreeStandingDeclSpec action should be used. 5689 if (D.isDecompositionDeclarator()) { 5690 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 5691 } else if (!Name) { 5692 if (!D.isInvalidType()) // Reject this if we think it is valid. 5693 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident) 5694 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 5695 return nullptr; 5696 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 5697 return nullptr; 5698 5699 // The scope passed in may not be a decl scope. Zip up the scope tree until 5700 // we find one that is. 5701 while ((S->getFlags() & Scope::DeclScope) == 0 || 5702 (S->getFlags() & Scope::TemplateParamScope) != 0) 5703 S = S->getParent(); 5704 5705 DeclContext *DC = CurContext; 5706 if (D.getCXXScopeSpec().isInvalid()) 5707 D.setInvalidType(); 5708 else if (D.getCXXScopeSpec().isSet()) { 5709 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 5710 UPPC_DeclarationQualifier)) 5711 return nullptr; 5712 5713 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 5714 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 5715 if (!DC || isa<EnumDecl>(DC)) { 5716 // If we could not compute the declaration context, it's because the 5717 // declaration context is dependent but does not refer to a class, 5718 // class template, or class template partial specialization. Complain 5719 // and return early, to avoid the coming semantic disaster. 5720 Diag(D.getIdentifierLoc(), 5721 diag::err_template_qualified_declarator_no_match) 5722 << D.getCXXScopeSpec().getScopeRep() 5723 << D.getCXXScopeSpec().getRange(); 5724 return nullptr; 5725 } 5726 bool IsDependentContext = DC->isDependentContext(); 5727 5728 if (!IsDependentContext && 5729 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 5730 return nullptr; 5731 5732 // If a class is incomplete, do not parse entities inside it. 5733 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 5734 Diag(D.getIdentifierLoc(), 5735 diag::err_member_def_undefined_record) 5736 << Name << DC << D.getCXXScopeSpec().getRange(); 5737 return nullptr; 5738 } 5739 if (!D.getDeclSpec().isFriendSpecified()) { 5740 if (diagnoseQualifiedDeclaration( 5741 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(), 5742 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) { 5743 if (DC->isRecord()) 5744 return nullptr; 5745 5746 D.setInvalidType(); 5747 } 5748 } 5749 5750 // Check whether we need to rebuild the type of the given 5751 // declaration in the current instantiation. 5752 if (EnteringContext && IsDependentContext && 5753 TemplateParamLists.size() != 0) { 5754 ContextRAII SavedContext(*this, DC); 5755 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 5756 D.setInvalidType(); 5757 } 5758 } 5759 5760 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5761 QualType R = TInfo->getType(); 5762 5763 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 5764 UPPC_DeclarationType)) 5765 D.setInvalidType(); 5766 5767 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5768 forRedeclarationInCurContext()); 5769 5770 // See if this is a redefinition of a variable in the same scope. 5771 if (!D.getCXXScopeSpec().isSet()) { 5772 bool IsLinkageLookup = false; 5773 bool CreateBuiltins = false; 5774 5775 // If the declaration we're planning to build will be a function 5776 // or object with linkage, then look for another declaration with 5777 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 5778 // 5779 // If the declaration we're planning to build will be declared with 5780 // external linkage in the translation unit, create any builtin with 5781 // the same name. 5782 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5783 /* Do nothing*/; 5784 else if (CurContext->isFunctionOrMethod() && 5785 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 5786 R->isFunctionType())) { 5787 IsLinkageLookup = true; 5788 CreateBuiltins = 5789 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 5790 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 5791 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 5792 CreateBuiltins = true; 5793 5794 if (IsLinkageLookup) { 5795 Previous.clear(LookupRedeclarationWithLinkage); 5796 Previous.setRedeclarationKind(ForExternalRedeclaration); 5797 } 5798 5799 LookupName(Previous, S, CreateBuiltins); 5800 } else { // Something like "int foo::x;" 5801 LookupQualifiedName(Previous, DC); 5802 5803 // C++ [dcl.meaning]p1: 5804 // When the declarator-id is qualified, the declaration shall refer to a 5805 // previously declared member of the class or namespace to which the 5806 // qualifier refers (or, in the case of a namespace, of an element of the 5807 // inline namespace set of that namespace (7.3.1)) or to a specialization 5808 // thereof; [...] 5809 // 5810 // Note that we already checked the context above, and that we do not have 5811 // enough information to make sure that Previous contains the declaration 5812 // we want to match. For example, given: 5813 // 5814 // class X { 5815 // void f(); 5816 // void f(float); 5817 // }; 5818 // 5819 // void X::f(int) { } // ill-formed 5820 // 5821 // In this case, Previous will point to the overload set 5822 // containing the two f's declared in X, but neither of them 5823 // matches. 5824 5825 // C++ [dcl.meaning]p1: 5826 // [...] the member shall not merely have been introduced by a 5827 // using-declaration in the scope of the class or namespace nominated by 5828 // the nested-name-specifier of the declarator-id. 5829 RemoveUsingDecls(Previous); 5830 } 5831 5832 if (Previous.isSingleResult() && 5833 Previous.getFoundDecl()->isTemplateParameter()) { 5834 // Maybe we will complain about the shadowed template parameter. 5835 if (!D.isInvalidType()) 5836 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 5837 Previous.getFoundDecl()); 5838 5839 // Just pretend that we didn't see the previous declaration. 5840 Previous.clear(); 5841 } 5842 5843 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 5844 // Forget that the previous declaration is the injected-class-name. 5845 Previous.clear(); 5846 5847 // In C++, the previous declaration we find might be a tag type 5848 // (class or enum). In this case, the new declaration will hide the 5849 // tag type. Note that this applies to functions, function templates, and 5850 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. 5851 if (Previous.isSingleTagDecl() && 5852 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 5853 (TemplateParamLists.size() == 0 || R->isFunctionType())) 5854 Previous.clear(); 5855 5856 // Check that there are no default arguments other than in the parameters 5857 // of a function declaration (C++ only). 5858 if (getLangOpts().CPlusPlus) 5859 CheckExtraCXXDefaultArguments(D); 5860 5861 NamedDecl *New; 5862 5863 bool AddToScope = true; 5864 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 5865 if (TemplateParamLists.size()) { 5866 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 5867 return nullptr; 5868 } 5869 5870 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 5871 } else if (R->isFunctionType()) { 5872 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 5873 TemplateParamLists, 5874 AddToScope); 5875 } else { 5876 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 5877 AddToScope); 5878 } 5879 5880 if (!New) 5881 return nullptr; 5882 5883 // If this has an identifier and is not a function template specialization, 5884 // add it to the scope stack. 5885 if (New->getDeclName() && AddToScope) 5886 PushOnScopeChains(New, S); 5887 5888 if (isInOpenMPDeclareTargetContext()) 5889 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 5890 5891 return New; 5892 } 5893 5894 /// Helper method to turn variable array types into constant array 5895 /// types in certain situations which would otherwise be errors (for 5896 /// GCC compatibility). 5897 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 5898 ASTContext &Context, 5899 bool &SizeIsNegative, 5900 llvm::APSInt &Oversized) { 5901 // This method tries to turn a variable array into a constant 5902 // array even when the size isn't an ICE. This is necessary 5903 // for compatibility with code that depends on gcc's buggy 5904 // constant expression folding, like struct {char x[(int)(char*)2];} 5905 SizeIsNegative = false; 5906 Oversized = 0; 5907 5908 if (T->isDependentType()) 5909 return QualType(); 5910 5911 QualifierCollector Qs; 5912 const Type *Ty = Qs.strip(T); 5913 5914 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 5915 QualType Pointee = PTy->getPointeeType(); 5916 QualType FixedType = 5917 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 5918 Oversized); 5919 if (FixedType.isNull()) return FixedType; 5920 FixedType = Context.getPointerType(FixedType); 5921 return Qs.apply(Context, FixedType); 5922 } 5923 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 5924 QualType Inner = PTy->getInnerType(); 5925 QualType FixedType = 5926 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 5927 Oversized); 5928 if (FixedType.isNull()) return FixedType; 5929 FixedType = Context.getParenType(FixedType); 5930 return Qs.apply(Context, FixedType); 5931 } 5932 5933 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 5934 if (!VLATy) 5935 return QualType(); 5936 // FIXME: We should probably handle this case 5937 if (VLATy->getElementType()->isVariablyModifiedType()) 5938 return QualType(); 5939 5940 Expr::EvalResult Result; 5941 if (!VLATy->getSizeExpr() || 5942 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context)) 5943 return QualType(); 5944 5945 llvm::APSInt Res = Result.Val.getInt(); 5946 5947 // Check whether the array size is negative. 5948 if (Res.isSigned() && Res.isNegative()) { 5949 SizeIsNegative = true; 5950 return QualType(); 5951 } 5952 5953 // Check whether the array is too large to be addressed. 5954 unsigned ActiveSizeBits 5955 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 5956 Res); 5957 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 5958 Oversized = Res; 5959 return QualType(); 5960 } 5961 5962 return Context.getConstantArrayType( 5963 VLATy->getElementType(), Res, VLATy->getSizeExpr(), ArrayType::Normal, 0); 5964 } 5965 5966 static void 5967 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 5968 SrcTL = SrcTL.getUnqualifiedLoc(); 5969 DstTL = DstTL.getUnqualifiedLoc(); 5970 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 5971 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 5972 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 5973 DstPTL.getPointeeLoc()); 5974 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 5975 return; 5976 } 5977 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 5978 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 5979 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 5980 DstPTL.getInnerLoc()); 5981 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 5982 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 5983 return; 5984 } 5985 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 5986 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 5987 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 5988 TypeLoc DstElemTL = DstATL.getElementLoc(); 5989 DstElemTL.initializeFullCopy(SrcElemTL); 5990 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 5991 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 5992 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 5993 } 5994 5995 /// Helper method to turn variable array types into constant array 5996 /// types in certain situations which would otherwise be errors (for 5997 /// GCC compatibility). 5998 static TypeSourceInfo* 5999 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 6000 ASTContext &Context, 6001 bool &SizeIsNegative, 6002 llvm::APSInt &Oversized) { 6003 QualType FixedTy 6004 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 6005 SizeIsNegative, Oversized); 6006 if (FixedTy.isNull()) 6007 return nullptr; 6008 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 6009 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 6010 FixedTInfo->getTypeLoc()); 6011 return FixedTInfo; 6012 } 6013 6014 /// Register the given locally-scoped extern "C" declaration so 6015 /// that it can be found later for redeclarations. We include any extern "C" 6016 /// declaration that is not visible in the translation unit here, not just 6017 /// function-scope declarations. 6018 void 6019 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 6020 if (!getLangOpts().CPlusPlus && 6021 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 6022 // Don't need to track declarations in the TU in C. 6023 return; 6024 6025 // Note that we have a locally-scoped external with this name. 6026 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 6027 } 6028 6029 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 6030 // FIXME: We can have multiple results via __attribute__((overloadable)). 6031 auto Result = Context.getExternCContextDecl()->lookup(Name); 6032 return Result.empty() ? nullptr : *Result.begin(); 6033 } 6034 6035 /// Diagnose function specifiers on a declaration of an identifier that 6036 /// does not identify a function. 6037 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 6038 // FIXME: We should probably indicate the identifier in question to avoid 6039 // confusion for constructs like "virtual int a(), b;" 6040 if (DS.isVirtualSpecified()) 6041 Diag(DS.getVirtualSpecLoc(), 6042 diag::err_virtual_non_function); 6043 6044 if (DS.hasExplicitSpecifier()) 6045 Diag(DS.getExplicitSpecLoc(), 6046 diag::err_explicit_non_function); 6047 6048 if (DS.isNoreturnSpecified()) 6049 Diag(DS.getNoreturnSpecLoc(), 6050 diag::err_noreturn_non_function); 6051 } 6052 6053 NamedDecl* 6054 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 6055 TypeSourceInfo *TInfo, LookupResult &Previous) { 6056 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 6057 if (D.getCXXScopeSpec().isSet()) { 6058 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 6059 << D.getCXXScopeSpec().getRange(); 6060 D.setInvalidType(); 6061 // Pretend we didn't see the scope specifier. 6062 DC = CurContext; 6063 Previous.clear(); 6064 } 6065 6066 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6067 6068 if (D.getDeclSpec().isInlineSpecified()) 6069 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6070 << getLangOpts().CPlusPlus17; 6071 if (D.getDeclSpec().hasConstexprSpecifier()) 6072 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 6073 << 1 << D.getDeclSpec().getConstexprSpecifier(); 6074 6075 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) { 6076 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName) 6077 Diag(D.getName().StartLocation, 6078 diag::err_deduction_guide_invalid_specifier) 6079 << "typedef"; 6080 else 6081 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 6082 << D.getName().getSourceRange(); 6083 return nullptr; 6084 } 6085 6086 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 6087 if (!NewTD) return nullptr; 6088 6089 // Handle attributes prior to checking for duplicates in MergeVarDecl 6090 ProcessDeclAttributes(S, NewTD, D); 6091 6092 CheckTypedefForVariablyModifiedType(S, NewTD); 6093 6094 bool Redeclaration = D.isRedeclaration(); 6095 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 6096 D.setRedeclaration(Redeclaration); 6097 return ND; 6098 } 6099 6100 void 6101 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 6102 // C99 6.7.7p2: If a typedef name specifies a variably modified type 6103 // then it shall have block scope. 6104 // Note that variably modified types must be fixed before merging the decl so 6105 // that redeclarations will match. 6106 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 6107 QualType T = TInfo->getType(); 6108 if (T->isVariablyModifiedType()) { 6109 setFunctionHasBranchProtectedScope(); 6110 6111 if (S->getFnParent() == nullptr) { 6112 bool SizeIsNegative; 6113 llvm::APSInt Oversized; 6114 TypeSourceInfo *FixedTInfo = 6115 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 6116 SizeIsNegative, 6117 Oversized); 6118 if (FixedTInfo) { 6119 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 6120 NewTD->setTypeSourceInfo(FixedTInfo); 6121 } else { 6122 if (SizeIsNegative) 6123 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 6124 else if (T->isVariableArrayType()) 6125 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 6126 else if (Oversized.getBoolValue()) 6127 Diag(NewTD->getLocation(), diag::err_array_too_large) 6128 << Oversized.toString(10); 6129 else 6130 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 6131 NewTD->setInvalidDecl(); 6132 } 6133 } 6134 } 6135 } 6136 6137 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 6138 /// declares a typedef-name, either using the 'typedef' type specifier or via 6139 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 6140 NamedDecl* 6141 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 6142 LookupResult &Previous, bool &Redeclaration) { 6143 6144 // Find the shadowed declaration before filtering for scope. 6145 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); 6146 6147 // Merge the decl with the existing one if appropriate. If the decl is 6148 // in an outer scope, it isn't the same thing. 6149 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 6150 /*AllowInlineNamespace*/false); 6151 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 6152 if (!Previous.empty()) { 6153 Redeclaration = true; 6154 MergeTypedefNameDecl(S, NewTD, Previous); 6155 } else { 6156 inferGslPointerAttribute(NewTD); 6157 } 6158 6159 if (ShadowedDecl && !Redeclaration) 6160 CheckShadow(NewTD, ShadowedDecl, Previous); 6161 6162 // If this is the C FILE type, notify the AST context. 6163 if (IdentifierInfo *II = NewTD->getIdentifier()) 6164 if (!NewTD->isInvalidDecl() && 6165 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 6166 if (II->isStr("FILE")) 6167 Context.setFILEDecl(NewTD); 6168 else if (II->isStr("jmp_buf")) 6169 Context.setjmp_bufDecl(NewTD); 6170 else if (II->isStr("sigjmp_buf")) 6171 Context.setsigjmp_bufDecl(NewTD); 6172 else if (II->isStr("ucontext_t")) 6173 Context.setucontext_tDecl(NewTD); 6174 } 6175 6176 return NewTD; 6177 } 6178 6179 /// Determines whether the given declaration is an out-of-scope 6180 /// previous declaration. 6181 /// 6182 /// This routine should be invoked when name lookup has found a 6183 /// previous declaration (PrevDecl) that is not in the scope where a 6184 /// new declaration by the same name is being introduced. If the new 6185 /// declaration occurs in a local scope, previous declarations with 6186 /// linkage may still be considered previous declarations (C99 6187 /// 6.2.2p4-5, C++ [basic.link]p6). 6188 /// 6189 /// \param PrevDecl the previous declaration found by name 6190 /// lookup 6191 /// 6192 /// \param DC the context in which the new declaration is being 6193 /// declared. 6194 /// 6195 /// \returns true if PrevDecl is an out-of-scope previous declaration 6196 /// for a new delcaration with the same name. 6197 static bool 6198 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 6199 ASTContext &Context) { 6200 if (!PrevDecl) 6201 return false; 6202 6203 if (!PrevDecl->hasLinkage()) 6204 return false; 6205 6206 if (Context.getLangOpts().CPlusPlus) { 6207 // C++ [basic.link]p6: 6208 // If there is a visible declaration of an entity with linkage 6209 // having the same name and type, ignoring entities declared 6210 // outside the innermost enclosing namespace scope, the block 6211 // scope declaration declares that same entity and receives the 6212 // linkage of the previous declaration. 6213 DeclContext *OuterContext = DC->getRedeclContext(); 6214 if (!OuterContext->isFunctionOrMethod()) 6215 // This rule only applies to block-scope declarations. 6216 return false; 6217 6218 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 6219 if (PrevOuterContext->isRecord()) 6220 // We found a member function: ignore it. 6221 return false; 6222 6223 // Find the innermost enclosing namespace for the new and 6224 // previous declarations. 6225 OuterContext = OuterContext->getEnclosingNamespaceContext(); 6226 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 6227 6228 // The previous declaration is in a different namespace, so it 6229 // isn't the same function. 6230 if (!OuterContext->Equals(PrevOuterContext)) 6231 return false; 6232 } 6233 6234 return true; 6235 } 6236 6237 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) { 6238 CXXScopeSpec &SS = D.getCXXScopeSpec(); 6239 if (!SS.isSet()) return; 6240 DD->setQualifierInfo(SS.getWithLocInContext(S.Context)); 6241 } 6242 6243 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 6244 QualType type = decl->getType(); 6245 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 6246 if (lifetime == Qualifiers::OCL_Autoreleasing) { 6247 // Various kinds of declaration aren't allowed to be __autoreleasing. 6248 unsigned kind = -1U; 6249 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6250 if (var->hasAttr<BlocksAttr>()) 6251 kind = 0; // __block 6252 else if (!var->hasLocalStorage()) 6253 kind = 1; // global 6254 } else if (isa<ObjCIvarDecl>(decl)) { 6255 kind = 3; // ivar 6256 } else if (isa<FieldDecl>(decl)) { 6257 kind = 2; // field 6258 } 6259 6260 if (kind != -1U) { 6261 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 6262 << kind; 6263 } 6264 } else if (lifetime == Qualifiers::OCL_None) { 6265 // Try to infer lifetime. 6266 if (!type->isObjCLifetimeType()) 6267 return false; 6268 6269 lifetime = type->getObjCARCImplicitLifetime(); 6270 type = Context.getLifetimeQualifiedType(type, lifetime); 6271 decl->setType(type); 6272 } 6273 6274 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6275 // Thread-local variables cannot have lifetime. 6276 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 6277 var->getTLSKind()) { 6278 Diag(var->getLocation(), diag::err_arc_thread_ownership) 6279 << var->getType(); 6280 return true; 6281 } 6282 } 6283 6284 return false; 6285 } 6286 6287 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) { 6288 if (Decl->getType().hasAddressSpace()) 6289 return; 6290 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) { 6291 QualType Type = Var->getType(); 6292 if (Type->isSamplerT() || Type->isVoidType()) 6293 return; 6294 LangAS ImplAS = LangAS::opencl_private; 6295 if ((getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) && 6296 Var->hasGlobalStorage()) 6297 ImplAS = LangAS::opencl_global; 6298 // If the original type from a decayed type is an array type and that array 6299 // type has no address space yet, deduce it now. 6300 if (auto DT = dyn_cast<DecayedType>(Type)) { 6301 auto OrigTy = DT->getOriginalType(); 6302 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) { 6303 // Add the address space to the original array type and then propagate 6304 // that to the element type through `getAsArrayType`. 6305 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS); 6306 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0); 6307 // Re-generate the decayed type. 6308 Type = Context.getDecayedType(OrigTy); 6309 } 6310 } 6311 Type = Context.getAddrSpaceQualType(Type, ImplAS); 6312 // Apply any qualifiers (including address space) from the array type to 6313 // the element type. This implements C99 6.7.3p8: "If the specification of 6314 // an array type includes any type qualifiers, the element type is so 6315 // qualified, not the array type." 6316 if (Type->isArrayType()) 6317 Type = QualType(Context.getAsArrayType(Type), 0); 6318 Decl->setType(Type); 6319 } 6320 } 6321 6322 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 6323 // Ensure that an auto decl is deduced otherwise the checks below might cache 6324 // the wrong linkage. 6325 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 6326 6327 // 'weak' only applies to declarations with external linkage. 6328 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 6329 if (!ND.isExternallyVisible()) { 6330 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 6331 ND.dropAttr<WeakAttr>(); 6332 } 6333 } 6334 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 6335 if (ND.isExternallyVisible()) { 6336 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 6337 ND.dropAttr<WeakRefAttr>(); 6338 ND.dropAttr<AliasAttr>(); 6339 } 6340 } 6341 6342 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 6343 if (VD->hasInit()) { 6344 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 6345 assert(VD->isThisDeclarationADefinition() && 6346 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 6347 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 6348 VD->dropAttr<AliasAttr>(); 6349 } 6350 } 6351 } 6352 6353 // 'selectany' only applies to externally visible variable declarations. 6354 // It does not apply to functions. 6355 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 6356 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 6357 S.Diag(Attr->getLocation(), 6358 diag::err_attribute_selectany_non_extern_data); 6359 ND.dropAttr<SelectAnyAttr>(); 6360 } 6361 } 6362 6363 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 6364 auto *VD = dyn_cast<VarDecl>(&ND); 6365 bool IsAnonymousNS = false; 6366 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6367 if (VD) { 6368 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext()); 6369 while (NS && !IsAnonymousNS) { 6370 IsAnonymousNS = NS->isAnonymousNamespace(); 6371 NS = dyn_cast<NamespaceDecl>(NS->getParent()); 6372 } 6373 } 6374 // dll attributes require external linkage. Static locals may have external 6375 // linkage but still cannot be explicitly imported or exported. 6376 // In Microsoft mode, a variable defined in anonymous namespace must have 6377 // external linkage in order to be exported. 6378 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft; 6379 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) || 6380 (!AnonNSInMicrosoftMode && 6381 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) { 6382 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 6383 << &ND << Attr; 6384 ND.setInvalidDecl(); 6385 } 6386 } 6387 6388 // Virtual functions cannot be marked as 'notail'. 6389 if (auto *Attr = ND.getAttr<NotTailCalledAttr>()) 6390 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND)) 6391 if (MD->isVirtual()) { 6392 S.Diag(ND.getLocation(), 6393 diag::err_invalid_attribute_on_virtual_function) 6394 << Attr; 6395 ND.dropAttr<NotTailCalledAttr>(); 6396 } 6397 6398 // Check the attributes on the function type, if any. 6399 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) { 6400 // Don't declare this variable in the second operand of the for-statement; 6401 // GCC miscompiles that by ending its lifetime before evaluating the 6402 // third operand. See gcc.gnu.org/PR86769. 6403 AttributedTypeLoc ATL; 6404 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc(); 6405 (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); 6406 TL = ATL.getModifiedLoc()) { 6407 // The [[lifetimebound]] attribute can be applied to the implicit object 6408 // parameter of a non-static member function (other than a ctor or dtor) 6409 // by applying it to the function type. 6410 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) { 6411 const auto *MD = dyn_cast<CXXMethodDecl>(FD); 6412 if (!MD || MD->isStatic()) { 6413 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param) 6414 << !MD << A->getRange(); 6415 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) { 6416 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor) 6417 << isa<CXXDestructorDecl>(MD) << A->getRange(); 6418 } 6419 } 6420 } 6421 } 6422 } 6423 6424 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 6425 NamedDecl *NewDecl, 6426 bool IsSpecialization, 6427 bool IsDefinition) { 6428 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl()) 6429 return; 6430 6431 bool IsTemplate = false; 6432 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 6433 OldDecl = OldTD->getTemplatedDecl(); 6434 IsTemplate = true; 6435 if (!IsSpecialization) 6436 IsDefinition = false; 6437 } 6438 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { 6439 NewDecl = NewTD->getTemplatedDecl(); 6440 IsTemplate = true; 6441 } 6442 6443 if (!OldDecl || !NewDecl) 6444 return; 6445 6446 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 6447 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 6448 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 6449 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 6450 6451 // dllimport and dllexport are inheritable attributes so we have to exclude 6452 // inherited attribute instances. 6453 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 6454 (NewExportAttr && !NewExportAttr->isInherited()); 6455 6456 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 6457 // the only exception being explicit specializations. 6458 // Implicitly generated declarations are also excluded for now because there 6459 // is no other way to switch these to use dllimport or dllexport. 6460 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 6461 6462 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 6463 // Allow with a warning for free functions and global variables. 6464 bool JustWarn = false; 6465 if (!OldDecl->isCXXClassMember()) { 6466 auto *VD = dyn_cast<VarDecl>(OldDecl); 6467 if (VD && !VD->getDescribedVarTemplate()) 6468 JustWarn = true; 6469 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 6470 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 6471 JustWarn = true; 6472 } 6473 6474 // We cannot change a declaration that's been used because IR has already 6475 // been emitted. Dllimported functions will still work though (modulo 6476 // address equality) as they can use the thunk. 6477 if (OldDecl->isUsed()) 6478 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 6479 JustWarn = false; 6480 6481 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 6482 : diag::err_attribute_dll_redeclaration; 6483 S.Diag(NewDecl->getLocation(), DiagID) 6484 << NewDecl 6485 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 6486 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6487 if (!JustWarn) { 6488 NewDecl->setInvalidDecl(); 6489 return; 6490 } 6491 } 6492 6493 // A redeclaration is not allowed to drop a dllimport attribute, the only 6494 // exceptions being inline function definitions (except for function 6495 // templates), local extern declarations, qualified friend declarations or 6496 // special MSVC extension: in the last case, the declaration is treated as if 6497 // it were marked dllexport. 6498 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 6499 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6500 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 6501 // Ignore static data because out-of-line definitions are diagnosed 6502 // separately. 6503 IsStaticDataMember = VD->isStaticDataMember(); 6504 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 6505 VarDecl::DeclarationOnly; 6506 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 6507 IsInline = FD->isInlined(); 6508 IsQualifiedFriend = FD->getQualifier() && 6509 FD->getFriendObjectKind() == Decl::FOK_Declared; 6510 } 6511 6512 if (OldImportAttr && !HasNewAttr && 6513 (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember && 6514 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 6515 if (IsMicrosoft && IsDefinition) { 6516 S.Diag(NewDecl->getLocation(), 6517 diag::warn_redeclaration_without_import_attribute) 6518 << NewDecl; 6519 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6520 NewDecl->dropAttr<DLLImportAttr>(); 6521 NewDecl->addAttr( 6522 DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange())); 6523 } else { 6524 S.Diag(NewDecl->getLocation(), 6525 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 6526 << NewDecl << OldImportAttr; 6527 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6528 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 6529 OldDecl->dropAttr<DLLImportAttr>(); 6530 NewDecl->dropAttr<DLLImportAttr>(); 6531 } 6532 } else if (IsInline && OldImportAttr && !IsMicrosoft) { 6533 // In MinGW, seeing a function declared inline drops the dllimport 6534 // attribute. 6535 OldDecl->dropAttr<DLLImportAttr>(); 6536 NewDecl->dropAttr<DLLImportAttr>(); 6537 S.Diag(NewDecl->getLocation(), 6538 diag::warn_dllimport_dropped_from_inline_function) 6539 << NewDecl << OldImportAttr; 6540 } 6541 6542 // A specialization of a class template member function is processed here 6543 // since it's a redeclaration. If the parent class is dllexport, the 6544 // specialization inherits that attribute. This doesn't happen automatically 6545 // since the parent class isn't instantiated until later. 6546 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) { 6547 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && 6548 !NewImportAttr && !NewExportAttr) { 6549 if (const DLLExportAttr *ParentExportAttr = 6550 MD->getParent()->getAttr<DLLExportAttr>()) { 6551 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context); 6552 NewAttr->setInherited(true); 6553 NewDecl->addAttr(NewAttr); 6554 } 6555 } 6556 } 6557 } 6558 6559 /// Given that we are within the definition of the given function, 6560 /// will that definition behave like C99's 'inline', where the 6561 /// definition is discarded except for optimization purposes? 6562 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 6563 // Try to avoid calling GetGVALinkageForFunction. 6564 6565 // All cases of this require the 'inline' keyword. 6566 if (!FD->isInlined()) return false; 6567 6568 // This is only possible in C++ with the gnu_inline attribute. 6569 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 6570 return false; 6571 6572 // Okay, go ahead and call the relatively-more-expensive function. 6573 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 6574 } 6575 6576 /// Determine whether a variable is extern "C" prior to attaching 6577 /// an initializer. We can't just call isExternC() here, because that 6578 /// will also compute and cache whether the declaration is externally 6579 /// visible, which might change when we attach the initializer. 6580 /// 6581 /// This can only be used if the declaration is known to not be a 6582 /// redeclaration of an internal linkage declaration. 6583 /// 6584 /// For instance: 6585 /// 6586 /// auto x = []{}; 6587 /// 6588 /// Attaching the initializer here makes this declaration not externally 6589 /// visible, because its type has internal linkage. 6590 /// 6591 /// FIXME: This is a hack. 6592 template<typename T> 6593 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 6594 if (S.getLangOpts().CPlusPlus) { 6595 // In C++, the overloadable attribute negates the effects of extern "C". 6596 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 6597 return false; 6598 6599 // So do CUDA's host/device attributes. 6600 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 6601 D->template hasAttr<CUDAHostAttr>())) 6602 return false; 6603 } 6604 return D->isExternC(); 6605 } 6606 6607 static bool shouldConsiderLinkage(const VarDecl *VD) { 6608 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 6609 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) || 6610 isa<OMPDeclareMapperDecl>(DC)) 6611 return VD->hasExternalStorage(); 6612 if (DC->isFileContext()) 6613 return true; 6614 if (DC->isRecord()) 6615 return false; 6616 if (isa<RequiresExprBodyDecl>(DC)) 6617 return false; 6618 llvm_unreachable("Unexpected context"); 6619 } 6620 6621 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 6622 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 6623 if (DC->isFileContext() || DC->isFunctionOrMethod() || 6624 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC)) 6625 return true; 6626 if (DC->isRecord()) 6627 return false; 6628 llvm_unreachable("Unexpected context"); 6629 } 6630 6631 static bool hasParsedAttr(Scope *S, const Declarator &PD, 6632 ParsedAttr::Kind Kind) { 6633 // Check decl attributes on the DeclSpec. 6634 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind)) 6635 return true; 6636 6637 // Walk the declarator structure, checking decl attributes that were in a type 6638 // position to the decl itself. 6639 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 6640 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind)) 6641 return true; 6642 } 6643 6644 // Finally, check attributes on the decl itself. 6645 return PD.getAttributes().hasAttribute(Kind); 6646 } 6647 6648 /// Adjust the \c DeclContext for a function or variable that might be a 6649 /// function-local external declaration. 6650 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 6651 if (!DC->isFunctionOrMethod()) 6652 return false; 6653 6654 // If this is a local extern function or variable declared within a function 6655 // template, don't add it into the enclosing namespace scope until it is 6656 // instantiated; it might have a dependent type right now. 6657 if (DC->isDependentContext()) 6658 return true; 6659 6660 // C++11 [basic.link]p7: 6661 // When a block scope declaration of an entity with linkage is not found to 6662 // refer to some other declaration, then that entity is a member of the 6663 // innermost enclosing namespace. 6664 // 6665 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 6666 // semantically-enclosing namespace, not a lexically-enclosing one. 6667 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 6668 DC = DC->getParent(); 6669 return true; 6670 } 6671 6672 /// Returns true if given declaration has external C language linkage. 6673 static bool isDeclExternC(const Decl *D) { 6674 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 6675 return FD->isExternC(); 6676 if (const auto *VD = dyn_cast<VarDecl>(D)) 6677 return VD->isExternC(); 6678 6679 llvm_unreachable("Unknown type of decl!"); 6680 } 6681 /// Returns true if there hasn't been any invalid type diagnosed. 6682 static bool diagnoseOpenCLTypes(Scope *S, Sema &Se, Declarator &D, 6683 DeclContext *DC, QualType R) { 6684 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 6685 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 6686 // argument. 6687 if (R->isImageType() || R->isPipeType()) { 6688 Se.Diag(D.getIdentifierLoc(), 6689 diag::err_opencl_type_can_only_be_used_as_function_parameter) 6690 << R; 6691 D.setInvalidType(); 6692 return false; 6693 } 6694 6695 // OpenCL v1.2 s6.9.r: 6696 // The event type cannot be used to declare a program scope variable. 6697 // OpenCL v2.0 s6.9.q: 6698 // The clk_event_t and reserve_id_t types cannot be declared in program 6699 // scope. 6700 if (NULL == S->getParent()) { 6701 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 6702 Se.Diag(D.getIdentifierLoc(), 6703 diag::err_invalid_type_for_program_scope_var) 6704 << R; 6705 D.setInvalidType(); 6706 return false; 6707 } 6708 } 6709 6710 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 6711 QualType NR = R; 6712 while (NR->isPointerType()) { 6713 if (NR->isFunctionPointerType()) { 6714 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer); 6715 D.setInvalidType(); 6716 return false; 6717 } 6718 NR = NR->getPointeeType(); 6719 } 6720 6721 if (!Se.getOpenCLOptions().isEnabled("cl_khr_fp16")) { 6722 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 6723 // half array type (unless the cl_khr_fp16 extension is enabled). 6724 if (Se.Context.getBaseElementType(R)->isHalfType()) { 6725 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 6726 D.setInvalidType(); 6727 return false; 6728 } 6729 } 6730 6731 // OpenCL v1.2 s6.9.r: 6732 // The event type cannot be used with the __local, __constant and __global 6733 // address space qualifiers. 6734 if (R->isEventT()) { 6735 if (R.getAddressSpace() != LangAS::opencl_private) { 6736 Se.Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual); 6737 D.setInvalidType(); 6738 return false; 6739 } 6740 } 6741 6742 // C++ for OpenCL does not allow the thread_local storage qualifier. 6743 // OpenCL C does not support thread_local either, and 6744 // also reject all other thread storage class specifiers. 6745 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec(); 6746 if (TSC != TSCS_unspecified) { 6747 bool IsCXX = Se.getLangOpts().OpenCLCPlusPlus; 6748 Se.Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6749 diag::err_opencl_unknown_type_specifier) 6750 << IsCXX << Se.getLangOpts().getOpenCLVersionTuple().getAsString() 6751 << DeclSpec::getSpecifierName(TSC) << 1; 6752 D.setInvalidType(); 6753 return false; 6754 } 6755 6756 if (R->isSamplerT()) { 6757 // OpenCL v1.2 s6.9.b p4: 6758 // The sampler type cannot be used with the __local and __global address 6759 // space qualifiers. 6760 if (R.getAddressSpace() == LangAS::opencl_local || 6761 R.getAddressSpace() == LangAS::opencl_global) { 6762 Se.Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 6763 D.setInvalidType(); 6764 } 6765 6766 // OpenCL v1.2 s6.12.14.1: 6767 // A global sampler must be declared with either the constant address 6768 // space qualifier or with the const qualifier. 6769 if (DC->isTranslationUnit() && 6770 !(R.getAddressSpace() == LangAS::opencl_constant || 6771 R.isConstQualified())) { 6772 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler); 6773 D.setInvalidType(); 6774 } 6775 if (D.isInvalidType()) 6776 return false; 6777 } 6778 return true; 6779 } 6780 6781 NamedDecl *Sema::ActOnVariableDeclarator( 6782 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 6783 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 6784 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 6785 QualType R = TInfo->getType(); 6786 DeclarationName Name = GetNameForDeclarator(D).getName(); 6787 6788 IdentifierInfo *II = Name.getAsIdentifierInfo(); 6789 6790 if (D.isDecompositionDeclarator()) { 6791 // Take the name of the first declarator as our name for diagnostic 6792 // purposes. 6793 auto &Decomp = D.getDecompositionDeclarator(); 6794 if (!Decomp.bindings().empty()) { 6795 II = Decomp.bindings()[0].Name; 6796 Name = II; 6797 } 6798 } else if (!II) { 6799 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; 6800 return nullptr; 6801 } 6802 6803 6804 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 6805 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 6806 6807 // dllimport globals without explicit storage class are treated as extern. We 6808 // have to change the storage class this early to get the right DeclContext. 6809 if (SC == SC_None && !DC->isRecord() && 6810 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) && 6811 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport)) 6812 SC = SC_Extern; 6813 6814 DeclContext *OriginalDC = DC; 6815 bool IsLocalExternDecl = SC == SC_Extern && 6816 adjustContextForLocalExternDecl(DC); 6817 6818 if (SCSpec == DeclSpec::SCS_mutable) { 6819 // mutable can only appear on non-static class members, so it's always 6820 // an error here 6821 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 6822 D.setInvalidType(); 6823 SC = SC_None; 6824 } 6825 6826 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 6827 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 6828 D.getDeclSpec().getStorageClassSpecLoc())) { 6829 // In C++11, the 'register' storage class specifier is deprecated. 6830 // Suppress the warning in system macros, it's used in macros in some 6831 // popular C system headers, such as in glibc's htonl() macro. 6832 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6833 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 6834 : diag::warn_deprecated_register) 6835 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6836 } 6837 6838 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6839 6840 if (!DC->isRecord() && S->getFnParent() == nullptr) { 6841 // C99 6.9p2: The storage-class specifiers auto and register shall not 6842 // appear in the declaration specifiers in an external declaration. 6843 // Global Register+Asm is a GNU extension we support. 6844 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 6845 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 6846 D.setInvalidType(); 6847 } 6848 } 6849 6850 bool IsMemberSpecialization = false; 6851 bool IsVariableTemplateSpecialization = false; 6852 bool IsPartialSpecialization = false; 6853 bool IsVariableTemplate = false; 6854 VarDecl *NewVD = nullptr; 6855 VarTemplateDecl *NewTemplate = nullptr; 6856 TemplateParameterList *TemplateParams = nullptr; 6857 if (!getLangOpts().CPlusPlus) { 6858 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), 6859 II, R, TInfo, SC); 6860 6861 if (R->getContainedDeducedType()) 6862 ParsingInitForAutoVars.insert(NewVD); 6863 6864 if (D.isInvalidType()) 6865 NewVD->setInvalidDecl(); 6866 6867 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() && 6868 NewVD->hasLocalStorage()) 6869 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(), 6870 NTCUC_AutoVar, NTCUK_Destruct); 6871 } else { 6872 bool Invalid = false; 6873 6874 if (DC->isRecord() && !CurContext->isRecord()) { 6875 // This is an out-of-line definition of a static data member. 6876 switch (SC) { 6877 case SC_None: 6878 break; 6879 case SC_Static: 6880 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6881 diag::err_static_out_of_line) 6882 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6883 break; 6884 case SC_Auto: 6885 case SC_Register: 6886 case SC_Extern: 6887 // [dcl.stc] p2: The auto or register specifiers shall be applied only 6888 // to names of variables declared in a block or to function parameters. 6889 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 6890 // of class members 6891 6892 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6893 diag::err_storage_class_for_static_member) 6894 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6895 break; 6896 case SC_PrivateExtern: 6897 llvm_unreachable("C storage class in c++!"); 6898 } 6899 } 6900 6901 if (SC == SC_Static && CurContext->isRecord()) { 6902 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 6903 // Walk up the enclosing DeclContexts to check for any that are 6904 // incompatible with static data members. 6905 const DeclContext *FunctionOrMethod = nullptr; 6906 const CXXRecordDecl *AnonStruct = nullptr; 6907 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) { 6908 if (Ctxt->isFunctionOrMethod()) { 6909 FunctionOrMethod = Ctxt; 6910 break; 6911 } 6912 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt); 6913 if (ParentDecl && !ParentDecl->getDeclName()) { 6914 AnonStruct = ParentDecl; 6915 break; 6916 } 6917 } 6918 if (FunctionOrMethod) { 6919 // C++ [class.static.data]p5: A local class shall not have static data 6920 // members. 6921 Diag(D.getIdentifierLoc(), 6922 diag::err_static_data_member_not_allowed_in_local_class) 6923 << Name << RD->getDeclName() << RD->getTagKind(); 6924 } else if (AnonStruct) { 6925 // C++ [class.static.data]p4: Unnamed classes and classes contained 6926 // directly or indirectly within unnamed classes shall not contain 6927 // static data members. 6928 Diag(D.getIdentifierLoc(), 6929 diag::err_static_data_member_not_allowed_in_anon_struct) 6930 << Name << AnonStruct->getTagKind(); 6931 Invalid = true; 6932 } else if (RD->isUnion()) { 6933 // C++98 [class.union]p1: If a union contains a static data member, 6934 // the program is ill-formed. C++11 drops this restriction. 6935 Diag(D.getIdentifierLoc(), 6936 getLangOpts().CPlusPlus11 6937 ? diag::warn_cxx98_compat_static_data_member_in_union 6938 : diag::ext_static_data_member_in_union) << Name; 6939 } 6940 } 6941 } 6942 6943 // Match up the template parameter lists with the scope specifier, then 6944 // determine whether we have a template or a template specialization. 6945 bool InvalidScope = false; 6946 TemplateParams = MatchTemplateParametersToScopeSpecifier( 6947 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 6948 D.getCXXScopeSpec(), 6949 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 6950 ? D.getName().TemplateId 6951 : nullptr, 6952 TemplateParamLists, 6953 /*never a friend*/ false, IsMemberSpecialization, InvalidScope); 6954 Invalid |= InvalidScope; 6955 6956 if (TemplateParams) { 6957 if (!TemplateParams->size() && 6958 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 6959 // There is an extraneous 'template<>' for this variable. Complain 6960 // about it, but allow the declaration of the variable. 6961 Diag(TemplateParams->getTemplateLoc(), 6962 diag::err_template_variable_noparams) 6963 << II 6964 << SourceRange(TemplateParams->getTemplateLoc(), 6965 TemplateParams->getRAngleLoc()); 6966 TemplateParams = nullptr; 6967 } else { 6968 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 6969 // This is an explicit specialization or a partial specialization. 6970 // FIXME: Check that we can declare a specialization here. 6971 IsVariableTemplateSpecialization = true; 6972 IsPartialSpecialization = TemplateParams->size() > 0; 6973 } else { // if (TemplateParams->size() > 0) 6974 // This is a template declaration. 6975 IsVariableTemplate = true; 6976 6977 // Check that we can declare a template here. 6978 if (CheckTemplateDeclScope(S, TemplateParams)) 6979 return nullptr; 6980 6981 // Only C++1y supports variable templates (N3651). 6982 Diag(D.getIdentifierLoc(), 6983 getLangOpts().CPlusPlus14 6984 ? diag::warn_cxx11_compat_variable_template 6985 : diag::ext_variable_template); 6986 } 6987 } 6988 } else { 6989 assert((Invalid || 6990 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && 6991 "should have a 'template<>' for this decl"); 6992 } 6993 6994 if (IsVariableTemplateSpecialization) { 6995 SourceLocation TemplateKWLoc = 6996 TemplateParamLists.size() > 0 6997 ? TemplateParamLists[0]->getTemplateLoc() 6998 : SourceLocation(); 6999 DeclResult Res = ActOnVarTemplateSpecialization( 7000 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 7001 IsPartialSpecialization); 7002 if (Res.isInvalid()) 7003 return nullptr; 7004 NewVD = cast<VarDecl>(Res.get()); 7005 AddToScope = false; 7006 } else if (D.isDecompositionDeclarator()) { 7007 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(), 7008 D.getIdentifierLoc(), R, TInfo, SC, 7009 Bindings); 7010 } else 7011 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), 7012 D.getIdentifierLoc(), II, R, TInfo, SC); 7013 7014 // If this is supposed to be a variable template, create it as such. 7015 if (IsVariableTemplate) { 7016 NewTemplate = 7017 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 7018 TemplateParams, NewVD); 7019 NewVD->setDescribedVarTemplate(NewTemplate); 7020 } 7021 7022 // If this decl has an auto type in need of deduction, make a note of the 7023 // Decl so we can diagnose uses of it in its own initializer. 7024 if (R->getContainedDeducedType()) 7025 ParsingInitForAutoVars.insert(NewVD); 7026 7027 if (D.isInvalidType() || Invalid) { 7028 NewVD->setInvalidDecl(); 7029 if (NewTemplate) 7030 NewTemplate->setInvalidDecl(); 7031 } 7032 7033 SetNestedNameSpecifier(*this, NewVD, D); 7034 7035 // If we have any template parameter lists that don't directly belong to 7036 // the variable (matching the scope specifier), store them. 7037 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 7038 if (TemplateParamLists.size() > VDTemplateParamLists) 7039 NewVD->setTemplateParameterListsInfo( 7040 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 7041 } 7042 7043 if (D.getDeclSpec().isInlineSpecified()) { 7044 if (!getLangOpts().CPlusPlus) { 7045 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 7046 << 0; 7047 } else if (CurContext->isFunctionOrMethod()) { 7048 // 'inline' is not allowed on block scope variable declaration. 7049 Diag(D.getDeclSpec().getInlineSpecLoc(), 7050 diag::err_inline_declaration_block_scope) << Name 7051 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 7052 } else { 7053 Diag(D.getDeclSpec().getInlineSpecLoc(), 7054 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable 7055 : diag::ext_inline_variable); 7056 NewVD->setInlineSpecified(); 7057 } 7058 } 7059 7060 // Set the lexical context. If the declarator has a C++ scope specifier, the 7061 // lexical context will be different from the semantic context. 7062 NewVD->setLexicalDeclContext(CurContext); 7063 if (NewTemplate) 7064 NewTemplate->setLexicalDeclContext(CurContext); 7065 7066 if (IsLocalExternDecl) { 7067 if (D.isDecompositionDeclarator()) 7068 for (auto *B : Bindings) 7069 B->setLocalExternDecl(); 7070 else 7071 NewVD->setLocalExternDecl(); 7072 } 7073 7074 bool EmitTLSUnsupportedError = false; 7075 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 7076 // C++11 [dcl.stc]p4: 7077 // When thread_local is applied to a variable of block scope the 7078 // storage-class-specifier static is implied if it does not appear 7079 // explicitly. 7080 // Core issue: 'static' is not implied if the variable is declared 7081 // 'extern'. 7082 if (NewVD->hasLocalStorage() && 7083 (SCSpec != DeclSpec::SCS_unspecified || 7084 TSCS != DeclSpec::TSCS_thread_local || 7085 !DC->isFunctionOrMethod())) 7086 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7087 diag::err_thread_non_global) 7088 << DeclSpec::getSpecifierName(TSCS); 7089 else if (!Context.getTargetInfo().isTLSSupported()) { 7090 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || 7091 getLangOpts().SYCLIsDevice) { 7092 // Postpone error emission until we've collected attributes required to 7093 // figure out whether it's a host or device variable and whether the 7094 // error should be ignored. 7095 EmitTLSUnsupportedError = true; 7096 // We still need to mark the variable as TLS so it shows up in AST with 7097 // proper storage class for other tools to use even if we're not going 7098 // to emit any code for it. 7099 NewVD->setTSCSpec(TSCS); 7100 } else 7101 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7102 diag::err_thread_unsupported); 7103 } else 7104 NewVD->setTSCSpec(TSCS); 7105 } 7106 7107 switch (D.getDeclSpec().getConstexprSpecifier()) { 7108 case CSK_unspecified: 7109 break; 7110 7111 case CSK_consteval: 7112 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7113 diag::err_constexpr_wrong_decl_kind) 7114 << D.getDeclSpec().getConstexprSpecifier(); 7115 LLVM_FALLTHROUGH; 7116 7117 case CSK_constexpr: 7118 NewVD->setConstexpr(true); 7119 MaybeAddCUDAConstantAttr(NewVD); 7120 // C++1z [dcl.spec.constexpr]p1: 7121 // A static data member declared with the constexpr specifier is 7122 // implicitly an inline variable. 7123 if (NewVD->isStaticDataMember() && 7124 (getLangOpts().CPlusPlus17 || 7125 Context.getTargetInfo().getCXXABI().isMicrosoft())) 7126 NewVD->setImplicitlyInline(); 7127 break; 7128 7129 case CSK_constinit: 7130 if (!NewVD->hasGlobalStorage()) 7131 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7132 diag::err_constinit_local_variable); 7133 else 7134 NewVD->addAttr(ConstInitAttr::Create( 7135 Context, D.getDeclSpec().getConstexprSpecLoc(), 7136 AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit)); 7137 break; 7138 } 7139 7140 // C99 6.7.4p3 7141 // An inline definition of a function with external linkage shall 7142 // not contain a definition of a modifiable object with static or 7143 // thread storage duration... 7144 // We only apply this when the function is required to be defined 7145 // elsewhere, i.e. when the function is not 'extern inline'. Note 7146 // that a local variable with thread storage duration still has to 7147 // be marked 'static'. Also note that it's possible to get these 7148 // semantics in C++ using __attribute__((gnu_inline)). 7149 if (SC == SC_Static && S->getFnParent() != nullptr && 7150 !NewVD->getType().isConstQualified()) { 7151 FunctionDecl *CurFD = getCurFunctionDecl(); 7152 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 7153 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7154 diag::warn_static_local_in_extern_inline); 7155 MaybeSuggestAddingStaticToDecl(CurFD); 7156 } 7157 } 7158 7159 if (D.getDeclSpec().isModulePrivateSpecified()) { 7160 if (IsVariableTemplateSpecialization) 7161 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7162 << (IsPartialSpecialization ? 1 : 0) 7163 << FixItHint::CreateRemoval( 7164 D.getDeclSpec().getModulePrivateSpecLoc()); 7165 else if (IsMemberSpecialization) 7166 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7167 << 2 7168 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 7169 else if (NewVD->hasLocalStorage()) 7170 Diag(NewVD->getLocation(), diag::err_module_private_local) 7171 << 0 << NewVD->getDeclName() 7172 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 7173 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 7174 else { 7175 NewVD->setModulePrivate(); 7176 if (NewTemplate) 7177 NewTemplate->setModulePrivate(); 7178 for (auto *B : Bindings) 7179 B->setModulePrivate(); 7180 } 7181 } 7182 7183 if (getLangOpts().OpenCL) { 7184 7185 deduceOpenCLAddressSpace(NewVD); 7186 7187 diagnoseOpenCLTypes(S, *this, D, DC, NewVD->getType()); 7188 } 7189 7190 // Handle attributes prior to checking for duplicates in MergeVarDecl 7191 ProcessDeclAttributes(S, NewVD, D); 7192 7193 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || 7194 getLangOpts().SYCLIsDevice) { 7195 if (EmitTLSUnsupportedError && 7196 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || 7197 (getLangOpts().OpenMPIsDevice && 7198 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD)))) 7199 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7200 diag::err_thread_unsupported); 7201 7202 if (EmitTLSUnsupportedError && 7203 (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice))) 7204 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported); 7205 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 7206 // storage [duration]." 7207 if (SC == SC_None && S->getFnParent() != nullptr && 7208 (NewVD->hasAttr<CUDASharedAttr>() || 7209 NewVD->hasAttr<CUDAConstantAttr>())) { 7210 NewVD->setStorageClass(SC_Static); 7211 } 7212 } 7213 7214 // Ensure that dllimport globals without explicit storage class are treated as 7215 // extern. The storage class is set above using parsed attributes. Now we can 7216 // check the VarDecl itself. 7217 assert(!NewVD->hasAttr<DLLImportAttr>() || 7218 NewVD->getAttr<DLLImportAttr>()->isInherited() || 7219 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 7220 7221 // In auto-retain/release, infer strong retension for variables of 7222 // retainable type. 7223 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 7224 NewVD->setInvalidDecl(); 7225 7226 // Handle GNU asm-label extension (encoded as an attribute). 7227 if (Expr *E = (Expr*)D.getAsmLabel()) { 7228 // The parser guarantees this is a string. 7229 StringLiteral *SE = cast<StringLiteral>(E); 7230 StringRef Label = SE->getString(); 7231 if (S->getFnParent() != nullptr) { 7232 switch (SC) { 7233 case SC_None: 7234 case SC_Auto: 7235 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 7236 break; 7237 case SC_Register: 7238 // Local Named register 7239 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 7240 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 7241 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7242 break; 7243 case SC_Static: 7244 case SC_Extern: 7245 case SC_PrivateExtern: 7246 break; 7247 } 7248 } else if (SC == SC_Register) { 7249 // Global Named register 7250 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 7251 const auto &TI = Context.getTargetInfo(); 7252 bool HasSizeMismatch; 7253 7254 if (!TI.isValidGCCRegisterName(Label)) 7255 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7256 else if (!TI.validateGlobalRegisterVariable(Label, 7257 Context.getTypeSize(R), 7258 HasSizeMismatch)) 7259 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 7260 else if (HasSizeMismatch) 7261 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 7262 } 7263 7264 if (!R->isIntegralType(Context) && !R->isPointerType()) { 7265 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type); 7266 NewVD->setInvalidDecl(true); 7267 } 7268 } 7269 7270 NewVD->addAttr(AsmLabelAttr::Create(Context, Label, 7271 /*IsLiteralLabel=*/true, 7272 SE->getStrTokenLoc(0))); 7273 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 7274 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 7275 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 7276 if (I != ExtnameUndeclaredIdentifiers.end()) { 7277 if (isDeclExternC(NewVD)) { 7278 NewVD->addAttr(I->second); 7279 ExtnameUndeclaredIdentifiers.erase(I); 7280 } else 7281 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 7282 << /*Variable*/1 << NewVD; 7283 } 7284 } 7285 7286 // Find the shadowed declaration before filtering for scope. 7287 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 7288 ? getShadowedDeclaration(NewVD, Previous) 7289 : nullptr; 7290 7291 // Don't consider existing declarations that are in a different 7292 // scope and are out-of-semantic-context declarations (if the new 7293 // declaration has linkage). 7294 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 7295 D.getCXXScopeSpec().isNotEmpty() || 7296 IsMemberSpecialization || 7297 IsVariableTemplateSpecialization); 7298 7299 // Check whether the previous declaration is in the same block scope. This 7300 // affects whether we merge types with it, per C++11 [dcl.array]p3. 7301 if (getLangOpts().CPlusPlus && 7302 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 7303 NewVD->setPreviousDeclInSameBlockScope( 7304 Previous.isSingleResult() && !Previous.isShadowed() && 7305 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 7306 7307 if (!getLangOpts().CPlusPlus) { 7308 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7309 } else { 7310 // If this is an explicit specialization of a static data member, check it. 7311 if (IsMemberSpecialization && !NewVD->isInvalidDecl() && 7312 CheckMemberSpecialization(NewVD, Previous)) 7313 NewVD->setInvalidDecl(); 7314 7315 // Merge the decl with the existing one if appropriate. 7316 if (!Previous.empty()) { 7317 if (Previous.isSingleResult() && 7318 isa<FieldDecl>(Previous.getFoundDecl()) && 7319 D.getCXXScopeSpec().isSet()) { 7320 // The user tried to define a non-static data member 7321 // out-of-line (C++ [dcl.meaning]p1). 7322 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 7323 << D.getCXXScopeSpec().getRange(); 7324 Previous.clear(); 7325 NewVD->setInvalidDecl(); 7326 } 7327 } else if (D.getCXXScopeSpec().isSet()) { 7328 // No previous declaration in the qualifying scope. 7329 Diag(D.getIdentifierLoc(), diag::err_no_member) 7330 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 7331 << D.getCXXScopeSpec().getRange(); 7332 NewVD->setInvalidDecl(); 7333 } 7334 7335 if (!IsVariableTemplateSpecialization) 7336 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7337 7338 if (NewTemplate) { 7339 VarTemplateDecl *PrevVarTemplate = 7340 NewVD->getPreviousDecl() 7341 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 7342 : nullptr; 7343 7344 // Check the template parameter list of this declaration, possibly 7345 // merging in the template parameter list from the previous variable 7346 // template declaration. 7347 if (CheckTemplateParameterList( 7348 TemplateParams, 7349 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 7350 : nullptr, 7351 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 7352 DC->isDependentContext()) 7353 ? TPC_ClassTemplateMember 7354 : TPC_VarTemplate)) 7355 NewVD->setInvalidDecl(); 7356 7357 // If we are providing an explicit specialization of a static variable 7358 // template, make a note of that. 7359 if (PrevVarTemplate && 7360 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 7361 PrevVarTemplate->setMemberSpecialization(); 7362 } 7363 } 7364 7365 // Diagnose shadowed variables iff this isn't a redeclaration. 7366 if (ShadowedDecl && !D.isRedeclaration()) 7367 CheckShadow(NewVD, ShadowedDecl, Previous); 7368 7369 ProcessPragmaWeak(S, NewVD); 7370 7371 // If this is the first declaration of an extern C variable, update 7372 // the map of such variables. 7373 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 7374 isIncompleteDeclExternC(*this, NewVD)) 7375 RegisterLocallyScopedExternCDecl(NewVD, S); 7376 7377 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 7378 MangleNumberingContext *MCtx; 7379 Decl *ManglingContextDecl; 7380 std::tie(MCtx, ManglingContextDecl) = 7381 getCurrentMangleNumberContext(NewVD->getDeclContext()); 7382 if (MCtx) { 7383 Context.setManglingNumber( 7384 NewVD, MCtx->getManglingNumber( 7385 NewVD, getMSManglingNumber(getLangOpts(), S))); 7386 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 7387 } 7388 } 7389 7390 // Special handling of variable named 'main'. 7391 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 7392 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 7393 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 7394 7395 // C++ [basic.start.main]p3 7396 // A program that declares a variable main at global scope is ill-formed. 7397 if (getLangOpts().CPlusPlus) 7398 Diag(D.getBeginLoc(), diag::err_main_global_variable); 7399 7400 // In C, and external-linkage variable named main results in undefined 7401 // behavior. 7402 else if (NewVD->hasExternalFormalLinkage()) 7403 Diag(D.getBeginLoc(), diag::warn_main_redefined); 7404 } 7405 7406 if (D.isRedeclaration() && !Previous.empty()) { 7407 NamedDecl *Prev = Previous.getRepresentativeDecl(); 7408 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization, 7409 D.isFunctionDefinition()); 7410 } 7411 7412 if (NewTemplate) { 7413 if (NewVD->isInvalidDecl()) 7414 NewTemplate->setInvalidDecl(); 7415 ActOnDocumentableDecl(NewTemplate); 7416 return NewTemplate; 7417 } 7418 7419 if (IsMemberSpecialization && !NewVD->isInvalidDecl()) 7420 CompleteMemberSpecialization(NewVD, Previous); 7421 7422 return NewVD; 7423 } 7424 7425 /// Enum describing the %select options in diag::warn_decl_shadow. 7426 enum ShadowedDeclKind { 7427 SDK_Local, 7428 SDK_Global, 7429 SDK_StaticMember, 7430 SDK_Field, 7431 SDK_Typedef, 7432 SDK_Using 7433 }; 7434 7435 /// Determine what kind of declaration we're shadowing. 7436 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 7437 const DeclContext *OldDC) { 7438 if (isa<TypeAliasDecl>(ShadowedDecl)) 7439 return SDK_Using; 7440 else if (isa<TypedefDecl>(ShadowedDecl)) 7441 return SDK_Typedef; 7442 else if (isa<RecordDecl>(OldDC)) 7443 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 7444 7445 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 7446 } 7447 7448 /// Return the location of the capture if the given lambda captures the given 7449 /// variable \p VD, or an invalid source location otherwise. 7450 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 7451 const VarDecl *VD) { 7452 for (const Capture &Capture : LSI->Captures) { 7453 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 7454 return Capture.getLocation(); 7455 } 7456 return SourceLocation(); 7457 } 7458 7459 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, 7460 const LookupResult &R) { 7461 // Only diagnose if we're shadowing an unambiguous field or variable. 7462 if (R.getResultKind() != LookupResult::Found) 7463 return false; 7464 7465 // Return false if warning is ignored. 7466 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); 7467 } 7468 7469 /// Return the declaration shadowed by the given variable \p D, or null 7470 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7471 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 7472 const LookupResult &R) { 7473 if (!shouldWarnIfShadowedDecl(Diags, R)) 7474 return nullptr; 7475 7476 // Don't diagnose declarations at file scope. 7477 if (D->hasGlobalStorage()) 7478 return nullptr; 7479 7480 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7481 return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl) 7482 ? ShadowedDecl 7483 : nullptr; 7484 } 7485 7486 /// Return the declaration shadowed by the given typedef \p D, or null 7487 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7488 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, 7489 const LookupResult &R) { 7490 // Don't warn if typedef declaration is part of a class 7491 if (D->getDeclContext()->isRecord()) 7492 return nullptr; 7493 7494 if (!shouldWarnIfShadowedDecl(Diags, R)) 7495 return nullptr; 7496 7497 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7498 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; 7499 } 7500 7501 /// Diagnose variable or built-in function shadowing. Implements 7502 /// -Wshadow. 7503 /// 7504 /// This method is called whenever a VarDecl is added to a "useful" 7505 /// scope. 7506 /// 7507 /// \param ShadowedDecl the declaration that is shadowed by the given variable 7508 /// \param R the lookup of the name 7509 /// 7510 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 7511 const LookupResult &R) { 7512 DeclContext *NewDC = D->getDeclContext(); 7513 7514 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 7515 // Fields are not shadowed by variables in C++ static methods. 7516 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 7517 if (MD->isStatic()) 7518 return; 7519 7520 // Fields shadowed by constructor parameters are a special case. Usually 7521 // the constructor initializes the field with the parameter. 7522 if (isa<CXXConstructorDecl>(NewDC)) 7523 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { 7524 // Remember that this was shadowed so we can either warn about its 7525 // modification or its existence depending on warning settings. 7526 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); 7527 return; 7528 } 7529 } 7530 7531 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 7532 if (shadowedVar->isExternC()) { 7533 // For shadowing external vars, make sure that we point to the global 7534 // declaration, not a locally scoped extern declaration. 7535 for (auto I : shadowedVar->redecls()) 7536 if (I->isFileVarDecl()) { 7537 ShadowedDecl = I; 7538 break; 7539 } 7540 } 7541 7542 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); 7543 7544 unsigned WarningDiag = diag::warn_decl_shadow; 7545 SourceLocation CaptureLoc; 7546 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && 7547 isa<CXXMethodDecl>(NewDC)) { 7548 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 7549 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 7550 if (RD->getLambdaCaptureDefault() == LCD_None) { 7551 // Try to avoid warnings for lambdas with an explicit capture list. 7552 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 7553 // Warn only when the lambda captures the shadowed decl explicitly. 7554 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 7555 if (CaptureLoc.isInvalid()) 7556 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 7557 } else { 7558 // Remember that this was shadowed so we can avoid the warning if the 7559 // shadowed decl isn't captured and the warning settings allow it. 7560 cast<LambdaScopeInfo>(getCurFunction()) 7561 ->ShadowingDecls.push_back( 7562 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); 7563 return; 7564 } 7565 } 7566 7567 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { 7568 // A variable can't shadow a local variable in an enclosing scope, if 7569 // they are separated by a non-capturing declaration context. 7570 for (DeclContext *ParentDC = NewDC; 7571 ParentDC && !ParentDC->Equals(OldDC); 7572 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { 7573 // Only block literals, captured statements, and lambda expressions 7574 // can capture; other scopes don't. 7575 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && 7576 !isLambdaCallOperator(ParentDC)) { 7577 return; 7578 } 7579 } 7580 } 7581 } 7582 } 7583 7584 // Only warn about certain kinds of shadowing for class members. 7585 if (NewDC && NewDC->isRecord()) { 7586 // In particular, don't warn about shadowing non-class members. 7587 if (!OldDC->isRecord()) 7588 return; 7589 7590 // TODO: should we warn about static data members shadowing 7591 // static data members from base classes? 7592 7593 // TODO: don't diagnose for inaccessible shadowed members. 7594 // This is hard to do perfectly because we might friend the 7595 // shadowing context, but that's just a false negative. 7596 } 7597 7598 7599 DeclarationName Name = R.getLookupName(); 7600 7601 // Emit warning and note. 7602 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 7603 return; 7604 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 7605 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 7606 if (!CaptureLoc.isInvalid()) 7607 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7608 << Name << /*explicitly*/ 1; 7609 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7610 } 7611 7612 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 7613 /// when these variables are captured by the lambda. 7614 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 7615 for (const auto &Shadow : LSI->ShadowingDecls) { 7616 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 7617 // Try to avoid the warning when the shadowed decl isn't captured. 7618 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 7619 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7620 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 7621 ? diag::warn_decl_shadow_uncaptured_local 7622 : diag::warn_decl_shadow) 7623 << Shadow.VD->getDeclName() 7624 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 7625 if (!CaptureLoc.isInvalid()) 7626 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7627 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 7628 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7629 } 7630 } 7631 7632 /// Check -Wshadow without the advantage of a previous lookup. 7633 void Sema::CheckShadow(Scope *S, VarDecl *D) { 7634 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 7635 return; 7636 7637 LookupResult R(*this, D->getDeclName(), D->getLocation(), 7638 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); 7639 LookupName(R, S); 7640 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 7641 CheckShadow(D, ShadowedDecl, R); 7642 } 7643 7644 /// Check if 'E', which is an expression that is about to be modified, refers 7645 /// to a constructor parameter that shadows a field. 7646 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 7647 // Quickly ignore expressions that can't be shadowing ctor parameters. 7648 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 7649 return; 7650 E = E->IgnoreParenImpCasts(); 7651 auto *DRE = dyn_cast<DeclRefExpr>(E); 7652 if (!DRE) 7653 return; 7654 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 7655 auto I = ShadowingDecls.find(D); 7656 if (I == ShadowingDecls.end()) 7657 return; 7658 const NamedDecl *ShadowedDecl = I->second; 7659 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7660 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 7661 Diag(D->getLocation(), diag::note_var_declared_here) << D; 7662 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7663 7664 // Avoid issuing multiple warnings about the same decl. 7665 ShadowingDecls.erase(I); 7666 } 7667 7668 /// Check for conflict between this global or extern "C" declaration and 7669 /// previous global or extern "C" declarations. This is only used in C++. 7670 template<typename T> 7671 static bool checkGlobalOrExternCConflict( 7672 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 7673 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 7674 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 7675 7676 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 7677 // The common case: this global doesn't conflict with any extern "C" 7678 // declaration. 7679 return false; 7680 } 7681 7682 if (Prev) { 7683 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 7684 // Both the old and new declarations have C language linkage. This is a 7685 // redeclaration. 7686 Previous.clear(); 7687 Previous.addDecl(Prev); 7688 return true; 7689 } 7690 7691 // This is a global, non-extern "C" declaration, and there is a previous 7692 // non-global extern "C" declaration. Diagnose if this is a variable 7693 // declaration. 7694 if (!isa<VarDecl>(ND)) 7695 return false; 7696 } else { 7697 // The declaration is extern "C". Check for any declaration in the 7698 // translation unit which might conflict. 7699 if (IsGlobal) { 7700 // We have already performed the lookup into the translation unit. 7701 IsGlobal = false; 7702 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7703 I != E; ++I) { 7704 if (isa<VarDecl>(*I)) { 7705 Prev = *I; 7706 break; 7707 } 7708 } 7709 } else { 7710 DeclContext::lookup_result R = 7711 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 7712 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 7713 I != E; ++I) { 7714 if (isa<VarDecl>(*I)) { 7715 Prev = *I; 7716 break; 7717 } 7718 // FIXME: If we have any other entity with this name in global scope, 7719 // the declaration is ill-formed, but that is a defect: it breaks the 7720 // 'stat' hack, for instance. Only variables can have mangled name 7721 // clashes with extern "C" declarations, so only they deserve a 7722 // diagnostic. 7723 } 7724 } 7725 7726 if (!Prev) 7727 return false; 7728 } 7729 7730 // Use the first declaration's location to ensure we point at something which 7731 // is lexically inside an extern "C" linkage-spec. 7732 assert(Prev && "should have found a previous declaration to diagnose"); 7733 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 7734 Prev = FD->getFirstDecl(); 7735 else 7736 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 7737 7738 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 7739 << IsGlobal << ND; 7740 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 7741 << IsGlobal; 7742 return false; 7743 } 7744 7745 /// Apply special rules for handling extern "C" declarations. Returns \c true 7746 /// if we have found that this is a redeclaration of some prior entity. 7747 /// 7748 /// Per C++ [dcl.link]p6: 7749 /// Two declarations [for a function or variable] with C language linkage 7750 /// with the same name that appear in different scopes refer to the same 7751 /// [entity]. An entity with C language linkage shall not be declared with 7752 /// the same name as an entity in global scope. 7753 template<typename T> 7754 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 7755 LookupResult &Previous) { 7756 if (!S.getLangOpts().CPlusPlus) { 7757 // In C, when declaring a global variable, look for a corresponding 'extern' 7758 // variable declared in function scope. We don't need this in C++, because 7759 // we find local extern decls in the surrounding file-scope DeclContext. 7760 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7761 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 7762 Previous.clear(); 7763 Previous.addDecl(Prev); 7764 return true; 7765 } 7766 } 7767 return false; 7768 } 7769 7770 // A declaration in the translation unit can conflict with an extern "C" 7771 // declaration. 7772 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 7773 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 7774 7775 // An extern "C" declaration can conflict with a declaration in the 7776 // translation unit or can be a redeclaration of an extern "C" declaration 7777 // in another scope. 7778 if (isIncompleteDeclExternC(S,ND)) 7779 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 7780 7781 // Neither global nor extern "C": nothing to do. 7782 return false; 7783 } 7784 7785 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 7786 // If the decl is already known invalid, don't check it. 7787 if (NewVD->isInvalidDecl()) 7788 return; 7789 7790 QualType T = NewVD->getType(); 7791 7792 // Defer checking an 'auto' type until its initializer is attached. 7793 if (T->isUndeducedType()) 7794 return; 7795 7796 if (NewVD->hasAttrs()) 7797 CheckAlignasUnderalignment(NewVD); 7798 7799 if (T->isObjCObjectType()) { 7800 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 7801 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 7802 T = Context.getObjCObjectPointerType(T); 7803 NewVD->setType(T); 7804 } 7805 7806 // Emit an error if an address space was applied to decl with local storage. 7807 // This includes arrays of objects with address space qualifiers, but not 7808 // automatic variables that point to other address spaces. 7809 // ISO/IEC TR 18037 S5.1.2 7810 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && 7811 T.getAddressSpace() != LangAS::Default) { 7812 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; 7813 NewVD->setInvalidDecl(); 7814 return; 7815 } 7816 7817 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 7818 // scope. 7819 if (getLangOpts().OpenCLVersion == 120 && 7820 !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") && 7821 NewVD->isStaticLocal()) { 7822 Diag(NewVD->getLocation(), diag::err_static_function_scope); 7823 NewVD->setInvalidDecl(); 7824 return; 7825 } 7826 7827 if (getLangOpts().OpenCL) { 7828 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 7829 if (NewVD->hasAttr<BlocksAttr>()) { 7830 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 7831 return; 7832 } 7833 7834 if (T->isBlockPointerType()) { 7835 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 7836 // can't use 'extern' storage class. 7837 if (!T.isConstQualified()) { 7838 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 7839 << 0 /*const*/; 7840 NewVD->setInvalidDecl(); 7841 return; 7842 } 7843 if (NewVD->hasExternalStorage()) { 7844 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 7845 NewVD->setInvalidDecl(); 7846 return; 7847 } 7848 } 7849 // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the 7850 // __constant address space. 7851 // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static 7852 // variables inside a function can also be declared in the global 7853 // address space. 7854 // C++ for OpenCL inherits rule from OpenCL C v2.0. 7855 // FIXME: Adding local AS in C++ for OpenCL might make sense. 7856 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 7857 NewVD->hasExternalStorage()) { 7858 if (!T->isSamplerT() && 7859 !(T.getAddressSpace() == LangAS::opencl_constant || 7860 (T.getAddressSpace() == LangAS::opencl_global && 7861 (getLangOpts().OpenCLVersion == 200 || 7862 getLangOpts().OpenCLCPlusPlus)))) { 7863 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 7864 if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus) 7865 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7866 << Scope << "global or constant"; 7867 else 7868 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7869 << Scope << "constant"; 7870 NewVD->setInvalidDecl(); 7871 return; 7872 } 7873 } else { 7874 if (T.getAddressSpace() == LangAS::opencl_global) { 7875 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7876 << 1 /*is any function*/ << "global"; 7877 NewVD->setInvalidDecl(); 7878 return; 7879 } 7880 if (T.getAddressSpace() == LangAS::opencl_constant || 7881 T.getAddressSpace() == LangAS::opencl_local) { 7882 FunctionDecl *FD = getCurFunctionDecl(); 7883 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables 7884 // in functions. 7885 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 7886 if (T.getAddressSpace() == LangAS::opencl_constant) 7887 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7888 << 0 /*non-kernel only*/ << "constant"; 7889 else 7890 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7891 << 0 /*non-kernel only*/ << "local"; 7892 NewVD->setInvalidDecl(); 7893 return; 7894 } 7895 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be 7896 // in the outermost scope of a kernel function. 7897 if (FD && FD->hasAttr<OpenCLKernelAttr>()) { 7898 if (!getCurScope()->isFunctionScope()) { 7899 if (T.getAddressSpace() == LangAS::opencl_constant) 7900 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7901 << "constant"; 7902 else 7903 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7904 << "local"; 7905 NewVD->setInvalidDecl(); 7906 return; 7907 } 7908 } 7909 } else if (T.getAddressSpace() != LangAS::opencl_private && 7910 // If we are parsing a template we didn't deduce an addr 7911 // space yet. 7912 T.getAddressSpace() != LangAS::Default) { 7913 // Do not allow other address spaces on automatic variable. 7914 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; 7915 NewVD->setInvalidDecl(); 7916 return; 7917 } 7918 } 7919 } 7920 7921 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 7922 && !NewVD->hasAttr<BlocksAttr>()) { 7923 if (getLangOpts().getGC() != LangOptions::NonGC) 7924 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 7925 else { 7926 assert(!getLangOpts().ObjCAutoRefCount); 7927 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 7928 } 7929 } 7930 7931 bool isVM = T->isVariablyModifiedType(); 7932 if (isVM || NewVD->hasAttr<CleanupAttr>() || 7933 NewVD->hasAttr<BlocksAttr>()) 7934 setFunctionHasBranchProtectedScope(); 7935 7936 if ((isVM && NewVD->hasLinkage()) || 7937 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 7938 bool SizeIsNegative; 7939 llvm::APSInt Oversized; 7940 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 7941 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized); 7942 QualType FixedT; 7943 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType()) 7944 FixedT = FixedTInfo->getType(); 7945 else if (FixedTInfo) { 7946 // Type and type-as-written are canonically different. We need to fix up 7947 // both types separately. 7948 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 7949 Oversized); 7950 } 7951 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) { 7952 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 7953 // FIXME: This won't give the correct result for 7954 // int a[10][n]; 7955 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 7956 7957 if (NewVD->isFileVarDecl()) 7958 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 7959 << SizeRange; 7960 else if (NewVD->isStaticLocal()) 7961 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 7962 << SizeRange; 7963 else 7964 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 7965 << SizeRange; 7966 NewVD->setInvalidDecl(); 7967 return; 7968 } 7969 7970 if (!FixedTInfo) { 7971 if (NewVD->isFileVarDecl()) 7972 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 7973 else 7974 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 7975 NewVD->setInvalidDecl(); 7976 return; 7977 } 7978 7979 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 7980 NewVD->setType(FixedT); 7981 NewVD->setTypeSourceInfo(FixedTInfo); 7982 } 7983 7984 if (T->isVoidType()) { 7985 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 7986 // of objects and functions. 7987 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 7988 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 7989 << T; 7990 NewVD->setInvalidDecl(); 7991 return; 7992 } 7993 } 7994 7995 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 7996 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 7997 NewVD->setInvalidDecl(); 7998 return; 7999 } 8000 8001 if (!NewVD->hasLocalStorage() && T->isSizelessType()) { 8002 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T; 8003 NewVD->setInvalidDecl(); 8004 return; 8005 } 8006 8007 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 8008 Diag(NewVD->getLocation(), diag::err_block_on_vm); 8009 NewVD->setInvalidDecl(); 8010 return; 8011 } 8012 8013 if (NewVD->isConstexpr() && !T->isDependentType() && 8014 RequireLiteralType(NewVD->getLocation(), T, 8015 diag::err_constexpr_var_non_literal)) { 8016 NewVD->setInvalidDecl(); 8017 return; 8018 } 8019 } 8020 8021 /// Perform semantic checking on a newly-created variable 8022 /// declaration. 8023 /// 8024 /// This routine performs all of the type-checking required for a 8025 /// variable declaration once it has been built. It is used both to 8026 /// check variables after they have been parsed and their declarators 8027 /// have been translated into a declaration, and to check variables 8028 /// that have been instantiated from a template. 8029 /// 8030 /// Sets NewVD->isInvalidDecl() if an error was encountered. 8031 /// 8032 /// Returns true if the variable declaration is a redeclaration. 8033 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 8034 CheckVariableDeclarationType(NewVD); 8035 8036 // If the decl is already known invalid, don't check it. 8037 if (NewVD->isInvalidDecl()) 8038 return false; 8039 8040 // If we did not find anything by this name, look for a non-visible 8041 // extern "C" declaration with the same name. 8042 if (Previous.empty() && 8043 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 8044 Previous.setShadowed(); 8045 8046 if (!Previous.empty()) { 8047 MergeVarDecl(NewVD, Previous); 8048 return true; 8049 } 8050 return false; 8051 } 8052 8053 namespace { 8054 struct FindOverriddenMethod { 8055 Sema *S; 8056 CXXMethodDecl *Method; 8057 8058 /// Member lookup function that determines whether a given C++ 8059 /// method overrides a method in a base class, to be used with 8060 /// CXXRecordDecl::lookupInBases(). 8061 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 8062 RecordDecl *BaseRecord = 8063 Specifier->getType()->castAs<RecordType>()->getDecl(); 8064 8065 DeclarationName Name = Method->getDeclName(); 8066 8067 // FIXME: Do we care about other names here too? 8068 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8069 // We really want to find the base class destructor here. 8070 QualType T = S->Context.getTypeDeclType(BaseRecord); 8071 CanQualType CT = S->Context.getCanonicalType(T); 8072 8073 Name = S->Context.DeclarationNames.getCXXDestructorName(CT); 8074 } 8075 8076 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 8077 Path.Decls = Path.Decls.slice(1)) { 8078 NamedDecl *D = Path.Decls.front(); 8079 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 8080 if (MD->isVirtual() && 8081 !S->IsOverload( 8082 Method, MD, /*UseMemberUsingDeclRules=*/false, 8083 /*ConsiderCudaAttrs=*/true, 8084 // C++2a [class.virtual]p2 does not consider requires clauses 8085 // when overriding. 8086 /*ConsiderRequiresClauses=*/false)) 8087 return true; 8088 } 8089 } 8090 8091 return false; 8092 } 8093 }; 8094 } // end anonymous namespace 8095 8096 /// AddOverriddenMethods - See if a method overrides any in the base classes, 8097 /// and if so, check that it's a valid override and remember it. 8098 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 8099 // Look for methods in base classes that this method might override. 8100 CXXBasePaths Paths; 8101 FindOverriddenMethod FOM; 8102 FOM.Method = MD; 8103 FOM.S = this; 8104 bool AddedAny = false; 8105 if (DC->lookupInBases(FOM, Paths)) { 8106 for (auto *I : Paths.found_decls()) { 8107 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { 8108 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 8109 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 8110 !CheckOverridingFunctionAttributes(MD, OldMD) && 8111 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 8112 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 8113 AddedAny = true; 8114 } 8115 } 8116 } 8117 } 8118 8119 return AddedAny; 8120 } 8121 8122 namespace { 8123 // Struct for holding all of the extra arguments needed by 8124 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 8125 struct ActOnFDArgs { 8126 Scope *S; 8127 Declarator &D; 8128 MultiTemplateParamsArg TemplateParamLists; 8129 bool AddToScope; 8130 }; 8131 } // end anonymous namespace 8132 8133 namespace { 8134 8135 // Callback to only accept typo corrections that have a non-zero edit distance. 8136 // Also only accept corrections that have the same parent decl. 8137 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback { 8138 public: 8139 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 8140 CXXRecordDecl *Parent) 8141 : Context(Context), OriginalFD(TypoFD), 8142 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 8143 8144 bool ValidateCandidate(const TypoCorrection &candidate) override { 8145 if (candidate.getEditDistance() == 0) 8146 return false; 8147 8148 SmallVector<unsigned, 1> MismatchedParams; 8149 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 8150 CDeclEnd = candidate.end(); 8151 CDecl != CDeclEnd; ++CDecl) { 8152 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8153 8154 if (FD && !FD->hasBody() && 8155 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 8156 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 8157 CXXRecordDecl *Parent = MD->getParent(); 8158 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 8159 return true; 8160 } else if (!ExpectedParent) { 8161 return true; 8162 } 8163 } 8164 } 8165 8166 return false; 8167 } 8168 8169 std::unique_ptr<CorrectionCandidateCallback> clone() override { 8170 return std::make_unique<DifferentNameValidatorCCC>(*this); 8171 } 8172 8173 private: 8174 ASTContext &Context; 8175 FunctionDecl *OriginalFD; 8176 CXXRecordDecl *ExpectedParent; 8177 }; 8178 8179 } // end anonymous namespace 8180 8181 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { 8182 TypoCorrectedFunctionDefinitions.insert(F); 8183 } 8184 8185 /// Generate diagnostics for an invalid function redeclaration. 8186 /// 8187 /// This routine handles generating the diagnostic messages for an invalid 8188 /// function redeclaration, including finding possible similar declarations 8189 /// or performing typo correction if there are no previous declarations with 8190 /// the same name. 8191 /// 8192 /// Returns a NamedDecl iff typo correction was performed and substituting in 8193 /// the new declaration name does not cause new errors. 8194 static NamedDecl *DiagnoseInvalidRedeclaration( 8195 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 8196 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 8197 DeclarationName Name = NewFD->getDeclName(); 8198 DeclContext *NewDC = NewFD->getDeclContext(); 8199 SmallVector<unsigned, 1> MismatchedParams; 8200 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 8201 TypoCorrection Correction; 8202 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 8203 unsigned DiagMsg = 8204 IsLocalFriend ? diag::err_no_matching_local_friend : 8205 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match : 8206 diag::err_member_decl_does_not_match; 8207 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 8208 IsLocalFriend ? Sema::LookupLocalFriendName 8209 : Sema::LookupOrdinaryName, 8210 Sema::ForVisibleRedeclaration); 8211 8212 NewFD->setInvalidDecl(); 8213 if (IsLocalFriend) 8214 SemaRef.LookupName(Prev, S); 8215 else 8216 SemaRef.LookupQualifiedName(Prev, NewDC); 8217 assert(!Prev.isAmbiguous() && 8218 "Cannot have an ambiguity in previous-declaration lookup"); 8219 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 8220 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD, 8221 MD ? MD->getParent() : nullptr); 8222 if (!Prev.empty()) { 8223 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 8224 Func != FuncEnd; ++Func) { 8225 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 8226 if (FD && 8227 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8228 // Add 1 to the index so that 0 can mean the mismatch didn't 8229 // involve a parameter 8230 unsigned ParamNum = 8231 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 8232 NearMatches.push_back(std::make_pair(FD, ParamNum)); 8233 } 8234 } 8235 // If the qualified name lookup yielded nothing, try typo correction 8236 } else if ((Correction = SemaRef.CorrectTypo( 8237 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 8238 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery, 8239 IsLocalFriend ? nullptr : NewDC))) { 8240 // Set up everything for the call to ActOnFunctionDeclarator 8241 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 8242 ExtraArgs.D.getIdentifierLoc()); 8243 Previous.clear(); 8244 Previous.setLookupName(Correction.getCorrection()); 8245 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 8246 CDeclEnd = Correction.end(); 8247 CDecl != CDeclEnd; ++CDecl) { 8248 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8249 if (FD && !FD->hasBody() && 8250 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8251 Previous.addDecl(FD); 8252 } 8253 } 8254 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 8255 8256 NamedDecl *Result; 8257 // Retry building the function declaration with the new previous 8258 // declarations, and with errors suppressed. 8259 { 8260 // Trap errors. 8261 Sema::SFINAETrap Trap(SemaRef); 8262 8263 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 8264 // pieces need to verify the typo-corrected C++ declaration and hopefully 8265 // eliminate the need for the parameter pack ExtraArgs. 8266 Result = SemaRef.ActOnFunctionDeclarator( 8267 ExtraArgs.S, ExtraArgs.D, 8268 Correction.getCorrectionDecl()->getDeclContext(), 8269 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 8270 ExtraArgs.AddToScope); 8271 8272 if (Trap.hasErrorOccurred()) 8273 Result = nullptr; 8274 } 8275 8276 if (Result) { 8277 // Determine which correction we picked. 8278 Decl *Canonical = Result->getCanonicalDecl(); 8279 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 8280 I != E; ++I) 8281 if ((*I)->getCanonicalDecl() == Canonical) 8282 Correction.setCorrectionDecl(*I); 8283 8284 // Let Sema know about the correction. 8285 SemaRef.MarkTypoCorrectedFunctionDefinition(Result); 8286 SemaRef.diagnoseTypo( 8287 Correction, 8288 SemaRef.PDiag(IsLocalFriend 8289 ? diag::err_no_matching_local_friend_suggest 8290 : diag::err_member_decl_does_not_match_suggest) 8291 << Name << NewDC << IsDefinition); 8292 return Result; 8293 } 8294 8295 // Pretend the typo correction never occurred 8296 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 8297 ExtraArgs.D.getIdentifierLoc()); 8298 ExtraArgs.D.setRedeclaration(wasRedeclaration); 8299 Previous.clear(); 8300 Previous.setLookupName(Name); 8301 } 8302 8303 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 8304 << Name << NewDC << IsDefinition << NewFD->getLocation(); 8305 8306 bool NewFDisConst = false; 8307 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 8308 NewFDisConst = NewMD->isConst(); 8309 8310 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 8311 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 8312 NearMatch != NearMatchEnd; ++NearMatch) { 8313 FunctionDecl *FD = NearMatch->first; 8314 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 8315 bool FDisConst = MD && MD->isConst(); 8316 bool IsMember = MD || !IsLocalFriend; 8317 8318 // FIXME: These notes are poorly worded for the local friend case. 8319 if (unsigned Idx = NearMatch->second) { 8320 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 8321 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 8322 if (Loc.isInvalid()) Loc = FD->getLocation(); 8323 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 8324 : diag::note_local_decl_close_param_match) 8325 << Idx << FDParam->getType() 8326 << NewFD->getParamDecl(Idx - 1)->getType(); 8327 } else if (FDisConst != NewFDisConst) { 8328 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 8329 << NewFDisConst << FD->getSourceRange().getEnd(); 8330 } else 8331 SemaRef.Diag(FD->getLocation(), 8332 IsMember ? diag::note_member_def_close_match 8333 : diag::note_local_decl_close_match); 8334 } 8335 return nullptr; 8336 } 8337 8338 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 8339 switch (D.getDeclSpec().getStorageClassSpec()) { 8340 default: llvm_unreachable("Unknown storage class!"); 8341 case DeclSpec::SCS_auto: 8342 case DeclSpec::SCS_register: 8343 case DeclSpec::SCS_mutable: 8344 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8345 diag::err_typecheck_sclass_func); 8346 D.getMutableDeclSpec().ClearStorageClassSpecs(); 8347 D.setInvalidType(); 8348 break; 8349 case DeclSpec::SCS_unspecified: break; 8350 case DeclSpec::SCS_extern: 8351 if (D.getDeclSpec().isExternInLinkageSpec()) 8352 return SC_None; 8353 return SC_Extern; 8354 case DeclSpec::SCS_static: { 8355 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 8356 // C99 6.7.1p5: 8357 // The declaration of an identifier for a function that has 8358 // block scope shall have no explicit storage-class specifier 8359 // other than extern 8360 // See also (C++ [dcl.stc]p4). 8361 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8362 diag::err_static_block_func); 8363 break; 8364 } else 8365 return SC_Static; 8366 } 8367 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 8368 } 8369 8370 // No explicit storage class has already been returned 8371 return SC_None; 8372 } 8373 8374 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 8375 DeclContext *DC, QualType &R, 8376 TypeSourceInfo *TInfo, 8377 StorageClass SC, 8378 bool &IsVirtualOkay) { 8379 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 8380 DeclarationName Name = NameInfo.getName(); 8381 8382 FunctionDecl *NewFD = nullptr; 8383 bool isInline = D.getDeclSpec().isInlineSpecified(); 8384 8385 if (!SemaRef.getLangOpts().CPlusPlus) { 8386 // Determine whether the function was written with a 8387 // prototype. This true when: 8388 // - there is a prototype in the declarator, or 8389 // - the type R of the function is some kind of typedef or other non- 8390 // attributed reference to a type name (which eventually refers to a 8391 // function type). 8392 bool HasPrototype = 8393 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 8394 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 8395 8396 NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, 8397 R, TInfo, SC, isInline, HasPrototype, 8398 CSK_unspecified, 8399 /*TrailingRequiresClause=*/nullptr); 8400 if (D.isInvalidType()) 8401 NewFD->setInvalidDecl(); 8402 8403 return NewFD; 8404 } 8405 8406 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier(); 8407 8408 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 8409 if (ConstexprKind == CSK_constinit) { 8410 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(), 8411 diag::err_constexpr_wrong_decl_kind) 8412 << ConstexprKind; 8413 ConstexprKind = CSK_unspecified; 8414 D.getMutableDeclSpec().ClearConstexprSpec(); 8415 } 8416 Expr *TrailingRequiresClause = D.getTrailingRequiresClause(); 8417 8418 // Check that the return type is not an abstract class type. 8419 // For record types, this is done by the AbstractClassUsageDiagnoser once 8420 // the class has been completely parsed. 8421 if (!DC->isRecord() && 8422 SemaRef.RequireNonAbstractType( 8423 D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(), 8424 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 8425 D.setInvalidType(); 8426 8427 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 8428 // This is a C++ constructor declaration. 8429 assert(DC->isRecord() && 8430 "Constructors can only be declared in a member context"); 8431 8432 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 8433 return CXXConstructorDecl::Create( 8434 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8435 TInfo, ExplicitSpecifier, isInline, 8436 /*isImplicitlyDeclared=*/false, ConstexprKind, InheritedConstructor(), 8437 TrailingRequiresClause); 8438 8439 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8440 // This is a C++ destructor declaration. 8441 if (DC->isRecord()) { 8442 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 8443 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 8444 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 8445 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo, 8446 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind, 8447 TrailingRequiresClause); 8448 8449 // If the destructor needs an implicit exception specification, set it 8450 // now. FIXME: It'd be nice to be able to create the right type to start 8451 // with, but the type needs to reference the destructor declaration. 8452 if (SemaRef.getLangOpts().CPlusPlus11) 8453 SemaRef.AdjustDestructorExceptionSpec(NewDD); 8454 8455 IsVirtualOkay = true; 8456 return NewDD; 8457 8458 } else { 8459 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 8460 D.setInvalidType(); 8461 8462 // Create a FunctionDecl to satisfy the function definition parsing 8463 // code path. 8464 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8465 D.getIdentifierLoc(), Name, R, TInfo, SC, 8466 isInline, 8467 /*hasPrototype=*/true, ConstexprKind, 8468 TrailingRequiresClause); 8469 } 8470 8471 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 8472 if (!DC->isRecord()) { 8473 SemaRef.Diag(D.getIdentifierLoc(), 8474 diag::err_conv_function_not_member); 8475 return nullptr; 8476 } 8477 8478 SemaRef.CheckConversionDeclarator(D, R, SC); 8479 if (D.isInvalidType()) 8480 return nullptr; 8481 8482 IsVirtualOkay = true; 8483 return CXXConversionDecl::Create( 8484 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8485 TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation(), 8486 TrailingRequiresClause); 8487 8488 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 8489 if (TrailingRequiresClause) 8490 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(), 8491 diag::err_trailing_requires_clause_on_deduction_guide) 8492 << TrailingRequiresClause->getSourceRange(); 8493 SemaRef.CheckDeductionGuideDeclarator(D, R, SC); 8494 8495 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8496 ExplicitSpecifier, NameInfo, R, TInfo, 8497 D.getEndLoc()); 8498 } else if (DC->isRecord()) { 8499 // If the name of the function is the same as the name of the record, 8500 // then this must be an invalid constructor that has a return type. 8501 // (The parser checks for a return type and makes the declarator a 8502 // constructor if it has no return type). 8503 if (Name.getAsIdentifierInfo() && 8504 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 8505 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 8506 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8507 << SourceRange(D.getIdentifierLoc()); 8508 return nullptr; 8509 } 8510 8511 // This is a C++ method declaration. 8512 CXXMethodDecl *Ret = CXXMethodDecl::Create( 8513 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8514 TInfo, SC, isInline, ConstexprKind, SourceLocation(), 8515 TrailingRequiresClause); 8516 IsVirtualOkay = !Ret->isStatic(); 8517 return Ret; 8518 } else { 8519 bool isFriend = 8520 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 8521 if (!isFriend && SemaRef.CurContext->isRecord()) 8522 return nullptr; 8523 8524 // Determine whether the function was written with a 8525 // prototype. This true when: 8526 // - we're in C++ (where every function has a prototype), 8527 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, 8528 R, TInfo, SC, isInline, true /*HasPrototype*/, 8529 ConstexprKind, TrailingRequiresClause); 8530 } 8531 } 8532 8533 enum OpenCLParamType { 8534 ValidKernelParam, 8535 PtrPtrKernelParam, 8536 PtrKernelParam, 8537 InvalidAddrSpacePtrKernelParam, 8538 InvalidKernelParam, 8539 RecordKernelParam 8540 }; 8541 8542 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) { 8543 // Size dependent types are just typedefs to normal integer types 8544 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to 8545 // integers other than by their names. 8546 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"}; 8547 8548 // Remove typedefs one by one until we reach a typedef 8549 // for a size dependent type. 8550 QualType DesugaredTy = Ty; 8551 do { 8552 ArrayRef<StringRef> Names(SizeTypeNames); 8553 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString()); 8554 if (Names.end() != Match) 8555 return true; 8556 8557 Ty = DesugaredTy; 8558 DesugaredTy = Ty.getSingleStepDesugaredType(C); 8559 } while (DesugaredTy != Ty); 8560 8561 return false; 8562 } 8563 8564 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 8565 if (PT->isPointerType()) { 8566 QualType PointeeType = PT->getPointeeType(); 8567 if (PointeeType->isPointerType()) 8568 return PtrPtrKernelParam; 8569 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 8570 PointeeType.getAddressSpace() == LangAS::opencl_private || 8571 PointeeType.getAddressSpace() == LangAS::Default) 8572 return InvalidAddrSpacePtrKernelParam; 8573 return PtrKernelParam; 8574 } 8575 8576 // OpenCL v1.2 s6.9.k: 8577 // Arguments to kernel functions in a program cannot be declared with the 8578 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8579 // uintptr_t or a struct and/or union that contain fields declared to be one 8580 // of these built-in scalar types. 8581 if (isOpenCLSizeDependentType(S.getASTContext(), PT)) 8582 return InvalidKernelParam; 8583 8584 if (PT->isImageType()) 8585 return PtrKernelParam; 8586 8587 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) 8588 return InvalidKernelParam; 8589 8590 // OpenCL extension spec v1.2 s9.5: 8591 // This extension adds support for half scalar and vector types as built-in 8592 // types that can be used for arithmetic operations, conversions etc. 8593 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType()) 8594 return InvalidKernelParam; 8595 8596 if (PT->isRecordType()) 8597 return RecordKernelParam; 8598 8599 // Look into an array argument to check if it has a forbidden type. 8600 if (PT->isArrayType()) { 8601 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType(); 8602 // Call ourself to check an underlying type of an array. Since the 8603 // getPointeeOrArrayElementType returns an innermost type which is not an 8604 // array, this recursive call only happens once. 8605 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0)); 8606 } 8607 8608 return ValidKernelParam; 8609 } 8610 8611 static void checkIsValidOpenCLKernelParameter( 8612 Sema &S, 8613 Declarator &D, 8614 ParmVarDecl *Param, 8615 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 8616 QualType PT = Param->getType(); 8617 8618 // Cache the valid types we encounter to avoid rechecking structs that are 8619 // used again 8620 if (ValidTypes.count(PT.getTypePtr())) 8621 return; 8622 8623 switch (getOpenCLKernelParameterType(S, PT)) { 8624 case PtrPtrKernelParam: 8625 // OpenCL v1.2 s6.9.a: 8626 // A kernel function argument cannot be declared as a 8627 // pointer to a pointer type. 8628 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 8629 D.setInvalidType(); 8630 return; 8631 8632 case InvalidAddrSpacePtrKernelParam: 8633 // OpenCL v1.0 s6.5: 8634 // __kernel function arguments declared to be a pointer of a type can point 8635 // to one of the following address spaces only : __global, __local or 8636 // __constant. 8637 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 8638 D.setInvalidType(); 8639 return; 8640 8641 // OpenCL v1.2 s6.9.k: 8642 // Arguments to kernel functions in a program cannot be declared with the 8643 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8644 // uintptr_t or a struct and/or union that contain fields declared to be 8645 // one of these built-in scalar types. 8646 8647 case InvalidKernelParam: 8648 // OpenCL v1.2 s6.8 n: 8649 // A kernel function argument cannot be declared 8650 // of event_t type. 8651 // Do not diagnose half type since it is diagnosed as invalid argument 8652 // type for any function elsewhere. 8653 if (!PT->isHalfType()) { 8654 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8655 8656 // Explain what typedefs are involved. 8657 const TypedefType *Typedef = nullptr; 8658 while ((Typedef = PT->getAs<TypedefType>())) { 8659 SourceLocation Loc = Typedef->getDecl()->getLocation(); 8660 // SourceLocation may be invalid for a built-in type. 8661 if (Loc.isValid()) 8662 S.Diag(Loc, diag::note_entity_declared_at) << PT; 8663 PT = Typedef->desugar(); 8664 } 8665 } 8666 8667 D.setInvalidType(); 8668 return; 8669 8670 case PtrKernelParam: 8671 case ValidKernelParam: 8672 ValidTypes.insert(PT.getTypePtr()); 8673 return; 8674 8675 case RecordKernelParam: 8676 break; 8677 } 8678 8679 // Track nested structs we will inspect 8680 SmallVector<const Decl *, 4> VisitStack; 8681 8682 // Track where we are in the nested structs. Items will migrate from 8683 // VisitStack to HistoryStack as we do the DFS for bad field. 8684 SmallVector<const FieldDecl *, 4> HistoryStack; 8685 HistoryStack.push_back(nullptr); 8686 8687 // At this point we already handled everything except of a RecordType or 8688 // an ArrayType of a RecordType. 8689 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type."); 8690 const RecordType *RecTy = 8691 PT->getPointeeOrArrayElementType()->getAs<RecordType>(); 8692 const RecordDecl *OrigRecDecl = RecTy->getDecl(); 8693 8694 VisitStack.push_back(RecTy->getDecl()); 8695 assert(VisitStack.back() && "First decl null?"); 8696 8697 do { 8698 const Decl *Next = VisitStack.pop_back_val(); 8699 if (!Next) { 8700 assert(!HistoryStack.empty()); 8701 // Found a marker, we have gone up a level 8702 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 8703 ValidTypes.insert(Hist->getType().getTypePtr()); 8704 8705 continue; 8706 } 8707 8708 // Adds everything except the original parameter declaration (which is not a 8709 // field itself) to the history stack. 8710 const RecordDecl *RD; 8711 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 8712 HistoryStack.push_back(Field); 8713 8714 QualType FieldTy = Field->getType(); 8715 // Other field types (known to be valid or invalid) are handled while we 8716 // walk around RecordDecl::fields(). 8717 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) && 8718 "Unexpected type."); 8719 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType(); 8720 8721 RD = FieldRecTy->castAs<RecordType>()->getDecl(); 8722 } else { 8723 RD = cast<RecordDecl>(Next); 8724 } 8725 8726 // Add a null marker so we know when we've gone back up a level 8727 VisitStack.push_back(nullptr); 8728 8729 for (const auto *FD : RD->fields()) { 8730 QualType QT = FD->getType(); 8731 8732 if (ValidTypes.count(QT.getTypePtr())) 8733 continue; 8734 8735 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 8736 if (ParamType == ValidKernelParam) 8737 continue; 8738 8739 if (ParamType == RecordKernelParam) { 8740 VisitStack.push_back(FD); 8741 continue; 8742 } 8743 8744 // OpenCL v1.2 s6.9.p: 8745 // Arguments to kernel functions that are declared to be a struct or union 8746 // do not allow OpenCL objects to be passed as elements of the struct or 8747 // union. 8748 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 8749 ParamType == InvalidAddrSpacePtrKernelParam) { 8750 S.Diag(Param->getLocation(), 8751 diag::err_record_with_pointers_kernel_param) 8752 << PT->isUnionType() 8753 << PT; 8754 } else { 8755 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8756 } 8757 8758 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type) 8759 << OrigRecDecl->getDeclName(); 8760 8761 // We have an error, now let's go back up through history and show where 8762 // the offending field came from 8763 for (ArrayRef<const FieldDecl *>::const_iterator 8764 I = HistoryStack.begin() + 1, 8765 E = HistoryStack.end(); 8766 I != E; ++I) { 8767 const FieldDecl *OuterField = *I; 8768 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 8769 << OuterField->getType(); 8770 } 8771 8772 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 8773 << QT->isPointerType() 8774 << QT; 8775 D.setInvalidType(); 8776 return; 8777 } 8778 } while (!VisitStack.empty()); 8779 } 8780 8781 /// Find the DeclContext in which a tag is implicitly declared if we see an 8782 /// elaborated type specifier in the specified context, and lookup finds 8783 /// nothing. 8784 static DeclContext *getTagInjectionContext(DeclContext *DC) { 8785 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 8786 DC = DC->getParent(); 8787 return DC; 8788 } 8789 8790 /// Find the Scope in which a tag is implicitly declared if we see an 8791 /// elaborated type specifier in the specified context, and lookup finds 8792 /// nothing. 8793 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 8794 while (S->isClassScope() || 8795 (LangOpts.CPlusPlus && 8796 S->isFunctionPrototypeScope()) || 8797 ((S->getFlags() & Scope::DeclScope) == 0) || 8798 (S->getEntity() && S->getEntity()->isTransparentContext())) 8799 S = S->getParent(); 8800 return S; 8801 } 8802 8803 NamedDecl* 8804 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 8805 TypeSourceInfo *TInfo, LookupResult &Previous, 8806 MultiTemplateParamsArg TemplateParamListsRef, 8807 bool &AddToScope) { 8808 QualType R = TInfo->getType(); 8809 8810 assert(R->isFunctionType()); 8811 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr()) 8812 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call); 8813 8814 SmallVector<TemplateParameterList *, 4> TemplateParamLists; 8815 for (TemplateParameterList *TPL : TemplateParamListsRef) 8816 TemplateParamLists.push_back(TPL); 8817 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) { 8818 if (!TemplateParamLists.empty() && 8819 Invented->getDepth() == TemplateParamLists.back()->getDepth()) 8820 TemplateParamLists.back() = Invented; 8821 else 8822 TemplateParamLists.push_back(Invented); 8823 } 8824 8825 // TODO: consider using NameInfo for diagnostic. 8826 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 8827 DeclarationName Name = NameInfo.getName(); 8828 StorageClass SC = getFunctionStorageClass(*this, D); 8829 8830 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 8831 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 8832 diag::err_invalid_thread) 8833 << DeclSpec::getSpecifierName(TSCS); 8834 8835 if (D.isFirstDeclarationOfMember()) 8836 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 8837 D.getIdentifierLoc()); 8838 8839 bool isFriend = false; 8840 FunctionTemplateDecl *FunctionTemplate = nullptr; 8841 bool isMemberSpecialization = false; 8842 bool isFunctionTemplateSpecialization = false; 8843 8844 bool isDependentClassScopeExplicitSpecialization = false; 8845 bool HasExplicitTemplateArgs = false; 8846 TemplateArgumentListInfo TemplateArgs; 8847 8848 bool isVirtualOkay = false; 8849 8850 DeclContext *OriginalDC = DC; 8851 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 8852 8853 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 8854 isVirtualOkay); 8855 if (!NewFD) return nullptr; 8856 8857 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 8858 NewFD->setTopLevelDeclInObjCContainer(); 8859 8860 // Set the lexical context. If this is a function-scope declaration, or has a 8861 // C++ scope specifier, or is the object of a friend declaration, the lexical 8862 // context will be different from the semantic context. 8863 NewFD->setLexicalDeclContext(CurContext); 8864 8865 if (IsLocalExternDecl) 8866 NewFD->setLocalExternDecl(); 8867 8868 if (getLangOpts().CPlusPlus) { 8869 bool isInline = D.getDeclSpec().isInlineSpecified(); 8870 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 8871 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier(); 8872 isFriend = D.getDeclSpec().isFriendSpecified(); 8873 if (isFriend && !isInline && D.isFunctionDefinition()) { 8874 // C++ [class.friend]p5 8875 // A function can be defined in a friend declaration of a 8876 // class . . . . Such a function is implicitly inline. 8877 NewFD->setImplicitlyInline(); 8878 } 8879 8880 // If this is a method defined in an __interface, and is not a constructor 8881 // or an overloaded operator, then set the pure flag (isVirtual will already 8882 // return true). 8883 if (const CXXRecordDecl *Parent = 8884 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 8885 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 8886 NewFD->setPure(true); 8887 8888 // C++ [class.union]p2 8889 // A union can have member functions, but not virtual functions. 8890 if (isVirtual && Parent->isUnion()) 8891 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 8892 } 8893 8894 SetNestedNameSpecifier(*this, NewFD, D); 8895 isMemberSpecialization = false; 8896 isFunctionTemplateSpecialization = false; 8897 if (D.isInvalidType()) 8898 NewFD->setInvalidDecl(); 8899 8900 // Match up the template parameter lists with the scope specifier, then 8901 // determine whether we have a template or a template specialization. 8902 bool Invalid = false; 8903 TemplateParameterList *TemplateParams = 8904 MatchTemplateParametersToScopeSpecifier( 8905 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 8906 D.getCXXScopeSpec(), 8907 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 8908 ? D.getName().TemplateId 8909 : nullptr, 8910 TemplateParamLists, isFriend, isMemberSpecialization, 8911 Invalid); 8912 if (TemplateParams) { 8913 if (TemplateParams->size() > 0) { 8914 // This is a function template 8915 8916 // Check that we can declare a template here. 8917 if (CheckTemplateDeclScope(S, TemplateParams)) 8918 NewFD->setInvalidDecl(); 8919 8920 // A destructor cannot be a template. 8921 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8922 Diag(NewFD->getLocation(), diag::err_destructor_template); 8923 NewFD->setInvalidDecl(); 8924 } 8925 8926 // If we're adding a template to a dependent context, we may need to 8927 // rebuilding some of the types used within the template parameter list, 8928 // now that we know what the current instantiation is. 8929 if (DC->isDependentContext()) { 8930 ContextRAII SavedContext(*this, DC); 8931 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 8932 Invalid = true; 8933 } 8934 8935 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 8936 NewFD->getLocation(), 8937 Name, TemplateParams, 8938 NewFD); 8939 FunctionTemplate->setLexicalDeclContext(CurContext); 8940 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 8941 8942 // For source fidelity, store the other template param lists. 8943 if (TemplateParamLists.size() > 1) { 8944 NewFD->setTemplateParameterListsInfo(Context, 8945 ArrayRef<TemplateParameterList *>(TemplateParamLists) 8946 .drop_back(1)); 8947 } 8948 } else { 8949 // This is a function template specialization. 8950 isFunctionTemplateSpecialization = true; 8951 // For source fidelity, store all the template param lists. 8952 if (TemplateParamLists.size() > 0) 8953 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8954 8955 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 8956 if (isFriend) { 8957 // We want to remove the "template<>", found here. 8958 SourceRange RemoveRange = TemplateParams->getSourceRange(); 8959 8960 // If we remove the template<> and the name is not a 8961 // template-id, we're actually silently creating a problem: 8962 // the friend declaration will refer to an untemplated decl, 8963 // and clearly the user wants a template specialization. So 8964 // we need to insert '<>' after the name. 8965 SourceLocation InsertLoc; 8966 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 8967 InsertLoc = D.getName().getSourceRange().getEnd(); 8968 InsertLoc = getLocForEndOfToken(InsertLoc); 8969 } 8970 8971 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 8972 << Name << RemoveRange 8973 << FixItHint::CreateRemoval(RemoveRange) 8974 << FixItHint::CreateInsertion(InsertLoc, "<>"); 8975 } 8976 } 8977 } else { 8978 // All template param lists were matched against the scope specifier: 8979 // this is NOT (an explicit specialization of) a template. 8980 if (TemplateParamLists.size() > 0) 8981 // For source fidelity, store all the template param lists. 8982 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8983 } 8984 8985 if (Invalid) { 8986 NewFD->setInvalidDecl(); 8987 if (FunctionTemplate) 8988 FunctionTemplate->setInvalidDecl(); 8989 } 8990 8991 // C++ [dcl.fct.spec]p5: 8992 // The virtual specifier shall only be used in declarations of 8993 // nonstatic class member functions that appear within a 8994 // member-specification of a class declaration; see 10.3. 8995 // 8996 if (isVirtual && !NewFD->isInvalidDecl()) { 8997 if (!isVirtualOkay) { 8998 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8999 diag::err_virtual_non_function); 9000 } else if (!CurContext->isRecord()) { 9001 // 'virtual' was specified outside of the class. 9002 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9003 diag::err_virtual_out_of_class) 9004 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 9005 } else if (NewFD->getDescribedFunctionTemplate()) { 9006 // C++ [temp.mem]p3: 9007 // A member function template shall not be virtual. 9008 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9009 diag::err_virtual_member_function_template) 9010 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 9011 } else { 9012 // Okay: Add virtual to the method. 9013 NewFD->setVirtualAsWritten(true); 9014 } 9015 9016 if (getLangOpts().CPlusPlus14 && 9017 NewFD->getReturnType()->isUndeducedType()) 9018 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 9019 } 9020 9021 if (getLangOpts().CPlusPlus14 && 9022 (NewFD->isDependentContext() || 9023 (isFriend && CurContext->isDependentContext())) && 9024 NewFD->getReturnType()->isUndeducedType()) { 9025 // If the function template is referenced directly (for instance, as a 9026 // member of the current instantiation), pretend it has a dependent type. 9027 // This is not really justified by the standard, but is the only sane 9028 // thing to do. 9029 // FIXME: For a friend function, we have not marked the function as being 9030 // a friend yet, so 'isDependentContext' on the FD doesn't work. 9031 const FunctionProtoType *FPT = 9032 NewFD->getType()->castAs<FunctionProtoType>(); 9033 QualType Result = 9034 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 9035 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 9036 FPT->getExtProtoInfo())); 9037 } 9038 9039 // C++ [dcl.fct.spec]p3: 9040 // The inline specifier shall not appear on a block scope function 9041 // declaration. 9042 if (isInline && !NewFD->isInvalidDecl()) { 9043 if (CurContext->isFunctionOrMethod()) { 9044 // 'inline' is not allowed on block scope function declaration. 9045 Diag(D.getDeclSpec().getInlineSpecLoc(), 9046 diag::err_inline_declaration_block_scope) << Name 9047 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 9048 } 9049 } 9050 9051 // C++ [dcl.fct.spec]p6: 9052 // The explicit specifier shall be used only in the declaration of a 9053 // constructor or conversion function within its class definition; 9054 // see 12.3.1 and 12.3.2. 9055 if (hasExplicit && !NewFD->isInvalidDecl() && 9056 !isa<CXXDeductionGuideDecl>(NewFD)) { 9057 if (!CurContext->isRecord()) { 9058 // 'explicit' was specified outside of the class. 9059 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9060 diag::err_explicit_out_of_class) 9061 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9062 } else if (!isa<CXXConstructorDecl>(NewFD) && 9063 !isa<CXXConversionDecl>(NewFD)) { 9064 // 'explicit' was specified on a function that wasn't a constructor 9065 // or conversion function. 9066 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9067 diag::err_explicit_non_ctor_or_conv_function) 9068 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9069 } 9070 } 9071 9072 if (ConstexprSpecKind ConstexprKind = 9073 D.getDeclSpec().getConstexprSpecifier()) { 9074 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 9075 // are implicitly inline. 9076 NewFD->setImplicitlyInline(); 9077 9078 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 9079 // be either constructors or to return a literal type. Therefore, 9080 // destructors cannot be declared constexpr. 9081 if (isa<CXXDestructorDecl>(NewFD) && 9082 (!getLangOpts().CPlusPlus20 || ConstexprKind == CSK_consteval)) { 9083 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor) 9084 << ConstexprKind; 9085 NewFD->setConstexprKind(getLangOpts().CPlusPlus20 ? CSK_unspecified : CSK_constexpr); 9086 } 9087 // C++20 [dcl.constexpr]p2: An allocation function, or a 9088 // deallocation function shall not be declared with the consteval 9089 // specifier. 9090 if (ConstexprKind == CSK_consteval && 9091 (NewFD->getOverloadedOperator() == OO_New || 9092 NewFD->getOverloadedOperator() == OO_Array_New || 9093 NewFD->getOverloadedOperator() == OO_Delete || 9094 NewFD->getOverloadedOperator() == OO_Array_Delete)) { 9095 Diag(D.getDeclSpec().getConstexprSpecLoc(), 9096 diag::err_invalid_consteval_decl_kind) 9097 << NewFD; 9098 NewFD->setConstexprKind(CSK_constexpr); 9099 } 9100 } 9101 9102 // If __module_private__ was specified, mark the function accordingly. 9103 if (D.getDeclSpec().isModulePrivateSpecified()) { 9104 if (isFunctionTemplateSpecialization) { 9105 SourceLocation ModulePrivateLoc 9106 = D.getDeclSpec().getModulePrivateSpecLoc(); 9107 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 9108 << 0 9109 << FixItHint::CreateRemoval(ModulePrivateLoc); 9110 } else { 9111 NewFD->setModulePrivate(); 9112 if (FunctionTemplate) 9113 FunctionTemplate->setModulePrivate(); 9114 } 9115 } 9116 9117 if (isFriend) { 9118 if (FunctionTemplate) { 9119 FunctionTemplate->setObjectOfFriendDecl(); 9120 FunctionTemplate->setAccess(AS_public); 9121 } 9122 NewFD->setObjectOfFriendDecl(); 9123 NewFD->setAccess(AS_public); 9124 } 9125 9126 // If a function is defined as defaulted or deleted, mark it as such now. 9127 // We'll do the relevant checks on defaulted / deleted functions later. 9128 switch (D.getFunctionDefinitionKind()) { 9129 case FDK_Declaration: 9130 case FDK_Definition: 9131 break; 9132 9133 case FDK_Defaulted: 9134 NewFD->setDefaulted(); 9135 break; 9136 9137 case FDK_Deleted: 9138 NewFD->setDeletedAsWritten(); 9139 break; 9140 } 9141 9142 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 9143 D.isFunctionDefinition()) { 9144 // C++ [class.mfct]p2: 9145 // A member function may be defined (8.4) in its class definition, in 9146 // which case it is an inline member function (7.1.2) 9147 NewFD->setImplicitlyInline(); 9148 } 9149 9150 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 9151 !CurContext->isRecord()) { 9152 // C++ [class.static]p1: 9153 // A data or function member of a class may be declared static 9154 // in a class definition, in which case it is a static member of 9155 // the class. 9156 9157 // Complain about the 'static' specifier if it's on an out-of-line 9158 // member function definition. 9159 9160 // MSVC permits the use of a 'static' storage specifier on an out-of-line 9161 // member function template declaration and class member template 9162 // declaration (MSVC versions before 2015), warn about this. 9163 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 9164 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 9165 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) || 9166 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate())) 9167 ? diag::ext_static_out_of_line : diag::err_static_out_of_line) 9168 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 9169 } 9170 9171 // C++11 [except.spec]p15: 9172 // A deallocation function with no exception-specification is treated 9173 // as if it were specified with noexcept(true). 9174 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 9175 if ((Name.getCXXOverloadedOperator() == OO_Delete || 9176 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 9177 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 9178 NewFD->setType(Context.getFunctionType( 9179 FPT->getReturnType(), FPT->getParamTypes(), 9180 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 9181 } 9182 9183 // Filter out previous declarations that don't match the scope. 9184 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 9185 D.getCXXScopeSpec().isNotEmpty() || 9186 isMemberSpecialization || 9187 isFunctionTemplateSpecialization); 9188 9189 // Handle GNU asm-label extension (encoded as an attribute). 9190 if (Expr *E = (Expr*) D.getAsmLabel()) { 9191 // The parser guarantees this is a string. 9192 StringLiteral *SE = cast<StringLiteral>(E); 9193 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(), 9194 /*IsLiteralLabel=*/true, 9195 SE->getStrTokenLoc(0))); 9196 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 9197 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 9198 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 9199 if (I != ExtnameUndeclaredIdentifiers.end()) { 9200 if (isDeclExternC(NewFD)) { 9201 NewFD->addAttr(I->second); 9202 ExtnameUndeclaredIdentifiers.erase(I); 9203 } else 9204 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 9205 << /*Variable*/0 << NewFD; 9206 } 9207 } 9208 9209 // Copy the parameter declarations from the declarator D to the function 9210 // declaration NewFD, if they are available. First scavenge them into Params. 9211 SmallVector<ParmVarDecl*, 16> Params; 9212 unsigned FTIIdx; 9213 if (D.isFunctionDeclarator(FTIIdx)) { 9214 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 9215 9216 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 9217 // function that takes no arguments, not a function that takes a 9218 // single void argument. 9219 // We let through "const void" here because Sema::GetTypeForDeclarator 9220 // already checks for that case. 9221 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 9222 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 9223 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 9224 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 9225 Param->setDeclContext(NewFD); 9226 Params.push_back(Param); 9227 9228 if (Param->isInvalidDecl()) 9229 NewFD->setInvalidDecl(); 9230 } 9231 } 9232 9233 if (!getLangOpts().CPlusPlus) { 9234 // In C, find all the tag declarations from the prototype and move them 9235 // into the function DeclContext. Remove them from the surrounding tag 9236 // injection context of the function, which is typically but not always 9237 // the TU. 9238 DeclContext *PrototypeTagContext = 9239 getTagInjectionContext(NewFD->getLexicalDeclContext()); 9240 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 9241 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 9242 9243 // We don't want to reparent enumerators. Look at their parent enum 9244 // instead. 9245 if (!TD) { 9246 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 9247 TD = cast<EnumDecl>(ECD->getDeclContext()); 9248 } 9249 if (!TD) 9250 continue; 9251 DeclContext *TagDC = TD->getLexicalDeclContext(); 9252 if (!TagDC->containsDecl(TD)) 9253 continue; 9254 TagDC->removeDecl(TD); 9255 TD->setDeclContext(NewFD); 9256 NewFD->addDecl(TD); 9257 9258 // Preserve the lexical DeclContext if it is not the surrounding tag 9259 // injection context of the FD. In this example, the semantic context of 9260 // E will be f and the lexical context will be S, while both the 9261 // semantic and lexical contexts of S will be f: 9262 // void f(struct S { enum E { a } f; } s); 9263 if (TagDC != PrototypeTagContext) 9264 TD->setLexicalDeclContext(TagDC); 9265 } 9266 } 9267 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 9268 // When we're declaring a function with a typedef, typeof, etc as in the 9269 // following example, we'll need to synthesize (unnamed) 9270 // parameters for use in the declaration. 9271 // 9272 // @code 9273 // typedef void fn(int); 9274 // fn f; 9275 // @endcode 9276 9277 // Synthesize a parameter for each argument type. 9278 for (const auto &AI : FT->param_types()) { 9279 ParmVarDecl *Param = 9280 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 9281 Param->setScopeInfo(0, Params.size()); 9282 Params.push_back(Param); 9283 } 9284 } else { 9285 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 9286 "Should not need args for typedef of non-prototype fn"); 9287 } 9288 9289 // Finally, we know we have the right number of parameters, install them. 9290 NewFD->setParams(Params); 9291 9292 if (D.getDeclSpec().isNoreturnSpecified()) 9293 NewFD->addAttr(C11NoReturnAttr::Create(Context, 9294 D.getDeclSpec().getNoreturnSpecLoc(), 9295 AttributeCommonInfo::AS_Keyword)); 9296 9297 // Functions returning a variably modified type violate C99 6.7.5.2p2 9298 // because all functions have linkage. 9299 if (!NewFD->isInvalidDecl() && 9300 NewFD->getReturnType()->isVariablyModifiedType()) { 9301 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 9302 NewFD->setInvalidDecl(); 9303 } 9304 9305 // Apply an implicit SectionAttr if '#pragma clang section text' is active 9306 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && 9307 !NewFD->hasAttr<SectionAttr>()) 9308 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit( 9309 Context, PragmaClangTextSection.SectionName, 9310 PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma)); 9311 9312 // Apply an implicit SectionAttr if #pragma code_seg is active. 9313 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 9314 !NewFD->hasAttr<SectionAttr>()) { 9315 NewFD->addAttr(SectionAttr::CreateImplicit( 9316 Context, CodeSegStack.CurrentValue->getString(), 9317 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 9318 SectionAttr::Declspec_allocate)); 9319 if (UnifySection(CodeSegStack.CurrentValue->getString(), 9320 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 9321 ASTContext::PSF_Read, 9322 NewFD)) 9323 NewFD->dropAttr<SectionAttr>(); 9324 } 9325 9326 // Apply an implicit CodeSegAttr from class declspec or 9327 // apply an implicit SectionAttr from #pragma code_seg if active. 9328 if (!NewFD->hasAttr<CodeSegAttr>()) { 9329 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD, 9330 D.isFunctionDefinition())) { 9331 NewFD->addAttr(SAttr); 9332 } 9333 } 9334 9335 // Handle attributes. 9336 ProcessDeclAttributes(S, NewFD, D); 9337 9338 if (getLangOpts().OpenCL) { 9339 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 9340 // type declaration will generate a compilation error. 9341 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); 9342 if (AddressSpace != LangAS::Default) { 9343 Diag(NewFD->getLocation(), 9344 diag::err_opencl_return_value_with_address_space); 9345 NewFD->setInvalidDecl(); 9346 } 9347 } 9348 9349 if (!getLangOpts().CPlusPlus) { 9350 // Perform semantic checking on the function declaration. 9351 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9352 CheckMain(NewFD, D.getDeclSpec()); 9353 9354 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9355 CheckMSVCRTEntryPoint(NewFD); 9356 9357 if (!NewFD->isInvalidDecl()) 9358 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9359 isMemberSpecialization)); 9360 else if (!Previous.empty()) 9361 // Recover gracefully from an invalid redeclaration. 9362 D.setRedeclaration(true); 9363 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9364 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9365 "previous declaration set still overloaded"); 9366 9367 // Diagnose no-prototype function declarations with calling conventions that 9368 // don't support variadic calls. Only do this in C and do it after merging 9369 // possibly prototyped redeclarations. 9370 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 9371 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 9372 CallingConv CC = FT->getExtInfo().getCC(); 9373 if (!supportsVariadicCall(CC)) { 9374 // Windows system headers sometimes accidentally use stdcall without 9375 // (void) parameters, so we relax this to a warning. 9376 int DiagID = 9377 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 9378 Diag(NewFD->getLocation(), DiagID) 9379 << FunctionType::getNameForCallConv(CC); 9380 } 9381 } 9382 9383 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() || 9384 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion()) 9385 checkNonTrivialCUnion(NewFD->getReturnType(), 9386 NewFD->getReturnTypeSourceRange().getBegin(), 9387 NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy); 9388 } else { 9389 // C++11 [replacement.functions]p3: 9390 // The program's definitions shall not be specified as inline. 9391 // 9392 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 9393 // 9394 // Suppress the diagnostic if the function is __attribute__((used)), since 9395 // that forces an external definition to be emitted. 9396 if (D.getDeclSpec().isInlineSpecified() && 9397 NewFD->isReplaceableGlobalAllocationFunction() && 9398 !NewFD->hasAttr<UsedAttr>()) 9399 Diag(D.getDeclSpec().getInlineSpecLoc(), 9400 diag::ext_operator_new_delete_declared_inline) 9401 << NewFD->getDeclName(); 9402 9403 // If the declarator is a template-id, translate the parser's template 9404 // argument list into our AST format. 9405 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 9406 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 9407 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 9408 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 9409 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 9410 TemplateId->NumArgs); 9411 translateTemplateArguments(TemplateArgsPtr, 9412 TemplateArgs); 9413 9414 HasExplicitTemplateArgs = true; 9415 9416 if (NewFD->isInvalidDecl()) { 9417 HasExplicitTemplateArgs = false; 9418 } else if (FunctionTemplate) { 9419 // Function template with explicit template arguments. 9420 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 9421 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 9422 9423 HasExplicitTemplateArgs = false; 9424 } else { 9425 assert((isFunctionTemplateSpecialization || 9426 D.getDeclSpec().isFriendSpecified()) && 9427 "should have a 'template<>' for this decl"); 9428 // "friend void foo<>(int);" is an implicit specialization decl. 9429 isFunctionTemplateSpecialization = true; 9430 } 9431 } else if (isFriend && isFunctionTemplateSpecialization) { 9432 // This combination is only possible in a recovery case; the user 9433 // wrote something like: 9434 // template <> friend void foo(int); 9435 // which we're recovering from as if the user had written: 9436 // friend void foo<>(int); 9437 // Go ahead and fake up a template id. 9438 HasExplicitTemplateArgs = true; 9439 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 9440 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 9441 } 9442 9443 // We do not add HD attributes to specializations here because 9444 // they may have different constexpr-ness compared to their 9445 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 9446 // may end up with different effective targets. Instead, a 9447 // specialization inherits its target attributes from its template 9448 // in the CheckFunctionTemplateSpecialization() call below. 9449 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization) 9450 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 9451 9452 // If it's a friend (and only if it's a friend), it's possible 9453 // that either the specialized function type or the specialized 9454 // template is dependent, and therefore matching will fail. In 9455 // this case, don't check the specialization yet. 9456 bool InstantiationDependent = false; 9457 if (isFunctionTemplateSpecialization && isFriend && 9458 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 9459 TemplateSpecializationType::anyDependentTemplateArguments( 9460 TemplateArgs, 9461 InstantiationDependent))) { 9462 assert(HasExplicitTemplateArgs && 9463 "friend function specialization without template args"); 9464 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 9465 Previous)) 9466 NewFD->setInvalidDecl(); 9467 } else if (isFunctionTemplateSpecialization) { 9468 if (CurContext->isDependentContext() && CurContext->isRecord() 9469 && !isFriend) { 9470 isDependentClassScopeExplicitSpecialization = true; 9471 } else if (!NewFD->isInvalidDecl() && 9472 CheckFunctionTemplateSpecialization( 9473 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), 9474 Previous)) 9475 NewFD->setInvalidDecl(); 9476 9477 // C++ [dcl.stc]p1: 9478 // A storage-class-specifier shall not be specified in an explicit 9479 // specialization (14.7.3) 9480 FunctionTemplateSpecializationInfo *Info = 9481 NewFD->getTemplateSpecializationInfo(); 9482 if (Info && SC != SC_None) { 9483 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 9484 Diag(NewFD->getLocation(), 9485 diag::err_explicit_specialization_inconsistent_storage_class) 9486 << SC 9487 << FixItHint::CreateRemoval( 9488 D.getDeclSpec().getStorageClassSpecLoc()); 9489 9490 else 9491 Diag(NewFD->getLocation(), 9492 diag::ext_explicit_specialization_storage_class) 9493 << FixItHint::CreateRemoval( 9494 D.getDeclSpec().getStorageClassSpecLoc()); 9495 } 9496 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 9497 if (CheckMemberSpecialization(NewFD, Previous)) 9498 NewFD->setInvalidDecl(); 9499 } 9500 9501 // Perform semantic checking on the function declaration. 9502 if (!isDependentClassScopeExplicitSpecialization) { 9503 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9504 CheckMain(NewFD, D.getDeclSpec()); 9505 9506 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9507 CheckMSVCRTEntryPoint(NewFD); 9508 9509 if (!NewFD->isInvalidDecl()) 9510 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9511 isMemberSpecialization)); 9512 else if (!Previous.empty()) 9513 // Recover gracefully from an invalid redeclaration. 9514 D.setRedeclaration(true); 9515 } 9516 9517 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9518 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9519 "previous declaration set still overloaded"); 9520 9521 NamedDecl *PrincipalDecl = (FunctionTemplate 9522 ? cast<NamedDecl>(FunctionTemplate) 9523 : NewFD); 9524 9525 if (isFriend && NewFD->getPreviousDecl()) { 9526 AccessSpecifier Access = AS_public; 9527 if (!NewFD->isInvalidDecl()) 9528 Access = NewFD->getPreviousDecl()->getAccess(); 9529 9530 NewFD->setAccess(Access); 9531 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 9532 } 9533 9534 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 9535 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 9536 PrincipalDecl->setNonMemberOperator(); 9537 9538 // If we have a function template, check the template parameter 9539 // list. This will check and merge default template arguments. 9540 if (FunctionTemplate) { 9541 FunctionTemplateDecl *PrevTemplate = 9542 FunctionTemplate->getPreviousDecl(); 9543 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 9544 PrevTemplate ? PrevTemplate->getTemplateParameters() 9545 : nullptr, 9546 D.getDeclSpec().isFriendSpecified() 9547 ? (D.isFunctionDefinition() 9548 ? TPC_FriendFunctionTemplateDefinition 9549 : TPC_FriendFunctionTemplate) 9550 : (D.getCXXScopeSpec().isSet() && 9551 DC && DC->isRecord() && 9552 DC->isDependentContext()) 9553 ? TPC_ClassTemplateMember 9554 : TPC_FunctionTemplate); 9555 } 9556 9557 if (NewFD->isInvalidDecl()) { 9558 // Ignore all the rest of this. 9559 } else if (!D.isRedeclaration()) { 9560 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 9561 AddToScope }; 9562 // Fake up an access specifier if it's supposed to be a class member. 9563 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 9564 NewFD->setAccess(AS_public); 9565 9566 // Qualified decls generally require a previous declaration. 9567 if (D.getCXXScopeSpec().isSet()) { 9568 // ...with the major exception of templated-scope or 9569 // dependent-scope friend declarations. 9570 9571 // TODO: we currently also suppress this check in dependent 9572 // contexts because (1) the parameter depth will be off when 9573 // matching friend templates and (2) we might actually be 9574 // selecting a friend based on a dependent factor. But there 9575 // are situations where these conditions don't apply and we 9576 // can actually do this check immediately. 9577 // 9578 // Unless the scope is dependent, it's always an error if qualified 9579 // redeclaration lookup found nothing at all. Diagnose that now; 9580 // nothing will diagnose that error later. 9581 if (isFriend && 9582 (D.getCXXScopeSpec().getScopeRep()->isDependent() || 9583 (!Previous.empty() && CurContext->isDependentContext()))) { 9584 // ignore these 9585 } else { 9586 // The user tried to provide an out-of-line definition for a 9587 // function that is a member of a class or namespace, but there 9588 // was no such member function declared (C++ [class.mfct]p2, 9589 // C++ [namespace.memdef]p2). For example: 9590 // 9591 // class X { 9592 // void f() const; 9593 // }; 9594 // 9595 // void X::f() { } // ill-formed 9596 // 9597 // Complain about this problem, and attempt to suggest close 9598 // matches (e.g., those that differ only in cv-qualifiers and 9599 // whether the parameter types are references). 9600 9601 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9602 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 9603 AddToScope = ExtraArgs.AddToScope; 9604 return Result; 9605 } 9606 } 9607 9608 // Unqualified local friend declarations are required to resolve 9609 // to something. 9610 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 9611 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9612 *this, Previous, NewFD, ExtraArgs, true, S)) { 9613 AddToScope = ExtraArgs.AddToScope; 9614 return Result; 9615 } 9616 } 9617 } else if (!D.isFunctionDefinition() && 9618 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 9619 !isFriend && !isFunctionTemplateSpecialization && 9620 !isMemberSpecialization) { 9621 // An out-of-line member function declaration must also be a 9622 // definition (C++ [class.mfct]p2). 9623 // Note that this is not the case for explicit specializations of 9624 // function templates or member functions of class templates, per 9625 // C++ [temp.expl.spec]p2. We also allow these declarations as an 9626 // extension for compatibility with old SWIG code which likes to 9627 // generate them. 9628 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 9629 << D.getCXXScopeSpec().getRange(); 9630 } 9631 } 9632 9633 ProcessPragmaWeak(S, NewFD); 9634 checkAttributesAfterMerging(*this, *NewFD); 9635 9636 AddKnownFunctionAttributes(NewFD); 9637 9638 if (NewFD->hasAttr<OverloadableAttr>() && 9639 !NewFD->getType()->getAs<FunctionProtoType>()) { 9640 Diag(NewFD->getLocation(), 9641 diag::err_attribute_overloadable_no_prototype) 9642 << NewFD; 9643 9644 // Turn this into a variadic function with no parameters. 9645 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 9646 FunctionProtoType::ExtProtoInfo EPI( 9647 Context.getDefaultCallingConvention(true, false)); 9648 EPI.Variadic = true; 9649 EPI.ExtInfo = FT->getExtInfo(); 9650 9651 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 9652 NewFD->setType(R); 9653 } 9654 9655 // If there's a #pragma GCC visibility in scope, and this isn't a class 9656 // member, set the visibility of this function. 9657 if (!DC->isRecord() && NewFD->isExternallyVisible()) 9658 AddPushedVisibilityAttribute(NewFD); 9659 9660 // If there's a #pragma clang arc_cf_code_audited in scope, consider 9661 // marking the function. 9662 AddCFAuditedAttribute(NewFD); 9663 9664 // If this is a function definition, check if we have to apply optnone due to 9665 // a pragma. 9666 if(D.isFunctionDefinition()) 9667 AddRangeBasedOptnone(NewFD); 9668 9669 // If this is the first declaration of an extern C variable, update 9670 // the map of such variables. 9671 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 9672 isIncompleteDeclExternC(*this, NewFD)) 9673 RegisterLocallyScopedExternCDecl(NewFD, S); 9674 9675 // Set this FunctionDecl's range up to the right paren. 9676 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 9677 9678 if (D.isRedeclaration() && !Previous.empty()) { 9679 NamedDecl *Prev = Previous.getRepresentativeDecl(); 9680 checkDLLAttributeRedeclaration(*this, Prev, NewFD, 9681 isMemberSpecialization || 9682 isFunctionTemplateSpecialization, 9683 D.isFunctionDefinition()); 9684 } 9685 9686 if (getLangOpts().CUDA) { 9687 IdentifierInfo *II = NewFD->getIdentifier(); 9688 if (II && II->isStr(getCudaConfigureFuncName()) && 9689 !NewFD->isInvalidDecl() && 9690 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 9691 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 9692 Diag(NewFD->getLocation(), diag::err_config_scalar_return) 9693 << getCudaConfigureFuncName(); 9694 Context.setcudaConfigureCallDecl(NewFD); 9695 } 9696 9697 // Variadic functions, other than a *declaration* of printf, are not allowed 9698 // in device-side CUDA code, unless someone passed 9699 // -fcuda-allow-variadic-functions. 9700 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 9701 (NewFD->hasAttr<CUDADeviceAttr>() || 9702 NewFD->hasAttr<CUDAGlobalAttr>()) && 9703 !(II && II->isStr("printf") && NewFD->isExternC() && 9704 !D.isFunctionDefinition())) { 9705 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 9706 } 9707 } 9708 9709 MarkUnusedFileScopedDecl(NewFD); 9710 9711 9712 9713 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) { 9714 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 9715 if ((getLangOpts().OpenCLVersion >= 120) 9716 && (SC == SC_Static)) { 9717 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 9718 D.setInvalidType(); 9719 } 9720 9721 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 9722 if (!NewFD->getReturnType()->isVoidType()) { 9723 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 9724 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 9725 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 9726 : FixItHint()); 9727 D.setInvalidType(); 9728 } 9729 9730 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 9731 for (auto Param : NewFD->parameters()) 9732 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 9733 9734 if (getLangOpts().OpenCLCPlusPlus) { 9735 if (DC->isRecord()) { 9736 Diag(D.getIdentifierLoc(), diag::err_method_kernel); 9737 D.setInvalidType(); 9738 } 9739 if (FunctionTemplate) { 9740 Diag(D.getIdentifierLoc(), diag::err_template_kernel); 9741 D.setInvalidType(); 9742 } 9743 } 9744 } 9745 9746 if (getLangOpts().CPlusPlus) { 9747 if (FunctionTemplate) { 9748 if (NewFD->isInvalidDecl()) 9749 FunctionTemplate->setInvalidDecl(); 9750 return FunctionTemplate; 9751 } 9752 9753 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 9754 CompleteMemberSpecialization(NewFD, Previous); 9755 } 9756 9757 for (const ParmVarDecl *Param : NewFD->parameters()) { 9758 QualType PT = Param->getType(); 9759 9760 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 9761 // types. 9762 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 9763 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 9764 QualType ElemTy = PipeTy->getElementType(); 9765 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 9766 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 9767 D.setInvalidType(); 9768 } 9769 } 9770 } 9771 } 9772 9773 // Here we have an function template explicit specialization at class scope. 9774 // The actual specialization will be postponed to template instatiation 9775 // time via the ClassScopeFunctionSpecializationDecl node. 9776 if (isDependentClassScopeExplicitSpecialization) { 9777 ClassScopeFunctionSpecializationDecl *NewSpec = 9778 ClassScopeFunctionSpecializationDecl::Create( 9779 Context, CurContext, NewFD->getLocation(), 9780 cast<CXXMethodDecl>(NewFD), 9781 HasExplicitTemplateArgs, TemplateArgs); 9782 CurContext->addDecl(NewSpec); 9783 AddToScope = false; 9784 } 9785 9786 // Diagnose availability attributes. Availability cannot be used on functions 9787 // that are run during load/unload. 9788 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { 9789 if (NewFD->hasAttr<ConstructorAttr>()) { 9790 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9791 << 1; 9792 NewFD->dropAttr<AvailabilityAttr>(); 9793 } 9794 if (NewFD->hasAttr<DestructorAttr>()) { 9795 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9796 << 2; 9797 NewFD->dropAttr<AvailabilityAttr>(); 9798 } 9799 } 9800 9801 // Diagnose no_builtin attribute on function declaration that are not a 9802 // definition. 9803 // FIXME: We should really be doing this in 9804 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to 9805 // the FunctionDecl and at this point of the code 9806 // FunctionDecl::isThisDeclarationADefinition() which always returns `false` 9807 // because Sema::ActOnStartOfFunctionDef has not been called yet. 9808 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>()) 9809 switch (D.getFunctionDefinitionKind()) { 9810 case FDK_Defaulted: 9811 case FDK_Deleted: 9812 Diag(NBA->getLocation(), 9813 diag::err_attribute_no_builtin_on_defaulted_deleted_function) 9814 << NBA->getSpelling(); 9815 break; 9816 case FDK_Declaration: 9817 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition) 9818 << NBA->getSpelling(); 9819 break; 9820 case FDK_Definition: 9821 break; 9822 } 9823 9824 return NewFD; 9825 } 9826 9827 /// Return a CodeSegAttr from a containing class. The Microsoft docs say 9828 /// when __declspec(code_seg) "is applied to a class, all member functions of 9829 /// the class and nested classes -- this includes compiler-generated special 9830 /// member functions -- are put in the specified segment." 9831 /// The actual behavior is a little more complicated. The Microsoft compiler 9832 /// won't check outer classes if there is an active value from #pragma code_seg. 9833 /// The CodeSeg is always applied from the direct parent but only from outer 9834 /// classes when the #pragma code_seg stack is empty. See: 9835 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer 9836 /// available since MS has removed the page. 9837 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) { 9838 const auto *Method = dyn_cast<CXXMethodDecl>(FD); 9839 if (!Method) 9840 return nullptr; 9841 const CXXRecordDecl *Parent = Method->getParent(); 9842 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 9843 Attr *NewAttr = SAttr->clone(S.getASTContext()); 9844 NewAttr->setImplicit(true); 9845 return NewAttr; 9846 } 9847 9848 // The Microsoft compiler won't check outer classes for the CodeSeg 9849 // when the #pragma code_seg stack is active. 9850 if (S.CodeSegStack.CurrentValue) 9851 return nullptr; 9852 9853 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) { 9854 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 9855 Attr *NewAttr = SAttr->clone(S.getASTContext()); 9856 NewAttr->setImplicit(true); 9857 return NewAttr; 9858 } 9859 } 9860 return nullptr; 9861 } 9862 9863 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a 9864 /// containing class. Otherwise it will return implicit SectionAttr if the 9865 /// function is a definition and there is an active value on CodeSegStack 9866 /// (from the current #pragma code-seg value). 9867 /// 9868 /// \param FD Function being declared. 9869 /// \param IsDefinition Whether it is a definition or just a declarartion. 9870 /// \returns A CodeSegAttr or SectionAttr to apply to the function or 9871 /// nullptr if no attribute should be added. 9872 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, 9873 bool IsDefinition) { 9874 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD)) 9875 return A; 9876 if (!FD->hasAttr<SectionAttr>() && IsDefinition && 9877 CodeSegStack.CurrentValue) 9878 return SectionAttr::CreateImplicit( 9879 getASTContext(), CodeSegStack.CurrentValue->getString(), 9880 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 9881 SectionAttr::Declspec_allocate); 9882 return nullptr; 9883 } 9884 9885 /// Determines if we can perform a correct type check for \p D as a 9886 /// redeclaration of \p PrevDecl. If not, we can generally still perform a 9887 /// best-effort check. 9888 /// 9889 /// \param NewD The new declaration. 9890 /// \param OldD The old declaration. 9891 /// \param NewT The portion of the type of the new declaration to check. 9892 /// \param OldT The portion of the type of the old declaration to check. 9893 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, 9894 QualType NewT, QualType OldT) { 9895 if (!NewD->getLexicalDeclContext()->isDependentContext()) 9896 return true; 9897 9898 // For dependently-typed local extern declarations and friends, we can't 9899 // perform a correct type check in general until instantiation: 9900 // 9901 // int f(); 9902 // template<typename T> void g() { T f(); } 9903 // 9904 // (valid if g() is only instantiated with T = int). 9905 if (NewT->isDependentType() && 9906 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind())) 9907 return false; 9908 9909 // Similarly, if the previous declaration was a dependent local extern 9910 // declaration, we don't really know its type yet. 9911 if (OldT->isDependentType() && OldD->isLocalExternDecl()) 9912 return false; 9913 9914 return true; 9915 } 9916 9917 /// Checks if the new declaration declared in dependent context must be 9918 /// put in the same redeclaration chain as the specified declaration. 9919 /// 9920 /// \param D Declaration that is checked. 9921 /// \param PrevDecl Previous declaration found with proper lookup method for the 9922 /// same declaration name. 9923 /// \returns True if D must be added to the redeclaration chain which PrevDecl 9924 /// belongs to. 9925 /// 9926 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 9927 if (!D->getLexicalDeclContext()->isDependentContext()) 9928 return true; 9929 9930 // Don't chain dependent friend function definitions until instantiation, to 9931 // permit cases like 9932 // 9933 // void func(); 9934 // template<typename T> class C1 { friend void func() {} }; 9935 // template<typename T> class C2 { friend void func() {} }; 9936 // 9937 // ... which is valid if only one of C1 and C2 is ever instantiated. 9938 // 9939 // FIXME: This need only apply to function definitions. For now, we proxy 9940 // this by checking for a file-scope function. We do not want this to apply 9941 // to friend declarations nominating member functions, because that gets in 9942 // the way of access checks. 9943 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext()) 9944 return false; 9945 9946 auto *VD = dyn_cast<ValueDecl>(D); 9947 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl); 9948 return !VD || !PrevVD || 9949 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(), 9950 PrevVD->getType()); 9951 } 9952 9953 /// Check the target attribute of the function for MultiVersion 9954 /// validity. 9955 /// 9956 /// Returns true if there was an error, false otherwise. 9957 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { 9958 const auto *TA = FD->getAttr<TargetAttr>(); 9959 assert(TA && "MultiVersion Candidate requires a target attribute"); 9960 ParsedTargetAttr ParseInfo = TA->parse(); 9961 const TargetInfo &TargetInfo = S.Context.getTargetInfo(); 9962 enum ErrType { Feature = 0, Architecture = 1 }; 9963 9964 if (!ParseInfo.Architecture.empty() && 9965 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) { 9966 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9967 << Architecture << ParseInfo.Architecture; 9968 return true; 9969 } 9970 9971 for (const auto &Feat : ParseInfo.Features) { 9972 auto BareFeat = StringRef{Feat}.substr(1); 9973 if (Feat[0] == '-') { 9974 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9975 << Feature << ("no-" + BareFeat).str(); 9976 return true; 9977 } 9978 9979 if (!TargetInfo.validateCpuSupports(BareFeat) || 9980 !TargetInfo.isValidFeatureName(BareFeat)) { 9981 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9982 << Feature << BareFeat; 9983 return true; 9984 } 9985 } 9986 return false; 9987 } 9988 9989 // Provide a white-list of attributes that are allowed to be combined with 9990 // multiversion functions. 9991 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, 9992 MultiVersionKind MVType) { 9993 switch (Kind) { 9994 default: 9995 return false; 9996 case attr::Used: 9997 return MVType == MultiVersionKind::Target; 9998 } 9999 } 10000 10001 static bool HasNonMultiVersionAttributes(const FunctionDecl *FD, 10002 MultiVersionKind MVType) { 10003 for (const Attr *A : FD->attrs()) { 10004 switch (A->getKind()) { 10005 case attr::CPUDispatch: 10006 case attr::CPUSpecific: 10007 if (MVType != MultiVersionKind::CPUDispatch && 10008 MVType != MultiVersionKind::CPUSpecific) 10009 return true; 10010 break; 10011 case attr::Target: 10012 if (MVType != MultiVersionKind::Target) 10013 return true; 10014 break; 10015 default: 10016 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType)) 10017 return true; 10018 break; 10019 } 10020 } 10021 return false; 10022 } 10023 10024 bool Sema::areMultiversionVariantFunctionsCompatible( 10025 const FunctionDecl *OldFD, const FunctionDecl *NewFD, 10026 const PartialDiagnostic &NoProtoDiagID, 10027 const PartialDiagnosticAt &NoteCausedDiagIDAt, 10028 const PartialDiagnosticAt &NoSupportDiagIDAt, 10029 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, 10030 bool ConstexprSupported, bool CLinkageMayDiffer) { 10031 enum DoesntSupport { 10032 FuncTemplates = 0, 10033 VirtFuncs = 1, 10034 DeducedReturn = 2, 10035 Constructors = 3, 10036 Destructors = 4, 10037 DeletedFuncs = 5, 10038 DefaultedFuncs = 6, 10039 ConstexprFuncs = 7, 10040 ConstevalFuncs = 8, 10041 }; 10042 enum Different { 10043 CallingConv = 0, 10044 ReturnType = 1, 10045 ConstexprSpec = 2, 10046 InlineSpec = 3, 10047 StorageClass = 4, 10048 Linkage = 5, 10049 }; 10050 10051 if (NoProtoDiagID.getDiagID() != 0 && OldFD && 10052 !OldFD->getType()->getAs<FunctionProtoType>()) { 10053 Diag(OldFD->getLocation(), NoProtoDiagID); 10054 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second); 10055 return true; 10056 } 10057 10058 if (NoProtoDiagID.getDiagID() != 0 && 10059 !NewFD->getType()->getAs<FunctionProtoType>()) 10060 return Diag(NewFD->getLocation(), NoProtoDiagID); 10061 10062 if (!TemplatesSupported && 10063 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 10064 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10065 << FuncTemplates; 10066 10067 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { 10068 if (NewCXXFD->isVirtual()) 10069 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10070 << VirtFuncs; 10071 10072 if (isa<CXXConstructorDecl>(NewCXXFD)) 10073 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10074 << Constructors; 10075 10076 if (isa<CXXDestructorDecl>(NewCXXFD)) 10077 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10078 << Destructors; 10079 } 10080 10081 if (NewFD->isDeleted()) 10082 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10083 << DeletedFuncs; 10084 10085 if (NewFD->isDefaulted()) 10086 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10087 << DefaultedFuncs; 10088 10089 if (!ConstexprSupported && NewFD->isConstexpr()) 10090 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10091 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs); 10092 10093 QualType NewQType = Context.getCanonicalType(NewFD->getType()); 10094 const auto *NewType = cast<FunctionType>(NewQType); 10095 QualType NewReturnType = NewType->getReturnType(); 10096 10097 if (NewReturnType->isUndeducedType()) 10098 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10099 << DeducedReturn; 10100 10101 // Ensure the return type is identical. 10102 if (OldFD) { 10103 QualType OldQType = Context.getCanonicalType(OldFD->getType()); 10104 const auto *OldType = cast<FunctionType>(OldQType); 10105 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 10106 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 10107 10108 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) 10109 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv; 10110 10111 QualType OldReturnType = OldType->getReturnType(); 10112 10113 if (OldReturnType != NewReturnType) 10114 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType; 10115 10116 if (OldFD->getConstexprKind() != NewFD->getConstexprKind()) 10117 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec; 10118 10119 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) 10120 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec; 10121 10122 if (OldFD->getStorageClass() != NewFD->getStorageClass()) 10123 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass; 10124 10125 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC()) 10126 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage; 10127 10128 if (CheckEquivalentExceptionSpec( 10129 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), 10130 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) 10131 return true; 10132 } 10133 return false; 10134 } 10135 10136 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, 10137 const FunctionDecl *NewFD, 10138 bool CausesMV, 10139 MultiVersionKind MVType) { 10140 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10141 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10142 if (OldFD) 10143 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10144 return true; 10145 } 10146 10147 bool IsCPUSpecificCPUDispatchMVType = 10148 MVType == MultiVersionKind::CPUDispatch || 10149 MVType == MultiVersionKind::CPUSpecific; 10150 10151 // For now, disallow all other attributes. These should be opt-in, but 10152 // an analysis of all of them is a future FIXME. 10153 if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) { 10154 S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs) 10155 << IsCPUSpecificCPUDispatchMVType; 10156 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10157 return true; 10158 } 10159 10160 if (HasNonMultiVersionAttributes(NewFD, MVType)) 10161 return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs) 10162 << IsCPUSpecificCPUDispatchMVType; 10163 10164 // Only allow transition to MultiVersion if it hasn't been used. 10165 if (OldFD && CausesMV && OldFD->isUsed(false)) 10166 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 10167 10168 return S.areMultiversionVariantFunctionsCompatible( 10169 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto), 10170 PartialDiagnosticAt(NewFD->getLocation(), 10171 S.PDiag(diag::note_multiversioning_caused_here)), 10172 PartialDiagnosticAt(NewFD->getLocation(), 10173 S.PDiag(diag::err_multiversion_doesnt_support) 10174 << IsCPUSpecificCPUDispatchMVType), 10175 PartialDiagnosticAt(NewFD->getLocation(), 10176 S.PDiag(diag::err_multiversion_diff)), 10177 /*TemplatesSupported=*/false, 10178 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType, 10179 /*CLinkageMayDiffer=*/false); 10180 } 10181 10182 /// Check the validity of a multiversion function declaration that is the 10183 /// first of its kind. Also sets the multiversion'ness' of the function itself. 10184 /// 10185 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10186 /// 10187 /// Returns true if there was an error, false otherwise. 10188 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD, 10189 MultiVersionKind MVType, 10190 const TargetAttr *TA) { 10191 assert(MVType != MultiVersionKind::None && 10192 "Function lacks multiversion attribute"); 10193 10194 // Target only causes MV if it is default, otherwise this is a normal 10195 // function. 10196 if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion()) 10197 return false; 10198 10199 if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) { 10200 FD->setInvalidDecl(); 10201 return true; 10202 } 10203 10204 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) { 10205 FD->setInvalidDecl(); 10206 return true; 10207 } 10208 10209 FD->setIsMultiVersion(); 10210 return false; 10211 } 10212 10213 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) { 10214 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) { 10215 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None) 10216 return true; 10217 } 10218 10219 return false; 10220 } 10221 10222 static bool CheckTargetCausesMultiVersioning( 10223 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA, 10224 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 10225 LookupResult &Previous) { 10226 const auto *OldTA = OldFD->getAttr<TargetAttr>(); 10227 ParsedTargetAttr NewParsed = NewTA->parse(); 10228 // Sort order doesn't matter, it just needs to be consistent. 10229 llvm::sort(NewParsed.Features); 10230 10231 // If the old decl is NOT MultiVersioned yet, and we don't cause that 10232 // to change, this is a simple redeclaration. 10233 if (!NewTA->isDefaultVersion() && 10234 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) 10235 return false; 10236 10237 // Otherwise, this decl causes MultiVersioning. 10238 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10239 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10240 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10241 NewFD->setInvalidDecl(); 10242 return true; 10243 } 10244 10245 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true, 10246 MultiVersionKind::Target)) { 10247 NewFD->setInvalidDecl(); 10248 return true; 10249 } 10250 10251 if (CheckMultiVersionValue(S, NewFD)) { 10252 NewFD->setInvalidDecl(); 10253 return true; 10254 } 10255 10256 // If this is 'default', permit the forward declaration. 10257 if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) { 10258 Redeclaration = true; 10259 OldDecl = OldFD; 10260 OldFD->setIsMultiVersion(); 10261 NewFD->setIsMultiVersion(); 10262 return false; 10263 } 10264 10265 if (CheckMultiVersionValue(S, OldFD)) { 10266 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10267 NewFD->setInvalidDecl(); 10268 return true; 10269 } 10270 10271 ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>()); 10272 10273 if (OldParsed == NewParsed) { 10274 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10275 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10276 NewFD->setInvalidDecl(); 10277 return true; 10278 } 10279 10280 for (const auto *FD : OldFD->redecls()) { 10281 const auto *CurTA = FD->getAttr<TargetAttr>(); 10282 // We allow forward declarations before ANY multiversioning attributes, but 10283 // nothing after the fact. 10284 if (PreviousDeclsHaveMultiVersionAttribute(FD) && 10285 (!CurTA || CurTA->isInherited())) { 10286 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl) 10287 << 0; 10288 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10289 NewFD->setInvalidDecl(); 10290 return true; 10291 } 10292 } 10293 10294 OldFD->setIsMultiVersion(); 10295 NewFD->setIsMultiVersion(); 10296 Redeclaration = false; 10297 MergeTypeWithPrevious = false; 10298 OldDecl = nullptr; 10299 Previous.clear(); 10300 return false; 10301 } 10302 10303 /// Check the validity of a new function declaration being added to an existing 10304 /// multiversioned declaration collection. 10305 static bool CheckMultiVersionAdditionalDecl( 10306 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, 10307 MultiVersionKind NewMVType, const TargetAttr *NewTA, 10308 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, 10309 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 10310 LookupResult &Previous) { 10311 10312 MultiVersionKind OldMVType = OldFD->getMultiVersionKind(); 10313 // Disallow mixing of multiversioning types. 10314 if ((OldMVType == MultiVersionKind::Target && 10315 NewMVType != MultiVersionKind::Target) || 10316 (NewMVType == MultiVersionKind::Target && 10317 OldMVType != MultiVersionKind::Target)) { 10318 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10319 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10320 NewFD->setInvalidDecl(); 10321 return true; 10322 } 10323 10324 ParsedTargetAttr NewParsed; 10325 if (NewTA) { 10326 NewParsed = NewTA->parse(); 10327 llvm::sort(NewParsed.Features); 10328 } 10329 10330 bool UseMemberUsingDeclRules = 10331 S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); 10332 10333 // Next, check ALL non-overloads to see if this is a redeclaration of a 10334 // previous member of the MultiVersion set. 10335 for (NamedDecl *ND : Previous) { 10336 FunctionDecl *CurFD = ND->getAsFunction(); 10337 if (!CurFD) 10338 continue; 10339 if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) 10340 continue; 10341 10342 if (NewMVType == MultiVersionKind::Target) { 10343 const auto *CurTA = CurFD->getAttr<TargetAttr>(); 10344 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { 10345 NewFD->setIsMultiVersion(); 10346 Redeclaration = true; 10347 OldDecl = ND; 10348 return false; 10349 } 10350 10351 ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>()); 10352 if (CurParsed == NewParsed) { 10353 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10354 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10355 NewFD->setInvalidDecl(); 10356 return true; 10357 } 10358 } else { 10359 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>(); 10360 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>(); 10361 // Handle CPUDispatch/CPUSpecific versions. 10362 // Only 1 CPUDispatch function is allowed, this will make it go through 10363 // the redeclaration errors. 10364 if (NewMVType == MultiVersionKind::CPUDispatch && 10365 CurFD->hasAttr<CPUDispatchAttr>()) { 10366 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() && 10367 std::equal( 10368 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(), 10369 NewCPUDisp->cpus_begin(), 10370 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10371 return Cur->getName() == New->getName(); 10372 })) { 10373 NewFD->setIsMultiVersion(); 10374 Redeclaration = true; 10375 OldDecl = ND; 10376 return false; 10377 } 10378 10379 // If the declarations don't match, this is an error condition. 10380 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch); 10381 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10382 NewFD->setInvalidDecl(); 10383 return true; 10384 } 10385 if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) { 10386 10387 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() && 10388 std::equal( 10389 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(), 10390 NewCPUSpec->cpus_begin(), 10391 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10392 return Cur->getName() == New->getName(); 10393 })) { 10394 NewFD->setIsMultiVersion(); 10395 Redeclaration = true; 10396 OldDecl = ND; 10397 return false; 10398 } 10399 10400 // Only 1 version of CPUSpecific is allowed for each CPU. 10401 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) { 10402 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) { 10403 if (CurII == NewII) { 10404 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs) 10405 << NewII; 10406 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10407 NewFD->setInvalidDecl(); 10408 return true; 10409 } 10410 } 10411 } 10412 } 10413 // If the two decls aren't the same MVType, there is no possible error 10414 // condition. 10415 } 10416 } 10417 10418 // Else, this is simply a non-redecl case. Checking the 'value' is only 10419 // necessary in the Target case, since The CPUSpecific/Dispatch cases are 10420 // handled in the attribute adding step. 10421 if (NewMVType == MultiVersionKind::Target && 10422 CheckMultiVersionValue(S, NewFD)) { 10423 NewFD->setInvalidDecl(); 10424 return true; 10425 } 10426 10427 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, 10428 !OldFD->isMultiVersion(), NewMVType)) { 10429 NewFD->setInvalidDecl(); 10430 return true; 10431 } 10432 10433 // Permit forward declarations in the case where these two are compatible. 10434 if (!OldFD->isMultiVersion()) { 10435 OldFD->setIsMultiVersion(); 10436 NewFD->setIsMultiVersion(); 10437 Redeclaration = true; 10438 OldDecl = OldFD; 10439 return false; 10440 } 10441 10442 NewFD->setIsMultiVersion(); 10443 Redeclaration = false; 10444 MergeTypeWithPrevious = false; 10445 OldDecl = nullptr; 10446 Previous.clear(); 10447 return false; 10448 } 10449 10450 10451 /// Check the validity of a mulitversion function declaration. 10452 /// Also sets the multiversion'ness' of the function itself. 10453 /// 10454 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10455 /// 10456 /// Returns true if there was an error, false otherwise. 10457 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, 10458 bool &Redeclaration, NamedDecl *&OldDecl, 10459 bool &MergeTypeWithPrevious, 10460 LookupResult &Previous) { 10461 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 10462 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>(); 10463 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>(); 10464 10465 // Mixing Multiversioning types is prohibited. 10466 if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) || 10467 (NewCPUDisp && NewCPUSpec)) { 10468 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10469 NewFD->setInvalidDecl(); 10470 return true; 10471 } 10472 10473 MultiVersionKind MVType = NewFD->getMultiVersionKind(); 10474 10475 // Main isn't allowed to become a multiversion function, however it IS 10476 // permitted to have 'main' be marked with the 'target' optimization hint. 10477 if (NewFD->isMain()) { 10478 if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) || 10479 MVType == MultiVersionKind::CPUDispatch || 10480 MVType == MultiVersionKind::CPUSpecific) { 10481 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); 10482 NewFD->setInvalidDecl(); 10483 return true; 10484 } 10485 return false; 10486 } 10487 10488 if (!OldDecl || !OldDecl->getAsFunction() || 10489 OldDecl->getDeclContext()->getRedeclContext() != 10490 NewFD->getDeclContext()->getRedeclContext()) { 10491 // If there's no previous declaration, AND this isn't attempting to cause 10492 // multiversioning, this isn't an error condition. 10493 if (MVType == MultiVersionKind::None) 10494 return false; 10495 return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA); 10496 } 10497 10498 FunctionDecl *OldFD = OldDecl->getAsFunction(); 10499 10500 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None) 10501 return false; 10502 10503 if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) { 10504 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl) 10505 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target); 10506 NewFD->setInvalidDecl(); 10507 return true; 10508 } 10509 10510 // Handle the target potentially causes multiversioning case. 10511 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target) 10512 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA, 10513 Redeclaration, OldDecl, 10514 MergeTypeWithPrevious, Previous); 10515 10516 // At this point, we have a multiversion function decl (in OldFD) AND an 10517 // appropriate attribute in the current function decl. Resolve that these are 10518 // still compatible with previous declarations. 10519 return CheckMultiVersionAdditionalDecl( 10520 S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration, 10521 OldDecl, MergeTypeWithPrevious, Previous); 10522 } 10523 10524 /// Perform semantic checking of a new function declaration. 10525 /// 10526 /// Performs semantic analysis of the new function declaration 10527 /// NewFD. This routine performs all semantic checking that does not 10528 /// require the actual declarator involved in the declaration, and is 10529 /// used both for the declaration of functions as they are parsed 10530 /// (called via ActOnDeclarator) and for the declaration of functions 10531 /// that have been instantiated via C++ template instantiation (called 10532 /// via InstantiateDecl). 10533 /// 10534 /// \param IsMemberSpecialization whether this new function declaration is 10535 /// a member specialization (that replaces any definition provided by the 10536 /// previous declaration). 10537 /// 10538 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10539 /// 10540 /// \returns true if the function declaration is a redeclaration. 10541 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 10542 LookupResult &Previous, 10543 bool IsMemberSpecialization) { 10544 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 10545 "Variably modified return types are not handled here"); 10546 10547 // Determine whether the type of this function should be merged with 10548 // a previous visible declaration. This never happens for functions in C++, 10549 // and always happens in C if the previous declaration was visible. 10550 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 10551 !Previous.isShadowed(); 10552 10553 bool Redeclaration = false; 10554 NamedDecl *OldDecl = nullptr; 10555 bool MayNeedOverloadableChecks = false; 10556 10557 // Merge or overload the declaration with an existing declaration of 10558 // the same name, if appropriate. 10559 if (!Previous.empty()) { 10560 // Determine whether NewFD is an overload of PrevDecl or 10561 // a declaration that requires merging. If it's an overload, 10562 // there's no more work to do here; we'll just add the new 10563 // function to the scope. 10564 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { 10565 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 10566 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 10567 Redeclaration = true; 10568 OldDecl = Candidate; 10569 } 10570 } else { 10571 MayNeedOverloadableChecks = true; 10572 switch (CheckOverload(S, NewFD, Previous, OldDecl, 10573 /*NewIsUsingDecl*/ false)) { 10574 case Ovl_Match: 10575 Redeclaration = true; 10576 break; 10577 10578 case Ovl_NonFunction: 10579 Redeclaration = true; 10580 break; 10581 10582 case Ovl_Overload: 10583 Redeclaration = false; 10584 break; 10585 } 10586 } 10587 } 10588 10589 // Check for a previous extern "C" declaration with this name. 10590 if (!Redeclaration && 10591 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 10592 if (!Previous.empty()) { 10593 // This is an extern "C" declaration with the same name as a previous 10594 // declaration, and thus redeclares that entity... 10595 Redeclaration = true; 10596 OldDecl = Previous.getFoundDecl(); 10597 MergeTypeWithPrevious = false; 10598 10599 // ... except in the presence of __attribute__((overloadable)). 10600 if (OldDecl->hasAttr<OverloadableAttr>() || 10601 NewFD->hasAttr<OverloadableAttr>()) { 10602 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 10603 MayNeedOverloadableChecks = true; 10604 Redeclaration = false; 10605 OldDecl = nullptr; 10606 } 10607 } 10608 } 10609 } 10610 10611 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, 10612 MergeTypeWithPrevious, Previous)) 10613 return Redeclaration; 10614 10615 // C++11 [dcl.constexpr]p8: 10616 // A constexpr specifier for a non-static member function that is not 10617 // a constructor declares that member function to be const. 10618 // 10619 // This needs to be delayed until we know whether this is an out-of-line 10620 // definition of a static member function. 10621 // 10622 // This rule is not present in C++1y, so we produce a backwards 10623 // compatibility warning whenever it happens in C++11. 10624 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 10625 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 10626 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 10627 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) { 10628 CXXMethodDecl *OldMD = nullptr; 10629 if (OldDecl) 10630 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 10631 if (!OldMD || !OldMD->isStatic()) { 10632 const FunctionProtoType *FPT = 10633 MD->getType()->castAs<FunctionProtoType>(); 10634 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10635 EPI.TypeQuals.addConst(); 10636 MD->setType(Context.getFunctionType(FPT->getReturnType(), 10637 FPT->getParamTypes(), EPI)); 10638 10639 // Warn that we did this, if we're not performing template instantiation. 10640 // In that case, we'll have warned already when the template was defined. 10641 if (!inTemplateInstantiation()) { 10642 SourceLocation AddConstLoc; 10643 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 10644 .IgnoreParens().getAs<FunctionTypeLoc>()) 10645 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 10646 10647 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 10648 << FixItHint::CreateInsertion(AddConstLoc, " const"); 10649 } 10650 } 10651 } 10652 10653 if (Redeclaration) { 10654 // NewFD and OldDecl represent declarations that need to be 10655 // merged. 10656 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 10657 NewFD->setInvalidDecl(); 10658 return Redeclaration; 10659 } 10660 10661 Previous.clear(); 10662 Previous.addDecl(OldDecl); 10663 10664 if (FunctionTemplateDecl *OldTemplateDecl = 10665 dyn_cast<FunctionTemplateDecl>(OldDecl)) { 10666 auto *OldFD = OldTemplateDecl->getTemplatedDecl(); 10667 FunctionTemplateDecl *NewTemplateDecl 10668 = NewFD->getDescribedFunctionTemplate(); 10669 assert(NewTemplateDecl && "Template/non-template mismatch"); 10670 10671 // The call to MergeFunctionDecl above may have created some state in 10672 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we 10673 // can add it as a redeclaration. 10674 NewTemplateDecl->mergePrevDecl(OldTemplateDecl); 10675 10676 NewFD->setPreviousDeclaration(OldFD); 10677 adjustDeclContextForDeclaratorDecl(NewFD, OldFD); 10678 if (NewFD->isCXXClassMember()) { 10679 NewFD->setAccess(OldTemplateDecl->getAccess()); 10680 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 10681 } 10682 10683 // If this is an explicit specialization of a member that is a function 10684 // template, mark it as a member specialization. 10685 if (IsMemberSpecialization && 10686 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 10687 NewTemplateDecl->setMemberSpecialization(); 10688 assert(OldTemplateDecl->isMemberSpecialization()); 10689 // Explicit specializations of a member template do not inherit deleted 10690 // status from the parent member template that they are specializing. 10691 if (OldFD->isDeleted()) { 10692 // FIXME: This assert will not hold in the presence of modules. 10693 assert(OldFD->getCanonicalDecl() == OldFD); 10694 // FIXME: We need an update record for this AST mutation. 10695 OldFD->setDeletedAsWritten(false); 10696 } 10697 } 10698 10699 } else { 10700 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 10701 auto *OldFD = cast<FunctionDecl>(OldDecl); 10702 // This needs to happen first so that 'inline' propagates. 10703 NewFD->setPreviousDeclaration(OldFD); 10704 adjustDeclContextForDeclaratorDecl(NewFD, OldFD); 10705 if (NewFD->isCXXClassMember()) 10706 NewFD->setAccess(OldFD->getAccess()); 10707 } 10708 } 10709 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && 10710 !NewFD->getAttr<OverloadableAttr>()) { 10711 assert((Previous.empty() || 10712 llvm::any_of(Previous, 10713 [](const NamedDecl *ND) { 10714 return ND->hasAttr<OverloadableAttr>(); 10715 })) && 10716 "Non-redecls shouldn't happen without overloadable present"); 10717 10718 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { 10719 const auto *FD = dyn_cast<FunctionDecl>(ND); 10720 return FD && !FD->hasAttr<OverloadableAttr>(); 10721 }); 10722 10723 if (OtherUnmarkedIter != Previous.end()) { 10724 Diag(NewFD->getLocation(), 10725 diag::err_attribute_overloadable_multiple_unmarked_overloads); 10726 Diag((*OtherUnmarkedIter)->getLocation(), 10727 diag::note_attribute_overloadable_prev_overload) 10728 << false; 10729 10730 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 10731 } 10732 } 10733 10734 // Semantic checking for this function declaration (in isolation). 10735 10736 if (getLangOpts().CPlusPlus) { 10737 // C++-specific checks. 10738 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 10739 CheckConstructor(Constructor); 10740 } else if (CXXDestructorDecl *Destructor = 10741 dyn_cast<CXXDestructorDecl>(NewFD)) { 10742 CXXRecordDecl *Record = Destructor->getParent(); 10743 QualType ClassType = Context.getTypeDeclType(Record); 10744 10745 // FIXME: Shouldn't we be able to perform this check even when the class 10746 // type is dependent? Both gcc and edg can handle that. 10747 if (!ClassType->isDependentType()) { 10748 DeclarationName Name 10749 = Context.DeclarationNames.getCXXDestructorName( 10750 Context.getCanonicalType(ClassType)); 10751 if (NewFD->getDeclName() != Name) { 10752 Diag(NewFD->getLocation(), diag::err_destructor_name); 10753 NewFD->setInvalidDecl(); 10754 return Redeclaration; 10755 } 10756 } 10757 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 10758 if (auto *TD = Guide->getDescribedFunctionTemplate()) 10759 CheckDeductionGuideTemplate(TD); 10760 10761 // A deduction guide is not on the list of entities that can be 10762 // explicitly specialized. 10763 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 10764 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized) 10765 << /*explicit specialization*/ 1; 10766 } 10767 10768 // Find any virtual functions that this function overrides. 10769 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 10770 if (!Method->isFunctionTemplateSpecialization() && 10771 !Method->getDescribedFunctionTemplate() && 10772 Method->isCanonicalDecl()) { 10773 AddOverriddenMethods(Method->getParent(), Method); 10774 } 10775 if (Method->isVirtual() && NewFD->getTrailingRequiresClause()) 10776 // C++2a [class.virtual]p6 10777 // A virtual method shall not have a requires-clause. 10778 Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(), 10779 diag::err_constrained_virtual_method); 10780 10781 if (Method->isStatic()) 10782 checkThisInStaticMemberFunctionType(Method); 10783 } 10784 10785 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD)) 10786 ActOnConversionDeclarator(Conversion); 10787 10788 // Extra checking for C++ overloaded operators (C++ [over.oper]). 10789 if (NewFD->isOverloadedOperator() && 10790 CheckOverloadedOperatorDeclaration(NewFD)) { 10791 NewFD->setInvalidDecl(); 10792 return Redeclaration; 10793 } 10794 10795 // Extra checking for C++0x literal operators (C++0x [over.literal]). 10796 if (NewFD->getLiteralIdentifier() && 10797 CheckLiteralOperatorDeclaration(NewFD)) { 10798 NewFD->setInvalidDecl(); 10799 return Redeclaration; 10800 } 10801 10802 // In C++, check default arguments now that we have merged decls. Unless 10803 // the lexical context is the class, because in this case this is done 10804 // during delayed parsing anyway. 10805 if (!CurContext->isRecord()) 10806 CheckCXXDefaultArguments(NewFD); 10807 10808 // If this function declares a builtin function, check the type of this 10809 // declaration against the expected type for the builtin. 10810 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 10811 ASTContext::GetBuiltinTypeError Error; 10812 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 10813 QualType T = Context.GetBuiltinType(BuiltinID, Error); 10814 // If the type of the builtin differs only in its exception 10815 // specification, that's OK. 10816 // FIXME: If the types do differ in this way, it would be better to 10817 // retain the 'noexcept' form of the type. 10818 if (!T.isNull() && 10819 !Context.hasSameFunctionTypeIgnoringExceptionSpec(T, 10820 NewFD->getType())) 10821 // The type of this function differs from the type of the builtin, 10822 // so forget about the builtin entirely. 10823 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); 10824 } 10825 10826 // If this function is declared as being extern "C", then check to see if 10827 // the function returns a UDT (class, struct, or union type) that is not C 10828 // compatible, and if it does, warn the user. 10829 // But, issue any diagnostic on the first declaration only. 10830 if (Previous.empty() && NewFD->isExternC()) { 10831 QualType R = NewFD->getReturnType(); 10832 if (R->isIncompleteType() && !R->isVoidType()) 10833 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 10834 << NewFD << R; 10835 else if (!R.isPODType(Context) && !R->isVoidType() && 10836 !R->isObjCObjectPointerType()) 10837 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 10838 } 10839 10840 // C++1z [dcl.fct]p6: 10841 // [...] whether the function has a non-throwing exception-specification 10842 // [is] part of the function type 10843 // 10844 // This results in an ABI break between C++14 and C++17 for functions whose 10845 // declared type includes an exception-specification in a parameter or 10846 // return type. (Exception specifications on the function itself are OK in 10847 // most cases, and exception specifications are not permitted in most other 10848 // contexts where they could make it into a mangling.) 10849 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { 10850 auto HasNoexcept = [&](QualType T) -> bool { 10851 // Strip off declarator chunks that could be between us and a function 10852 // type. We don't need to look far, exception specifications are very 10853 // restricted prior to C++17. 10854 if (auto *RT = T->getAs<ReferenceType>()) 10855 T = RT->getPointeeType(); 10856 else if (T->isAnyPointerType()) 10857 T = T->getPointeeType(); 10858 else if (auto *MPT = T->getAs<MemberPointerType>()) 10859 T = MPT->getPointeeType(); 10860 if (auto *FPT = T->getAs<FunctionProtoType>()) 10861 if (FPT->isNothrow()) 10862 return true; 10863 return false; 10864 }; 10865 10866 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 10867 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 10868 for (QualType T : FPT->param_types()) 10869 AnyNoexcept |= HasNoexcept(T); 10870 if (AnyNoexcept) 10871 Diag(NewFD->getLocation(), 10872 diag::warn_cxx17_compat_exception_spec_in_signature) 10873 << NewFD; 10874 } 10875 10876 if (!Redeclaration && LangOpts.CUDA) 10877 checkCUDATargetOverload(NewFD, Previous); 10878 } 10879 return Redeclaration; 10880 } 10881 10882 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 10883 // C++11 [basic.start.main]p3: 10884 // A program that [...] declares main to be inline, static or 10885 // constexpr is ill-formed. 10886 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 10887 // appear in a declaration of main. 10888 // static main is not an error under C99, but we should warn about it. 10889 // We accept _Noreturn main as an extension. 10890 if (FD->getStorageClass() == SC_Static) 10891 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 10892 ? diag::err_static_main : diag::warn_static_main) 10893 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 10894 if (FD->isInlineSpecified()) 10895 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 10896 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 10897 if (DS.isNoreturnSpecified()) { 10898 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 10899 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 10900 Diag(NoreturnLoc, diag::ext_noreturn_main); 10901 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 10902 << FixItHint::CreateRemoval(NoreturnRange); 10903 } 10904 if (FD->isConstexpr()) { 10905 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 10906 << FD->isConsteval() 10907 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 10908 FD->setConstexprKind(CSK_unspecified); 10909 } 10910 10911 if (getLangOpts().OpenCL) { 10912 Diag(FD->getLocation(), diag::err_opencl_no_main) 10913 << FD->hasAttr<OpenCLKernelAttr>(); 10914 FD->setInvalidDecl(); 10915 return; 10916 } 10917 10918 QualType T = FD->getType(); 10919 assert(T->isFunctionType() && "function decl is not of function type"); 10920 const FunctionType* FT = T->castAs<FunctionType>(); 10921 10922 // Set default calling convention for main() 10923 if (FT->getCallConv() != CC_C) { 10924 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); 10925 FD->setType(QualType(FT, 0)); 10926 T = Context.getCanonicalType(FD->getType()); 10927 } 10928 10929 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 10930 // In C with GNU extensions we allow main() to have non-integer return 10931 // type, but we should warn about the extension, and we disable the 10932 // implicit-return-zero rule. 10933 10934 // GCC in C mode accepts qualified 'int'. 10935 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 10936 FD->setHasImplicitReturnZero(true); 10937 else { 10938 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 10939 SourceRange RTRange = FD->getReturnTypeSourceRange(); 10940 if (RTRange.isValid()) 10941 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 10942 << FixItHint::CreateReplacement(RTRange, "int"); 10943 } 10944 } else { 10945 // In C and C++, main magically returns 0 if you fall off the end; 10946 // set the flag which tells us that. 10947 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 10948 10949 // All the standards say that main() should return 'int'. 10950 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 10951 FD->setHasImplicitReturnZero(true); 10952 else { 10953 // Otherwise, this is just a flat-out error. 10954 SourceRange RTRange = FD->getReturnTypeSourceRange(); 10955 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 10956 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 10957 : FixItHint()); 10958 FD->setInvalidDecl(true); 10959 } 10960 } 10961 10962 // Treat protoless main() as nullary. 10963 if (isa<FunctionNoProtoType>(FT)) return; 10964 10965 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 10966 unsigned nparams = FTP->getNumParams(); 10967 assert(FD->getNumParams() == nparams); 10968 10969 bool HasExtraParameters = (nparams > 3); 10970 10971 if (FTP->isVariadic()) { 10972 Diag(FD->getLocation(), diag::ext_variadic_main); 10973 // FIXME: if we had information about the location of the ellipsis, we 10974 // could add a FixIt hint to remove it as a parameter. 10975 } 10976 10977 // Darwin passes an undocumented fourth argument of type char**. If 10978 // other platforms start sprouting these, the logic below will start 10979 // getting shifty. 10980 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 10981 HasExtraParameters = false; 10982 10983 if (HasExtraParameters) { 10984 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 10985 FD->setInvalidDecl(true); 10986 nparams = 3; 10987 } 10988 10989 // FIXME: a lot of the following diagnostics would be improved 10990 // if we had some location information about types. 10991 10992 QualType CharPP = 10993 Context.getPointerType(Context.getPointerType(Context.CharTy)); 10994 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 10995 10996 for (unsigned i = 0; i < nparams; ++i) { 10997 QualType AT = FTP->getParamType(i); 10998 10999 bool mismatch = true; 11000 11001 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 11002 mismatch = false; 11003 else if (Expected[i] == CharPP) { 11004 // As an extension, the following forms are okay: 11005 // char const ** 11006 // char const * const * 11007 // char * const * 11008 11009 QualifierCollector qs; 11010 const PointerType* PT; 11011 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 11012 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 11013 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 11014 Context.CharTy)) { 11015 qs.removeConst(); 11016 mismatch = !qs.empty(); 11017 } 11018 } 11019 11020 if (mismatch) { 11021 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 11022 // TODO: suggest replacing given type with expected type 11023 FD->setInvalidDecl(true); 11024 } 11025 } 11026 11027 if (nparams == 1 && !FD->isInvalidDecl()) { 11028 Diag(FD->getLocation(), diag::warn_main_one_arg); 11029 } 11030 11031 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11032 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11033 FD->setInvalidDecl(); 11034 } 11035 } 11036 11037 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 11038 QualType T = FD->getType(); 11039 assert(T->isFunctionType() && "function decl is not of function type"); 11040 const FunctionType *FT = T->castAs<FunctionType>(); 11041 11042 // Set an implicit return of 'zero' if the function can return some integral, 11043 // enumeration, pointer or nullptr type. 11044 if (FT->getReturnType()->isIntegralOrEnumerationType() || 11045 FT->getReturnType()->isAnyPointerType() || 11046 FT->getReturnType()->isNullPtrType()) 11047 // DllMain is exempt because a return value of zero means it failed. 11048 if (FD->getName() != "DllMain") 11049 FD->setHasImplicitReturnZero(true); 11050 11051 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11052 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11053 FD->setInvalidDecl(); 11054 } 11055 } 11056 11057 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 11058 // FIXME: Need strict checking. In C89, we need to check for 11059 // any assignment, increment, decrement, function-calls, or 11060 // commas outside of a sizeof. In C99, it's the same list, 11061 // except that the aforementioned are allowed in unevaluated 11062 // expressions. Everything else falls under the 11063 // "may accept other forms of constant expressions" exception. 11064 // (We never end up here for C++, so the constant expression 11065 // rules there don't matter.) 11066 const Expr *Culprit; 11067 if (Init->isConstantInitializer(Context, false, &Culprit)) 11068 return false; 11069 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 11070 << Culprit->getSourceRange(); 11071 return true; 11072 } 11073 11074 namespace { 11075 // Visits an initialization expression to see if OrigDecl is evaluated in 11076 // its own initialization and throws a warning if it does. 11077 class SelfReferenceChecker 11078 : public EvaluatedExprVisitor<SelfReferenceChecker> { 11079 Sema &S; 11080 Decl *OrigDecl; 11081 bool isRecordType; 11082 bool isPODType; 11083 bool isReferenceType; 11084 11085 bool isInitList; 11086 llvm::SmallVector<unsigned, 4> InitFieldIndex; 11087 11088 public: 11089 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 11090 11091 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 11092 S(S), OrigDecl(OrigDecl) { 11093 isPODType = false; 11094 isRecordType = false; 11095 isReferenceType = false; 11096 isInitList = false; 11097 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 11098 isPODType = VD->getType().isPODType(S.Context); 11099 isRecordType = VD->getType()->isRecordType(); 11100 isReferenceType = VD->getType()->isReferenceType(); 11101 } 11102 } 11103 11104 // For most expressions, just call the visitor. For initializer lists, 11105 // track the index of the field being initialized since fields are 11106 // initialized in order allowing use of previously initialized fields. 11107 void CheckExpr(Expr *E) { 11108 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 11109 if (!InitList) { 11110 Visit(E); 11111 return; 11112 } 11113 11114 // Track and increment the index here. 11115 isInitList = true; 11116 InitFieldIndex.push_back(0); 11117 for (auto Child : InitList->children()) { 11118 CheckExpr(cast<Expr>(Child)); 11119 ++InitFieldIndex.back(); 11120 } 11121 InitFieldIndex.pop_back(); 11122 } 11123 11124 // Returns true if MemberExpr is checked and no further checking is needed. 11125 // Returns false if additional checking is required. 11126 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 11127 llvm::SmallVector<FieldDecl*, 4> Fields; 11128 Expr *Base = E; 11129 bool ReferenceField = false; 11130 11131 // Get the field members used. 11132 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11133 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 11134 if (!FD) 11135 return false; 11136 Fields.push_back(FD); 11137 if (FD->getType()->isReferenceType()) 11138 ReferenceField = true; 11139 Base = ME->getBase()->IgnoreParenImpCasts(); 11140 } 11141 11142 // Keep checking only if the base Decl is the same. 11143 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 11144 if (!DRE || DRE->getDecl() != OrigDecl) 11145 return false; 11146 11147 // A reference field can be bound to an unininitialized field. 11148 if (CheckReference && !ReferenceField) 11149 return true; 11150 11151 // Convert FieldDecls to their index number. 11152 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 11153 for (const FieldDecl *I : llvm::reverse(Fields)) 11154 UsedFieldIndex.push_back(I->getFieldIndex()); 11155 11156 // See if a warning is needed by checking the first difference in index 11157 // numbers. If field being used has index less than the field being 11158 // initialized, then the use is safe. 11159 for (auto UsedIter = UsedFieldIndex.begin(), 11160 UsedEnd = UsedFieldIndex.end(), 11161 OrigIter = InitFieldIndex.begin(), 11162 OrigEnd = InitFieldIndex.end(); 11163 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 11164 if (*UsedIter < *OrigIter) 11165 return true; 11166 if (*UsedIter > *OrigIter) 11167 break; 11168 } 11169 11170 // TODO: Add a different warning which will print the field names. 11171 HandleDeclRefExpr(DRE); 11172 return true; 11173 } 11174 11175 // For most expressions, the cast is directly above the DeclRefExpr. 11176 // For conditional operators, the cast can be outside the conditional 11177 // operator if both expressions are DeclRefExpr's. 11178 void HandleValue(Expr *E) { 11179 E = E->IgnoreParens(); 11180 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 11181 HandleDeclRefExpr(DRE); 11182 return; 11183 } 11184 11185 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 11186 Visit(CO->getCond()); 11187 HandleValue(CO->getTrueExpr()); 11188 HandleValue(CO->getFalseExpr()); 11189 return; 11190 } 11191 11192 if (BinaryConditionalOperator *BCO = 11193 dyn_cast<BinaryConditionalOperator>(E)) { 11194 Visit(BCO->getCond()); 11195 HandleValue(BCO->getFalseExpr()); 11196 return; 11197 } 11198 11199 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 11200 HandleValue(OVE->getSourceExpr()); 11201 return; 11202 } 11203 11204 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11205 if (BO->getOpcode() == BO_Comma) { 11206 Visit(BO->getLHS()); 11207 HandleValue(BO->getRHS()); 11208 return; 11209 } 11210 } 11211 11212 if (isa<MemberExpr>(E)) { 11213 if (isInitList) { 11214 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 11215 false /*CheckReference*/)) 11216 return; 11217 } 11218 11219 Expr *Base = E->IgnoreParenImpCasts(); 11220 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11221 // Check for static member variables and don't warn on them. 11222 if (!isa<FieldDecl>(ME->getMemberDecl())) 11223 return; 11224 Base = ME->getBase()->IgnoreParenImpCasts(); 11225 } 11226 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 11227 HandleDeclRefExpr(DRE); 11228 return; 11229 } 11230 11231 Visit(E); 11232 } 11233 11234 // Reference types not handled in HandleValue are handled here since all 11235 // uses of references are bad, not just r-value uses. 11236 void VisitDeclRefExpr(DeclRefExpr *E) { 11237 if (isReferenceType) 11238 HandleDeclRefExpr(E); 11239 } 11240 11241 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 11242 if (E->getCastKind() == CK_LValueToRValue) { 11243 HandleValue(E->getSubExpr()); 11244 return; 11245 } 11246 11247 Inherited::VisitImplicitCastExpr(E); 11248 } 11249 11250 void VisitMemberExpr(MemberExpr *E) { 11251 if (isInitList) { 11252 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 11253 return; 11254 } 11255 11256 // Don't warn on arrays since they can be treated as pointers. 11257 if (E->getType()->canDecayToPointerType()) return; 11258 11259 // Warn when a non-static method call is followed by non-static member 11260 // field accesses, which is followed by a DeclRefExpr. 11261 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 11262 bool Warn = (MD && !MD->isStatic()); 11263 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 11264 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11265 if (!isa<FieldDecl>(ME->getMemberDecl())) 11266 Warn = false; 11267 Base = ME->getBase()->IgnoreParenImpCasts(); 11268 } 11269 11270 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 11271 if (Warn) 11272 HandleDeclRefExpr(DRE); 11273 return; 11274 } 11275 11276 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 11277 // Visit that expression. 11278 Visit(Base); 11279 } 11280 11281 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 11282 Expr *Callee = E->getCallee(); 11283 11284 if (isa<UnresolvedLookupExpr>(Callee)) 11285 return Inherited::VisitCXXOperatorCallExpr(E); 11286 11287 Visit(Callee); 11288 for (auto Arg: E->arguments()) 11289 HandleValue(Arg->IgnoreParenImpCasts()); 11290 } 11291 11292 void VisitUnaryOperator(UnaryOperator *E) { 11293 // For POD record types, addresses of its own members are well-defined. 11294 if (E->getOpcode() == UO_AddrOf && isRecordType && 11295 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 11296 if (!isPODType) 11297 HandleValue(E->getSubExpr()); 11298 return; 11299 } 11300 11301 if (E->isIncrementDecrementOp()) { 11302 HandleValue(E->getSubExpr()); 11303 return; 11304 } 11305 11306 Inherited::VisitUnaryOperator(E); 11307 } 11308 11309 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 11310 11311 void VisitCXXConstructExpr(CXXConstructExpr *E) { 11312 if (E->getConstructor()->isCopyConstructor()) { 11313 Expr *ArgExpr = E->getArg(0); 11314 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 11315 if (ILE->getNumInits() == 1) 11316 ArgExpr = ILE->getInit(0); 11317 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 11318 if (ICE->getCastKind() == CK_NoOp) 11319 ArgExpr = ICE->getSubExpr(); 11320 HandleValue(ArgExpr); 11321 return; 11322 } 11323 Inherited::VisitCXXConstructExpr(E); 11324 } 11325 11326 void VisitCallExpr(CallExpr *E) { 11327 // Treat std::move as a use. 11328 if (E->isCallToStdMove()) { 11329 HandleValue(E->getArg(0)); 11330 return; 11331 } 11332 11333 Inherited::VisitCallExpr(E); 11334 } 11335 11336 void VisitBinaryOperator(BinaryOperator *E) { 11337 if (E->isCompoundAssignmentOp()) { 11338 HandleValue(E->getLHS()); 11339 Visit(E->getRHS()); 11340 return; 11341 } 11342 11343 Inherited::VisitBinaryOperator(E); 11344 } 11345 11346 // A custom visitor for BinaryConditionalOperator is needed because the 11347 // regular visitor would check the condition and true expression separately 11348 // but both point to the same place giving duplicate diagnostics. 11349 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 11350 Visit(E->getCond()); 11351 Visit(E->getFalseExpr()); 11352 } 11353 11354 void HandleDeclRefExpr(DeclRefExpr *DRE) { 11355 Decl* ReferenceDecl = DRE->getDecl(); 11356 if (OrigDecl != ReferenceDecl) return; 11357 unsigned diag; 11358 if (isReferenceType) { 11359 diag = diag::warn_uninit_self_reference_in_reference_init; 11360 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 11361 diag = diag::warn_static_self_reference_in_init; 11362 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 11363 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 11364 DRE->getDecl()->getType()->isRecordType()) { 11365 diag = diag::warn_uninit_self_reference_in_init; 11366 } else { 11367 // Local variables will be handled by the CFG analysis. 11368 return; 11369 } 11370 11371 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE, 11372 S.PDiag(diag) 11373 << DRE->getDecl() << OrigDecl->getLocation() 11374 << DRE->getSourceRange()); 11375 } 11376 }; 11377 11378 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 11379 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 11380 bool DirectInit) { 11381 // Parameters arguments are occassionially constructed with itself, 11382 // for instance, in recursive functions. Skip them. 11383 if (isa<ParmVarDecl>(OrigDecl)) 11384 return; 11385 11386 E = E->IgnoreParens(); 11387 11388 // Skip checking T a = a where T is not a record or reference type. 11389 // Doing so is a way to silence uninitialized warnings. 11390 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 11391 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 11392 if (ICE->getCastKind() == CK_LValueToRValue) 11393 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 11394 if (DRE->getDecl() == OrigDecl) 11395 return; 11396 11397 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 11398 } 11399 } // end anonymous namespace 11400 11401 namespace { 11402 // Simple wrapper to add the name of a variable or (if no variable is 11403 // available) a DeclarationName into a diagnostic. 11404 struct VarDeclOrName { 11405 VarDecl *VDecl; 11406 DeclarationName Name; 11407 11408 friend const Sema::SemaDiagnosticBuilder & 11409 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 11410 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 11411 } 11412 }; 11413 } // end anonymous namespace 11414 11415 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 11416 DeclarationName Name, QualType Type, 11417 TypeSourceInfo *TSI, 11418 SourceRange Range, bool DirectInit, 11419 Expr *Init) { 11420 bool IsInitCapture = !VDecl; 11421 assert((!VDecl || !VDecl->isInitCapture()) && 11422 "init captures are expected to be deduced prior to initialization"); 11423 11424 VarDeclOrName VN{VDecl, Name}; 11425 11426 DeducedType *Deduced = Type->getContainedDeducedType(); 11427 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 11428 11429 // C++11 [dcl.spec.auto]p3 11430 if (!Init) { 11431 assert(VDecl && "no init for init capture deduction?"); 11432 11433 // Except for class argument deduction, and then for an initializing 11434 // declaration only, i.e. no static at class scope or extern. 11435 if (!isa<DeducedTemplateSpecializationType>(Deduced) || 11436 VDecl->hasExternalStorage() || 11437 VDecl->isStaticDataMember()) { 11438 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 11439 << VDecl->getDeclName() << Type; 11440 return QualType(); 11441 } 11442 } 11443 11444 ArrayRef<Expr*> DeduceInits; 11445 if (Init) 11446 DeduceInits = Init; 11447 11448 if (DirectInit) { 11449 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) 11450 DeduceInits = PL->exprs(); 11451 } 11452 11453 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 11454 assert(VDecl && "non-auto type for init capture deduction?"); 11455 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 11456 InitializationKind Kind = InitializationKind::CreateForInit( 11457 VDecl->getLocation(), DirectInit, Init); 11458 // FIXME: Initialization should not be taking a mutable list of inits. 11459 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 11460 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 11461 InitsCopy); 11462 } 11463 11464 if (DirectInit) { 11465 if (auto *IL = dyn_cast<InitListExpr>(Init)) 11466 DeduceInits = IL->inits(); 11467 } 11468 11469 // Deduction only works if we have exactly one source expression. 11470 if (DeduceInits.empty()) { 11471 // It isn't possible to write this directly, but it is possible to 11472 // end up in this situation with "auto x(some_pack...);" 11473 Diag(Init->getBeginLoc(), IsInitCapture 11474 ? diag::err_init_capture_no_expression 11475 : diag::err_auto_var_init_no_expression) 11476 << VN << Type << Range; 11477 return QualType(); 11478 } 11479 11480 if (DeduceInits.size() > 1) { 11481 Diag(DeduceInits[1]->getBeginLoc(), 11482 IsInitCapture ? diag::err_init_capture_multiple_expressions 11483 : diag::err_auto_var_init_multiple_expressions) 11484 << VN << Type << Range; 11485 return QualType(); 11486 } 11487 11488 Expr *DeduceInit = DeduceInits[0]; 11489 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 11490 Diag(Init->getBeginLoc(), IsInitCapture 11491 ? diag::err_init_capture_paren_braces 11492 : diag::err_auto_var_init_paren_braces) 11493 << isa<InitListExpr>(Init) << VN << Type << Range; 11494 return QualType(); 11495 } 11496 11497 // Expressions default to 'id' when we're in a debugger. 11498 bool DefaultedAnyToId = false; 11499 if (getLangOpts().DebuggerCastResultToId && 11500 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 11501 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 11502 if (Result.isInvalid()) { 11503 return QualType(); 11504 } 11505 Init = Result.get(); 11506 DefaultedAnyToId = true; 11507 } 11508 11509 // C++ [dcl.decomp]p1: 11510 // If the assignment-expression [...] has array type A and no ref-qualifier 11511 // is present, e has type cv A 11512 if (VDecl && isa<DecompositionDecl>(VDecl) && 11513 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 11514 DeduceInit->getType()->isConstantArrayType()) 11515 return Context.getQualifiedType(DeduceInit->getType(), 11516 Type.getQualifiers()); 11517 11518 QualType DeducedType; 11519 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 11520 if (!IsInitCapture) 11521 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 11522 else if (isa<InitListExpr>(Init)) 11523 Diag(Range.getBegin(), 11524 diag::err_init_capture_deduction_failure_from_init_list) 11525 << VN 11526 << (DeduceInit->getType().isNull() ? TSI->getType() 11527 : DeduceInit->getType()) 11528 << DeduceInit->getSourceRange(); 11529 else 11530 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 11531 << VN << TSI->getType() 11532 << (DeduceInit->getType().isNull() ? TSI->getType() 11533 : DeduceInit->getType()) 11534 << DeduceInit->getSourceRange(); 11535 } 11536 11537 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 11538 // 'id' instead of a specific object type prevents most of our usual 11539 // checks. 11540 // We only want to warn outside of template instantiations, though: 11541 // inside a template, the 'id' could have come from a parameter. 11542 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 11543 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 11544 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 11545 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 11546 } 11547 11548 return DeducedType; 11549 } 11550 11551 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 11552 Expr *Init) { 11553 assert(!Init || !Init->containsErrors()); 11554 QualType DeducedType = deduceVarTypeFromInitializer( 11555 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 11556 VDecl->getSourceRange(), DirectInit, Init); 11557 if (DeducedType.isNull()) { 11558 VDecl->setInvalidDecl(); 11559 return true; 11560 } 11561 11562 VDecl->setType(DeducedType); 11563 assert(VDecl->isLinkageValid()); 11564 11565 // In ARC, infer lifetime. 11566 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 11567 VDecl->setInvalidDecl(); 11568 11569 if (getLangOpts().OpenCL) 11570 deduceOpenCLAddressSpace(VDecl); 11571 11572 // If this is a redeclaration, check that the type we just deduced matches 11573 // the previously declared type. 11574 if (VarDecl *Old = VDecl->getPreviousDecl()) { 11575 // We never need to merge the type, because we cannot form an incomplete 11576 // array of auto, nor deduce such a type. 11577 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 11578 } 11579 11580 // Check the deduced type is valid for a variable declaration. 11581 CheckVariableDeclarationType(VDecl); 11582 return VDecl->isInvalidDecl(); 11583 } 11584 11585 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init, 11586 SourceLocation Loc) { 11587 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init)) 11588 Init = EWC->getSubExpr(); 11589 11590 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 11591 Init = CE->getSubExpr(); 11592 11593 QualType InitType = Init->getType(); 11594 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 11595 InitType.hasNonTrivialToPrimitiveCopyCUnion()) && 11596 "shouldn't be called if type doesn't have a non-trivial C struct"); 11597 if (auto *ILE = dyn_cast<InitListExpr>(Init)) { 11598 for (auto I : ILE->inits()) { 11599 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() && 11600 !I->getType().hasNonTrivialToPrimitiveCopyCUnion()) 11601 continue; 11602 SourceLocation SL = I->getExprLoc(); 11603 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc); 11604 } 11605 return; 11606 } 11607 11608 if (isa<ImplicitValueInitExpr>(Init)) { 11609 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 11610 checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject, 11611 NTCUK_Init); 11612 } else { 11613 // Assume all other explicit initializers involving copying some existing 11614 // object. 11615 // TODO: ignore any explicit initializers where we can guarantee 11616 // copy-elision. 11617 if (InitType.hasNonTrivialToPrimitiveCopyCUnion()) 11618 checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy); 11619 } 11620 } 11621 11622 namespace { 11623 11624 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) { 11625 // Ignore unavailable fields. A field can be marked as unavailable explicitly 11626 // in the source code or implicitly by the compiler if it is in a union 11627 // defined in a system header and has non-trivial ObjC ownership 11628 // qualifications. We don't want those fields to participate in determining 11629 // whether the containing union is non-trivial. 11630 return FD->hasAttr<UnavailableAttr>(); 11631 } 11632 11633 struct DiagNonTrivalCUnionDefaultInitializeVisitor 11634 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 11635 void> { 11636 using Super = 11637 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 11638 void>; 11639 11640 DiagNonTrivalCUnionDefaultInitializeVisitor( 11641 QualType OrigTy, SourceLocation OrigLoc, 11642 Sema::NonTrivialCUnionContext UseContext, Sema &S) 11643 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11644 11645 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT, 11646 const FieldDecl *FD, bool InNonTrivialUnion) { 11647 if (const auto *AT = S.Context.getAsArrayType(QT)) 11648 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11649 InNonTrivialUnion); 11650 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion); 11651 } 11652 11653 void visitARCStrong(QualType QT, const FieldDecl *FD, 11654 bool InNonTrivialUnion) { 11655 if (InNonTrivialUnion) 11656 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11657 << 1 << 0 << QT << FD->getName(); 11658 } 11659 11660 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11661 if (InNonTrivialUnion) 11662 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11663 << 1 << 0 << QT << FD->getName(); 11664 } 11665 11666 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11667 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11668 if (RD->isUnion()) { 11669 if (OrigLoc.isValid()) { 11670 bool IsUnion = false; 11671 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11672 IsUnion = OrigRD->isUnion(); 11673 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11674 << 0 << OrigTy << IsUnion << UseContext; 11675 // Reset OrigLoc so that this diagnostic is emitted only once. 11676 OrigLoc = SourceLocation(); 11677 } 11678 InNonTrivialUnion = true; 11679 } 11680 11681 if (InNonTrivialUnion) 11682 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11683 << 0 << 0 << QT.getUnqualifiedType() << ""; 11684 11685 for (const FieldDecl *FD : RD->fields()) 11686 if (!shouldIgnoreForRecordTriviality(FD)) 11687 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11688 } 11689 11690 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11691 11692 // The non-trivial C union type or the struct/union type that contains a 11693 // non-trivial C union. 11694 QualType OrigTy; 11695 SourceLocation OrigLoc; 11696 Sema::NonTrivialCUnionContext UseContext; 11697 Sema &S; 11698 }; 11699 11700 struct DiagNonTrivalCUnionDestructedTypeVisitor 11701 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> { 11702 using Super = 11703 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>; 11704 11705 DiagNonTrivalCUnionDestructedTypeVisitor( 11706 QualType OrigTy, SourceLocation OrigLoc, 11707 Sema::NonTrivialCUnionContext UseContext, Sema &S) 11708 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11709 11710 void visitWithKind(QualType::DestructionKind DK, QualType QT, 11711 const FieldDecl *FD, bool InNonTrivialUnion) { 11712 if (const auto *AT = S.Context.getAsArrayType(QT)) 11713 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11714 InNonTrivialUnion); 11715 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion); 11716 } 11717 11718 void visitARCStrong(QualType QT, const FieldDecl *FD, 11719 bool InNonTrivialUnion) { 11720 if (InNonTrivialUnion) 11721 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11722 << 1 << 1 << QT << FD->getName(); 11723 } 11724 11725 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11726 if (InNonTrivialUnion) 11727 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11728 << 1 << 1 << QT << FD->getName(); 11729 } 11730 11731 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11732 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11733 if (RD->isUnion()) { 11734 if (OrigLoc.isValid()) { 11735 bool IsUnion = false; 11736 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11737 IsUnion = OrigRD->isUnion(); 11738 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11739 << 1 << OrigTy << IsUnion << UseContext; 11740 // Reset OrigLoc so that this diagnostic is emitted only once. 11741 OrigLoc = SourceLocation(); 11742 } 11743 InNonTrivialUnion = true; 11744 } 11745 11746 if (InNonTrivialUnion) 11747 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11748 << 0 << 1 << QT.getUnqualifiedType() << ""; 11749 11750 for (const FieldDecl *FD : RD->fields()) 11751 if (!shouldIgnoreForRecordTriviality(FD)) 11752 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11753 } 11754 11755 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11756 void visitCXXDestructor(QualType QT, const FieldDecl *FD, 11757 bool InNonTrivialUnion) {} 11758 11759 // The non-trivial C union type or the struct/union type that contains a 11760 // non-trivial C union. 11761 QualType OrigTy; 11762 SourceLocation OrigLoc; 11763 Sema::NonTrivialCUnionContext UseContext; 11764 Sema &S; 11765 }; 11766 11767 struct DiagNonTrivalCUnionCopyVisitor 11768 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> { 11769 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>; 11770 11771 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc, 11772 Sema::NonTrivialCUnionContext UseContext, 11773 Sema &S) 11774 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11775 11776 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT, 11777 const FieldDecl *FD, bool InNonTrivialUnion) { 11778 if (const auto *AT = S.Context.getAsArrayType(QT)) 11779 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11780 InNonTrivialUnion); 11781 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion); 11782 } 11783 11784 void visitARCStrong(QualType QT, const FieldDecl *FD, 11785 bool InNonTrivialUnion) { 11786 if (InNonTrivialUnion) 11787 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11788 << 1 << 2 << QT << FD->getName(); 11789 } 11790 11791 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11792 if (InNonTrivialUnion) 11793 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11794 << 1 << 2 << QT << FD->getName(); 11795 } 11796 11797 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11798 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11799 if (RD->isUnion()) { 11800 if (OrigLoc.isValid()) { 11801 bool IsUnion = false; 11802 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11803 IsUnion = OrigRD->isUnion(); 11804 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11805 << 2 << OrigTy << IsUnion << UseContext; 11806 // Reset OrigLoc so that this diagnostic is emitted only once. 11807 OrigLoc = SourceLocation(); 11808 } 11809 InNonTrivialUnion = true; 11810 } 11811 11812 if (InNonTrivialUnion) 11813 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11814 << 0 << 2 << QT.getUnqualifiedType() << ""; 11815 11816 for (const FieldDecl *FD : RD->fields()) 11817 if (!shouldIgnoreForRecordTriviality(FD)) 11818 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11819 } 11820 11821 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT, 11822 const FieldDecl *FD, bool InNonTrivialUnion) {} 11823 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11824 void visitVolatileTrivial(QualType QT, const FieldDecl *FD, 11825 bool InNonTrivialUnion) {} 11826 11827 // The non-trivial C union type or the struct/union type that contains a 11828 // non-trivial C union. 11829 QualType OrigTy; 11830 SourceLocation OrigLoc; 11831 Sema::NonTrivialCUnionContext UseContext; 11832 Sema &S; 11833 }; 11834 11835 } // namespace 11836 11837 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc, 11838 NonTrivialCUnionContext UseContext, 11839 unsigned NonTrivialKind) { 11840 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 11841 QT.hasNonTrivialToPrimitiveDestructCUnion() || 11842 QT.hasNonTrivialToPrimitiveCopyCUnion()) && 11843 "shouldn't be called if type doesn't have a non-trivial C union"); 11844 11845 if ((NonTrivialKind & NTCUK_Init) && 11846 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 11847 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this) 11848 .visit(QT, nullptr, false); 11849 if ((NonTrivialKind & NTCUK_Destruct) && 11850 QT.hasNonTrivialToPrimitiveDestructCUnion()) 11851 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this) 11852 .visit(QT, nullptr, false); 11853 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion()) 11854 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this) 11855 .visit(QT, nullptr, false); 11856 } 11857 11858 /// AddInitializerToDecl - Adds the initializer Init to the 11859 /// declaration dcl. If DirectInit is true, this is C++ direct 11860 /// initialization rather than copy initialization. 11861 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 11862 // If there is no declaration, there was an error parsing it. Just ignore 11863 // the initializer. 11864 if (!RealDecl || RealDecl->isInvalidDecl()) { 11865 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 11866 return; 11867 } 11868 11869 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 11870 // Pure-specifiers are handled in ActOnPureSpecifier. 11871 Diag(Method->getLocation(), diag::err_member_function_initialization) 11872 << Method->getDeclName() << Init->getSourceRange(); 11873 Method->setInvalidDecl(); 11874 return; 11875 } 11876 11877 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 11878 if (!VDecl) { 11879 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 11880 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 11881 RealDecl->setInvalidDecl(); 11882 return; 11883 } 11884 11885 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 11886 if (VDecl->getType()->isUndeducedType()) { 11887 // Attempt typo correction early so that the type of the init expression can 11888 // be deduced based on the chosen correction if the original init contains a 11889 // TypoExpr. 11890 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 11891 if (!Res.isUsable()) { 11892 // There are unresolved typos in Init, just drop them. 11893 // FIXME: improve the recovery strategy to preserve the Init. 11894 RealDecl->setInvalidDecl(); 11895 return; 11896 } 11897 if (Res.get()->containsErrors()) { 11898 // Invalidate the decl as we don't know the type for recovery-expr yet. 11899 RealDecl->setInvalidDecl(); 11900 VDecl->setInit(Res.get()); 11901 return; 11902 } 11903 Init = Res.get(); 11904 11905 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 11906 return; 11907 } 11908 11909 // dllimport cannot be used on variable definitions. 11910 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 11911 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 11912 VDecl->setInvalidDecl(); 11913 return; 11914 } 11915 11916 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 11917 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 11918 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 11919 VDecl->setInvalidDecl(); 11920 return; 11921 } 11922 11923 if (!VDecl->getType()->isDependentType()) { 11924 // A definition must end up with a complete type, which means it must be 11925 // complete with the restriction that an array type might be completed by 11926 // the initializer; note that later code assumes this restriction. 11927 QualType BaseDeclType = VDecl->getType(); 11928 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 11929 BaseDeclType = Array->getElementType(); 11930 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 11931 diag::err_typecheck_decl_incomplete_type)) { 11932 RealDecl->setInvalidDecl(); 11933 return; 11934 } 11935 11936 // The variable can not have an abstract class type. 11937 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 11938 diag::err_abstract_type_in_decl, 11939 AbstractVariableType)) 11940 VDecl->setInvalidDecl(); 11941 } 11942 11943 // If adding the initializer will turn this declaration into a definition, 11944 // and we already have a definition for this variable, diagnose or otherwise 11945 // handle the situation. 11946 VarDecl *Def; 11947 if ((Def = VDecl->getDefinition()) && Def != VDecl && 11948 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 11949 !VDecl->isThisDeclarationADemotedDefinition() && 11950 checkVarDeclRedefinition(Def, VDecl)) 11951 return; 11952 11953 if (getLangOpts().CPlusPlus) { 11954 // C++ [class.static.data]p4 11955 // If a static data member is of const integral or const 11956 // enumeration type, its declaration in the class definition can 11957 // specify a constant-initializer which shall be an integral 11958 // constant expression (5.19). In that case, the member can appear 11959 // in integral constant expressions. The member shall still be 11960 // defined in a namespace scope if it is used in the program and the 11961 // namespace scope definition shall not contain an initializer. 11962 // 11963 // We already performed a redefinition check above, but for static 11964 // data members we also need to check whether there was an in-class 11965 // declaration with an initializer. 11966 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 11967 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 11968 << VDecl->getDeclName(); 11969 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 11970 diag::note_previous_initializer) 11971 << 0; 11972 return; 11973 } 11974 11975 if (VDecl->hasLocalStorage()) 11976 setFunctionHasBranchProtectedScope(); 11977 11978 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 11979 VDecl->setInvalidDecl(); 11980 return; 11981 } 11982 } 11983 11984 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 11985 // a kernel function cannot be initialized." 11986 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 11987 Diag(VDecl->getLocation(), diag::err_local_cant_init); 11988 VDecl->setInvalidDecl(); 11989 return; 11990 } 11991 11992 // The LoaderUninitialized attribute acts as a definition (of undef). 11993 if (VDecl->hasAttr<LoaderUninitializedAttr>()) { 11994 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init); 11995 VDecl->setInvalidDecl(); 11996 return; 11997 } 11998 11999 // Get the decls type and save a reference for later, since 12000 // CheckInitializerTypes may change it. 12001 QualType DclT = VDecl->getType(), SavT = DclT; 12002 12003 // Expressions default to 'id' when we're in a debugger 12004 // and we are assigning it to a variable of Objective-C pointer type. 12005 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 12006 Init->getType() == Context.UnknownAnyTy) { 12007 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 12008 if (Result.isInvalid()) { 12009 VDecl->setInvalidDecl(); 12010 return; 12011 } 12012 Init = Result.get(); 12013 } 12014 12015 // Perform the initialization. 12016 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 12017 if (!VDecl->isInvalidDecl()) { 12018 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 12019 InitializationKind Kind = InitializationKind::CreateForInit( 12020 VDecl->getLocation(), DirectInit, Init); 12021 12022 MultiExprArg Args = Init; 12023 if (CXXDirectInit) 12024 Args = MultiExprArg(CXXDirectInit->getExprs(), 12025 CXXDirectInit->getNumExprs()); 12026 12027 // Try to correct any TypoExprs in the initialization arguments. 12028 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 12029 ExprResult Res = CorrectDelayedTyposInExpr( 12030 Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/false, 12031 [this, Entity, Kind](Expr *E) { 12032 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 12033 return Init.Failed() ? ExprError() : E; 12034 }); 12035 if (Res.isInvalid()) { 12036 VDecl->setInvalidDecl(); 12037 } else if (Res.get() != Args[Idx]) { 12038 Args[Idx] = Res.get(); 12039 } 12040 } 12041 if (VDecl->isInvalidDecl()) 12042 return; 12043 12044 InitializationSequence InitSeq(*this, Entity, Kind, Args, 12045 /*TopLevelOfInitList=*/false, 12046 /*TreatUnavailableAsInvalid=*/false); 12047 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 12048 if (Result.isInvalid()) { 12049 // If the provied initializer fails to initialize the var decl, 12050 // we attach a recovery expr for better recovery. 12051 auto RecoveryExpr = 12052 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args); 12053 if (RecoveryExpr.get()) 12054 VDecl->setInit(RecoveryExpr.get()); 12055 return; 12056 } 12057 12058 Init = Result.getAs<Expr>(); 12059 } 12060 12061 // Check for self-references within variable initializers. 12062 // Variables declared within a function/method body (except for references) 12063 // are handled by a dataflow analysis. 12064 // This is undefined behavior in C++, but valid in C. 12065 if (getLangOpts().CPlusPlus) { 12066 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 12067 VDecl->getType()->isReferenceType()) { 12068 CheckSelfReference(*this, RealDecl, Init, DirectInit); 12069 } 12070 } 12071 12072 // If the type changed, it means we had an incomplete type that was 12073 // completed by the initializer. For example: 12074 // int ary[] = { 1, 3, 5 }; 12075 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 12076 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 12077 VDecl->setType(DclT); 12078 12079 if (!VDecl->isInvalidDecl()) { 12080 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 12081 12082 if (VDecl->hasAttr<BlocksAttr>()) 12083 checkRetainCycles(VDecl, Init); 12084 12085 // It is safe to assign a weak reference into a strong variable. 12086 // Although this code can still have problems: 12087 // id x = self.weakProp; 12088 // id y = self.weakProp; 12089 // we do not warn to warn spuriously when 'x' and 'y' are on separate 12090 // paths through the function. This should be revisited if 12091 // -Wrepeated-use-of-weak is made flow-sensitive. 12092 if (FunctionScopeInfo *FSI = getCurFunction()) 12093 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 12094 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 12095 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 12096 Init->getBeginLoc())) 12097 FSI->markSafeWeakUse(Init); 12098 } 12099 12100 // The initialization is usually a full-expression. 12101 // 12102 // FIXME: If this is a braced initialization of an aggregate, it is not 12103 // an expression, and each individual field initializer is a separate 12104 // full-expression. For instance, in: 12105 // 12106 // struct Temp { ~Temp(); }; 12107 // struct S { S(Temp); }; 12108 // struct T { S a, b; } t = { Temp(), Temp() } 12109 // 12110 // we should destroy the first Temp before constructing the second. 12111 ExprResult Result = 12112 ActOnFinishFullExpr(Init, VDecl->getLocation(), 12113 /*DiscardedValue*/ false, VDecl->isConstexpr()); 12114 if (Result.isInvalid()) { 12115 VDecl->setInvalidDecl(); 12116 return; 12117 } 12118 Init = Result.get(); 12119 12120 // Attach the initializer to the decl. 12121 VDecl->setInit(Init); 12122 12123 if (VDecl->isLocalVarDecl()) { 12124 // Don't check the initializer if the declaration is malformed. 12125 if (VDecl->isInvalidDecl()) { 12126 // do nothing 12127 12128 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 12129 // This is true even in C++ for OpenCL. 12130 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 12131 CheckForConstantInitializer(Init, DclT); 12132 12133 // Otherwise, C++ does not restrict the initializer. 12134 } else if (getLangOpts().CPlusPlus) { 12135 // do nothing 12136 12137 // C99 6.7.8p4: All the expressions in an initializer for an object that has 12138 // static storage duration shall be constant expressions or string literals. 12139 } else if (VDecl->getStorageClass() == SC_Static) { 12140 CheckForConstantInitializer(Init, DclT); 12141 12142 // C89 is stricter than C99 for aggregate initializers. 12143 // C89 6.5.7p3: All the expressions [...] in an initializer list 12144 // for an object that has aggregate or union type shall be 12145 // constant expressions. 12146 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 12147 isa<InitListExpr>(Init)) { 12148 const Expr *Culprit; 12149 if (!Init->isConstantInitializer(Context, false, &Culprit)) { 12150 Diag(Culprit->getExprLoc(), 12151 diag::ext_aggregate_init_not_constant) 12152 << Culprit->getSourceRange(); 12153 } 12154 } 12155 12156 if (auto *E = dyn_cast<ExprWithCleanups>(Init)) 12157 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens())) 12158 if (VDecl->hasLocalStorage()) 12159 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 12160 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 12161 VDecl->getLexicalDeclContext()->isRecord()) { 12162 // This is an in-class initialization for a static data member, e.g., 12163 // 12164 // struct S { 12165 // static const int value = 17; 12166 // }; 12167 12168 // C++ [class.mem]p4: 12169 // A member-declarator can contain a constant-initializer only 12170 // if it declares a static member (9.4) of const integral or 12171 // const enumeration type, see 9.4.2. 12172 // 12173 // C++11 [class.static.data]p3: 12174 // If a non-volatile non-inline const static data member is of integral 12175 // or enumeration type, its declaration in the class definition can 12176 // specify a brace-or-equal-initializer in which every initializer-clause 12177 // that is an assignment-expression is a constant expression. A static 12178 // data member of literal type can be declared in the class definition 12179 // with the constexpr specifier; if so, its declaration shall specify a 12180 // brace-or-equal-initializer in which every initializer-clause that is 12181 // an assignment-expression is a constant expression. 12182 12183 // Do nothing on dependent types. 12184 if (DclT->isDependentType()) { 12185 12186 // Allow any 'static constexpr' members, whether or not they are of literal 12187 // type. We separately check that every constexpr variable is of literal 12188 // type. 12189 } else if (VDecl->isConstexpr()) { 12190 12191 // Require constness. 12192 } else if (!DclT.isConstQualified()) { 12193 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 12194 << Init->getSourceRange(); 12195 VDecl->setInvalidDecl(); 12196 12197 // We allow integer constant expressions in all cases. 12198 } else if (DclT->isIntegralOrEnumerationType()) { 12199 // Check whether the expression is a constant expression. 12200 SourceLocation Loc; 12201 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 12202 // In C++11, a non-constexpr const static data member with an 12203 // in-class initializer cannot be volatile. 12204 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 12205 else if (Init->isValueDependent()) 12206 ; // Nothing to check. 12207 else if (Init->isIntegerConstantExpr(Context, &Loc)) 12208 ; // Ok, it's an ICE! 12209 else if (Init->getType()->isScopedEnumeralType() && 12210 Init->isCXX11ConstantExpr(Context)) 12211 ; // Ok, it is a scoped-enum constant expression. 12212 else if (Init->isEvaluatable(Context)) { 12213 // If we can constant fold the initializer through heroics, accept it, 12214 // but report this as a use of an extension for -pedantic. 12215 Diag(Loc, diag::ext_in_class_initializer_non_constant) 12216 << Init->getSourceRange(); 12217 } else { 12218 // Otherwise, this is some crazy unknown case. Report the issue at the 12219 // location provided by the isIntegerConstantExpr failed check. 12220 Diag(Loc, diag::err_in_class_initializer_non_constant) 12221 << Init->getSourceRange(); 12222 VDecl->setInvalidDecl(); 12223 } 12224 12225 // We allow foldable floating-point constants as an extension. 12226 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 12227 // In C++98, this is a GNU extension. In C++11, it is not, but we support 12228 // it anyway and provide a fixit to add the 'constexpr'. 12229 if (getLangOpts().CPlusPlus11) { 12230 Diag(VDecl->getLocation(), 12231 diag::ext_in_class_initializer_float_type_cxx11) 12232 << DclT << Init->getSourceRange(); 12233 Diag(VDecl->getBeginLoc(), 12234 diag::note_in_class_initializer_float_type_cxx11) 12235 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12236 } else { 12237 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 12238 << DclT << Init->getSourceRange(); 12239 12240 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 12241 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 12242 << Init->getSourceRange(); 12243 VDecl->setInvalidDecl(); 12244 } 12245 } 12246 12247 // Suggest adding 'constexpr' in C++11 for literal types. 12248 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 12249 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 12250 << DclT << Init->getSourceRange() 12251 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12252 VDecl->setConstexpr(true); 12253 12254 } else { 12255 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 12256 << DclT << Init->getSourceRange(); 12257 VDecl->setInvalidDecl(); 12258 } 12259 } else if (VDecl->isFileVarDecl()) { 12260 // In C, extern is typically used to avoid tentative definitions when 12261 // declaring variables in headers, but adding an intializer makes it a 12262 // definition. This is somewhat confusing, so GCC and Clang both warn on it. 12263 // In C++, extern is often used to give implictly static const variables 12264 // external linkage, so don't warn in that case. If selectany is present, 12265 // this might be header code intended for C and C++ inclusion, so apply the 12266 // C++ rules. 12267 if (VDecl->getStorageClass() == SC_Extern && 12268 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 12269 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 12270 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 12271 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 12272 Diag(VDecl->getLocation(), diag::warn_extern_init); 12273 12274 // In Microsoft C++ mode, a const variable defined in namespace scope has 12275 // external linkage by default if the variable is declared with 12276 // __declspec(dllexport). 12277 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 12278 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() && 12279 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition()) 12280 VDecl->setStorageClass(SC_Extern); 12281 12282 // C99 6.7.8p4. All file scoped initializers need to be constant. 12283 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 12284 CheckForConstantInitializer(Init, DclT); 12285 } 12286 12287 QualType InitType = Init->getType(); 12288 if (!InitType.isNull() && 12289 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12290 InitType.hasNonTrivialToPrimitiveCopyCUnion())) 12291 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc()); 12292 12293 // We will represent direct-initialization similarly to copy-initialization: 12294 // int x(1); -as-> int x = 1; 12295 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 12296 // 12297 // Clients that want to distinguish between the two forms, can check for 12298 // direct initializer using VarDecl::getInitStyle(). 12299 // A major benefit is that clients that don't particularly care about which 12300 // exactly form was it (like the CodeGen) can handle both cases without 12301 // special case code. 12302 12303 // C++ 8.5p11: 12304 // The form of initialization (using parentheses or '=') is generally 12305 // insignificant, but does matter when the entity being initialized has a 12306 // class type. 12307 if (CXXDirectInit) { 12308 assert(DirectInit && "Call-style initializer must be direct init."); 12309 VDecl->setInitStyle(VarDecl::CallInit); 12310 } else if (DirectInit) { 12311 // This must be list-initialization. No other way is direct-initialization. 12312 VDecl->setInitStyle(VarDecl::ListInit); 12313 } 12314 12315 if (LangOpts.OpenMP && VDecl->isFileVarDecl()) 12316 DeclsToCheckForDeferredDiags.push_back(VDecl); 12317 CheckCompleteVariableDeclaration(VDecl); 12318 } 12319 12320 /// ActOnInitializerError - Given that there was an error parsing an 12321 /// initializer for the given declaration, try to return to some form 12322 /// of sanity. 12323 void Sema::ActOnInitializerError(Decl *D) { 12324 // Our main concern here is re-establishing invariants like "a 12325 // variable's type is either dependent or complete". 12326 if (!D || D->isInvalidDecl()) return; 12327 12328 VarDecl *VD = dyn_cast<VarDecl>(D); 12329 if (!VD) return; 12330 12331 // Bindings are not usable if we can't make sense of the initializer. 12332 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 12333 for (auto *BD : DD->bindings()) 12334 BD->setInvalidDecl(); 12335 12336 // Auto types are meaningless if we can't make sense of the initializer. 12337 if (VD->getType()->isUndeducedType()) { 12338 D->setInvalidDecl(); 12339 return; 12340 } 12341 12342 QualType Ty = VD->getType(); 12343 if (Ty->isDependentType()) return; 12344 12345 // Require a complete type. 12346 if (RequireCompleteType(VD->getLocation(), 12347 Context.getBaseElementType(Ty), 12348 diag::err_typecheck_decl_incomplete_type)) { 12349 VD->setInvalidDecl(); 12350 return; 12351 } 12352 12353 // Require a non-abstract type. 12354 if (RequireNonAbstractType(VD->getLocation(), Ty, 12355 diag::err_abstract_type_in_decl, 12356 AbstractVariableType)) { 12357 VD->setInvalidDecl(); 12358 return; 12359 } 12360 12361 // Don't bother complaining about constructors or destructors, 12362 // though. 12363 } 12364 12365 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 12366 // If there is no declaration, there was an error parsing it. Just ignore it. 12367 if (!RealDecl) 12368 return; 12369 12370 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 12371 QualType Type = Var->getType(); 12372 12373 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 12374 if (isa<DecompositionDecl>(RealDecl)) { 12375 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 12376 Var->setInvalidDecl(); 12377 return; 12378 } 12379 12380 if (Type->isUndeducedType() && 12381 DeduceVariableDeclarationType(Var, false, nullptr)) 12382 return; 12383 12384 // C++11 [class.static.data]p3: A static data member can be declared with 12385 // the constexpr specifier; if so, its declaration shall specify 12386 // a brace-or-equal-initializer. 12387 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 12388 // the definition of a variable [...] or the declaration of a static data 12389 // member. 12390 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 12391 !Var->isThisDeclarationADemotedDefinition()) { 12392 if (Var->isStaticDataMember()) { 12393 // C++1z removes the relevant rule; the in-class declaration is always 12394 // a definition there. 12395 if (!getLangOpts().CPlusPlus17 && 12396 !Context.getTargetInfo().getCXXABI().isMicrosoft()) { 12397 Diag(Var->getLocation(), 12398 diag::err_constexpr_static_mem_var_requires_init) 12399 << Var->getDeclName(); 12400 Var->setInvalidDecl(); 12401 return; 12402 } 12403 } else { 12404 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 12405 Var->setInvalidDecl(); 12406 return; 12407 } 12408 } 12409 12410 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 12411 // be initialized. 12412 if (!Var->isInvalidDecl() && 12413 Var->getType().getAddressSpace() == LangAS::opencl_constant && 12414 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 12415 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 12416 Var->setInvalidDecl(); 12417 return; 12418 } 12419 12420 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) { 12421 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) { 12422 if (!RD->hasTrivialDefaultConstructor()) { 12423 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor); 12424 Var->setInvalidDecl(); 12425 return; 12426 } 12427 } 12428 if (Var->getStorageClass() == SC_Extern) { 12429 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl) 12430 << Var; 12431 Var->setInvalidDecl(); 12432 return; 12433 } 12434 } 12435 12436 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition(); 12437 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly && 12438 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 12439 checkNonTrivialCUnion(Var->getType(), Var->getLocation(), 12440 NTCUC_DefaultInitializedObject, NTCUK_Init); 12441 12442 12443 switch (DefKind) { 12444 case VarDecl::Definition: 12445 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 12446 break; 12447 12448 // We have an out-of-line definition of a static data member 12449 // that has an in-class initializer, so we type-check this like 12450 // a declaration. 12451 // 12452 LLVM_FALLTHROUGH; 12453 12454 case VarDecl::DeclarationOnly: 12455 // It's only a declaration. 12456 12457 // Block scope. C99 6.7p7: If an identifier for an object is 12458 // declared with no linkage (C99 6.2.2p6), the type for the 12459 // object shall be complete. 12460 if (!Type->isDependentType() && Var->isLocalVarDecl() && 12461 !Var->hasLinkage() && !Var->isInvalidDecl() && 12462 RequireCompleteType(Var->getLocation(), Type, 12463 diag::err_typecheck_decl_incomplete_type)) 12464 Var->setInvalidDecl(); 12465 12466 // Make sure that the type is not abstract. 12467 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12468 RequireNonAbstractType(Var->getLocation(), Type, 12469 diag::err_abstract_type_in_decl, 12470 AbstractVariableType)) 12471 Var->setInvalidDecl(); 12472 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12473 Var->getStorageClass() == SC_PrivateExtern) { 12474 Diag(Var->getLocation(), diag::warn_private_extern); 12475 Diag(Var->getLocation(), diag::note_private_extern); 12476 } 12477 12478 if (Context.getTargetInfo().allowDebugInfoForExternalVar() && 12479 !Var->isInvalidDecl() && !getLangOpts().CPlusPlus) 12480 ExternalDeclarations.push_back(Var); 12481 12482 return; 12483 12484 case VarDecl::TentativeDefinition: 12485 // File scope. C99 6.9.2p2: A declaration of an identifier for an 12486 // object that has file scope without an initializer, and without a 12487 // storage-class specifier or with the storage-class specifier "static", 12488 // constitutes a tentative definition. Note: A tentative definition with 12489 // external linkage is valid (C99 6.2.2p5). 12490 if (!Var->isInvalidDecl()) { 12491 if (const IncompleteArrayType *ArrayT 12492 = Context.getAsIncompleteArrayType(Type)) { 12493 if (RequireCompleteSizedType( 12494 Var->getLocation(), ArrayT->getElementType(), 12495 diag::err_array_incomplete_or_sizeless_type)) 12496 Var->setInvalidDecl(); 12497 } else if (Var->getStorageClass() == SC_Static) { 12498 // C99 6.9.2p3: If the declaration of an identifier for an object is 12499 // a tentative definition and has internal linkage (C99 6.2.2p3), the 12500 // declared type shall not be an incomplete type. 12501 // NOTE: code such as the following 12502 // static struct s; 12503 // struct s { int a; }; 12504 // is accepted by gcc. Hence here we issue a warning instead of 12505 // an error and we do not invalidate the static declaration. 12506 // NOTE: to avoid multiple warnings, only check the first declaration. 12507 if (Var->isFirstDecl()) 12508 RequireCompleteType(Var->getLocation(), Type, 12509 diag::ext_typecheck_decl_incomplete_type); 12510 } 12511 } 12512 12513 // Record the tentative definition; we're done. 12514 if (!Var->isInvalidDecl()) 12515 TentativeDefinitions.push_back(Var); 12516 return; 12517 } 12518 12519 // Provide a specific diagnostic for uninitialized variable 12520 // definitions with incomplete array type. 12521 if (Type->isIncompleteArrayType()) { 12522 Diag(Var->getLocation(), 12523 diag::err_typecheck_incomplete_array_needs_initializer); 12524 Var->setInvalidDecl(); 12525 return; 12526 } 12527 12528 // Provide a specific diagnostic for uninitialized variable 12529 // definitions with reference type. 12530 if (Type->isReferenceType()) { 12531 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 12532 << Var->getDeclName() 12533 << SourceRange(Var->getLocation(), Var->getLocation()); 12534 Var->setInvalidDecl(); 12535 return; 12536 } 12537 12538 // Do not attempt to type-check the default initializer for a 12539 // variable with dependent type. 12540 if (Type->isDependentType()) 12541 return; 12542 12543 if (Var->isInvalidDecl()) 12544 return; 12545 12546 if (!Var->hasAttr<AliasAttr>()) { 12547 if (RequireCompleteType(Var->getLocation(), 12548 Context.getBaseElementType(Type), 12549 diag::err_typecheck_decl_incomplete_type)) { 12550 Var->setInvalidDecl(); 12551 return; 12552 } 12553 } else { 12554 return; 12555 } 12556 12557 // The variable can not have an abstract class type. 12558 if (RequireNonAbstractType(Var->getLocation(), Type, 12559 diag::err_abstract_type_in_decl, 12560 AbstractVariableType)) { 12561 Var->setInvalidDecl(); 12562 return; 12563 } 12564 12565 // Check for jumps past the implicit initializer. C++0x 12566 // clarifies that this applies to a "variable with automatic 12567 // storage duration", not a "local variable". 12568 // C++11 [stmt.dcl]p3 12569 // A program that jumps from a point where a variable with automatic 12570 // storage duration is not in scope to a point where it is in scope is 12571 // ill-formed unless the variable has scalar type, class type with a 12572 // trivial default constructor and a trivial destructor, a cv-qualified 12573 // version of one of these types, or an array of one of the preceding 12574 // types and is declared without an initializer. 12575 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 12576 if (const RecordType *Record 12577 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 12578 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 12579 // Mark the function (if we're in one) for further checking even if the 12580 // looser rules of C++11 do not require such checks, so that we can 12581 // diagnose incompatibilities with C++98. 12582 if (!CXXRecord->isPOD()) 12583 setFunctionHasBranchProtectedScope(); 12584 } 12585 } 12586 // In OpenCL, we can't initialize objects in the __local address space, 12587 // even implicitly, so don't synthesize an implicit initializer. 12588 if (getLangOpts().OpenCL && 12589 Var->getType().getAddressSpace() == LangAS::opencl_local) 12590 return; 12591 // C++03 [dcl.init]p9: 12592 // If no initializer is specified for an object, and the 12593 // object is of (possibly cv-qualified) non-POD class type (or 12594 // array thereof), the object shall be default-initialized; if 12595 // the object is of const-qualified type, the underlying class 12596 // type shall have a user-declared default 12597 // constructor. Otherwise, if no initializer is specified for 12598 // a non- static object, the object and its subobjects, if 12599 // any, have an indeterminate initial value); if the object 12600 // or any of its subobjects are of const-qualified type, the 12601 // program is ill-formed. 12602 // C++0x [dcl.init]p11: 12603 // If no initializer is specified for an object, the object is 12604 // default-initialized; [...]. 12605 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 12606 InitializationKind Kind 12607 = InitializationKind::CreateDefault(Var->getLocation()); 12608 12609 InitializationSequence InitSeq(*this, Entity, Kind, None); 12610 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 12611 12612 if (Init.get()) { 12613 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 12614 // This is important for template substitution. 12615 Var->setInitStyle(VarDecl::CallInit); 12616 } else if (Init.isInvalid()) { 12617 // If default-init fails, attach a recovery-expr initializer to track 12618 // that initialization was attempted and failed. 12619 auto RecoveryExpr = 12620 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {}); 12621 if (RecoveryExpr.get()) 12622 Var->setInit(RecoveryExpr.get()); 12623 } 12624 12625 CheckCompleteVariableDeclaration(Var); 12626 } 12627 } 12628 12629 void Sema::ActOnCXXForRangeDecl(Decl *D) { 12630 // If there is no declaration, there was an error parsing it. Ignore it. 12631 if (!D) 12632 return; 12633 12634 VarDecl *VD = dyn_cast<VarDecl>(D); 12635 if (!VD) { 12636 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 12637 D->setInvalidDecl(); 12638 return; 12639 } 12640 12641 VD->setCXXForRangeDecl(true); 12642 12643 // for-range-declaration cannot be given a storage class specifier. 12644 int Error = -1; 12645 switch (VD->getStorageClass()) { 12646 case SC_None: 12647 break; 12648 case SC_Extern: 12649 Error = 0; 12650 break; 12651 case SC_Static: 12652 Error = 1; 12653 break; 12654 case SC_PrivateExtern: 12655 Error = 2; 12656 break; 12657 case SC_Auto: 12658 Error = 3; 12659 break; 12660 case SC_Register: 12661 Error = 4; 12662 break; 12663 } 12664 if (Error != -1) { 12665 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 12666 << VD->getDeclName() << Error; 12667 D->setInvalidDecl(); 12668 } 12669 } 12670 12671 StmtResult 12672 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 12673 IdentifierInfo *Ident, 12674 ParsedAttributes &Attrs, 12675 SourceLocation AttrEnd) { 12676 // C++1y [stmt.iter]p1: 12677 // A range-based for statement of the form 12678 // for ( for-range-identifier : for-range-initializer ) statement 12679 // is equivalent to 12680 // for ( auto&& for-range-identifier : for-range-initializer ) statement 12681 DeclSpec DS(Attrs.getPool().getFactory()); 12682 12683 const char *PrevSpec; 12684 unsigned DiagID; 12685 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 12686 getPrintingPolicy()); 12687 12688 Declarator D(DS, DeclaratorContext::ForContext); 12689 D.SetIdentifier(Ident, IdentLoc); 12690 D.takeAttributes(Attrs, AttrEnd); 12691 12692 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false), 12693 IdentLoc); 12694 Decl *Var = ActOnDeclarator(S, D); 12695 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 12696 FinalizeDeclaration(Var); 12697 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 12698 AttrEnd.isValid() ? AttrEnd : IdentLoc); 12699 } 12700 12701 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 12702 if (var->isInvalidDecl()) return; 12703 12704 if (getLangOpts().OpenCL) { 12705 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 12706 // initialiser 12707 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 12708 !var->hasInit()) { 12709 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 12710 << 1 /*Init*/; 12711 var->setInvalidDecl(); 12712 return; 12713 } 12714 } 12715 12716 // In Objective-C, don't allow jumps past the implicit initialization of a 12717 // local retaining variable. 12718 if (getLangOpts().ObjC && 12719 var->hasLocalStorage()) { 12720 switch (var->getType().getObjCLifetime()) { 12721 case Qualifiers::OCL_None: 12722 case Qualifiers::OCL_ExplicitNone: 12723 case Qualifiers::OCL_Autoreleasing: 12724 break; 12725 12726 case Qualifiers::OCL_Weak: 12727 case Qualifiers::OCL_Strong: 12728 setFunctionHasBranchProtectedScope(); 12729 break; 12730 } 12731 } 12732 12733 if (var->hasLocalStorage() && 12734 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 12735 setFunctionHasBranchProtectedScope(); 12736 12737 // Warn about externally-visible variables being defined without a 12738 // prior declaration. We only want to do this for global 12739 // declarations, but we also specifically need to avoid doing it for 12740 // class members because the linkage of an anonymous class can 12741 // change if it's later given a typedef name. 12742 if (var->isThisDeclarationADefinition() && 12743 var->getDeclContext()->getRedeclContext()->isFileContext() && 12744 var->isExternallyVisible() && var->hasLinkage() && 12745 !var->isInline() && !var->getDescribedVarTemplate() && 12746 !isa<VarTemplatePartialSpecializationDecl>(var) && 12747 !isTemplateInstantiation(var->getTemplateSpecializationKind()) && 12748 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 12749 var->getLocation())) { 12750 // Find a previous declaration that's not a definition. 12751 VarDecl *prev = var->getPreviousDecl(); 12752 while (prev && prev->isThisDeclarationADefinition()) 12753 prev = prev->getPreviousDecl(); 12754 12755 if (!prev) { 12756 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 12757 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 12758 << /* variable */ 0; 12759 } 12760 } 12761 12762 // Cache the result of checking for constant initialization. 12763 Optional<bool> CacheHasConstInit; 12764 const Expr *CacheCulprit = nullptr; 12765 auto checkConstInit = [&]() mutable { 12766 if (!CacheHasConstInit) 12767 CacheHasConstInit = var->getInit()->isConstantInitializer( 12768 Context, var->getType()->isReferenceType(), &CacheCulprit); 12769 return *CacheHasConstInit; 12770 }; 12771 12772 if (var->getTLSKind() == VarDecl::TLS_Static) { 12773 if (var->getType().isDestructedType()) { 12774 // GNU C++98 edits for __thread, [basic.start.term]p3: 12775 // The type of an object with thread storage duration shall not 12776 // have a non-trivial destructor. 12777 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 12778 if (getLangOpts().CPlusPlus11) 12779 Diag(var->getLocation(), diag::note_use_thread_local); 12780 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 12781 if (!checkConstInit()) { 12782 // GNU C++98 edits for __thread, [basic.start.init]p4: 12783 // An object of thread storage duration shall not require dynamic 12784 // initialization. 12785 // FIXME: Need strict checking here. 12786 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 12787 << CacheCulprit->getSourceRange(); 12788 if (getLangOpts().CPlusPlus11) 12789 Diag(var->getLocation(), diag::note_use_thread_local); 12790 } 12791 } 12792 } 12793 12794 // Apply section attributes and pragmas to global variables. 12795 bool GlobalStorage = var->hasGlobalStorage(); 12796 if (GlobalStorage && var->isThisDeclarationADefinition() && 12797 !inTemplateInstantiation()) { 12798 PragmaStack<StringLiteral *> *Stack = nullptr; 12799 int SectionFlags = ASTContext::PSF_Read; 12800 if (var->getType().isConstQualified()) 12801 Stack = &ConstSegStack; 12802 else if (!var->getInit()) { 12803 Stack = &BSSSegStack; 12804 SectionFlags |= ASTContext::PSF_Write; 12805 } else { 12806 Stack = &DataSegStack; 12807 SectionFlags |= ASTContext::PSF_Write; 12808 } 12809 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) { 12810 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec) 12811 SectionFlags |= ASTContext::PSF_Implicit; 12812 UnifySection(SA->getName(), SectionFlags, var); 12813 } else if (Stack->CurrentValue) { 12814 SectionFlags |= ASTContext::PSF_Implicit; 12815 auto SectionName = Stack->CurrentValue->getString(); 12816 var->addAttr(SectionAttr::CreateImplicit( 12817 Context, SectionName, Stack->CurrentPragmaLocation, 12818 AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate)); 12819 if (UnifySection(SectionName, SectionFlags, var)) 12820 var->dropAttr<SectionAttr>(); 12821 } 12822 12823 // Apply the init_seg attribute if this has an initializer. If the 12824 // initializer turns out to not be dynamic, we'll end up ignoring this 12825 // attribute. 12826 if (CurInitSeg && var->getInit()) 12827 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 12828 CurInitSegLoc, 12829 AttributeCommonInfo::AS_Pragma)); 12830 } 12831 12832 // All the following checks are C++ only. 12833 if (!getLangOpts().CPlusPlus) { 12834 // If this variable must be emitted, add it as an initializer for the 12835 // current module. 12836 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 12837 Context.addModuleInitializer(ModuleScopes.back().Module, var); 12838 return; 12839 } 12840 12841 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 12842 CheckCompleteDecompositionDeclaration(DD); 12843 12844 QualType type = var->getType(); 12845 if (type->isDependentType()) return; 12846 12847 if (var->hasAttr<BlocksAttr>()) 12848 getCurFunction()->addByrefBlockVar(var); 12849 12850 Expr *Init = var->getInit(); 12851 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 12852 QualType baseType = Context.getBaseElementType(type); 12853 12854 if (Init && !Init->isValueDependent()) { 12855 if (var->isConstexpr()) { 12856 SmallVector<PartialDiagnosticAt, 8> Notes; 12857 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 12858 SourceLocation DiagLoc = var->getLocation(); 12859 // If the note doesn't add any useful information other than a source 12860 // location, fold it into the primary diagnostic. 12861 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 12862 diag::note_invalid_subexpr_in_const_expr) { 12863 DiagLoc = Notes[0].first; 12864 Notes.clear(); 12865 } 12866 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 12867 << var << Init->getSourceRange(); 12868 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 12869 Diag(Notes[I].first, Notes[I].second); 12870 } 12871 } else if (var->mightBeUsableInConstantExpressions(Context)) { 12872 // Check whether the initializer of a const variable of integral or 12873 // enumeration type is an ICE now, since we can't tell whether it was 12874 // initialized by a constant expression if we check later. 12875 var->checkInitIsICE(); 12876 } 12877 12878 // Don't emit further diagnostics about constexpr globals since they 12879 // were just diagnosed. 12880 if (!var->isConstexpr() && GlobalStorage && var->hasAttr<ConstInitAttr>()) { 12881 // FIXME: Need strict checking in C++03 here. 12882 bool DiagErr = getLangOpts().CPlusPlus11 12883 ? !var->checkInitIsICE() : !checkConstInit(); 12884 if (DiagErr) { 12885 auto *Attr = var->getAttr<ConstInitAttr>(); 12886 Diag(var->getLocation(), diag::err_require_constant_init_failed) 12887 << Init->getSourceRange(); 12888 Diag(Attr->getLocation(), 12889 diag::note_declared_required_constant_init_here) 12890 << Attr->getRange() << Attr->isConstinit(); 12891 if (getLangOpts().CPlusPlus11) { 12892 APValue Value; 12893 SmallVector<PartialDiagnosticAt, 8> Notes; 12894 Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes); 12895 for (auto &it : Notes) 12896 Diag(it.first, it.second); 12897 } else { 12898 Diag(CacheCulprit->getExprLoc(), 12899 diag::note_invalid_subexpr_in_const_expr) 12900 << CacheCulprit->getSourceRange(); 12901 } 12902 } 12903 } 12904 else if (!var->isConstexpr() && IsGlobal && 12905 !getDiagnostics().isIgnored(diag::warn_global_constructor, 12906 var->getLocation())) { 12907 // Warn about globals which don't have a constant initializer. Don't 12908 // warn about globals with a non-trivial destructor because we already 12909 // warned about them. 12910 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 12911 if (!(RD && !RD->hasTrivialDestructor())) { 12912 if (!checkConstInit()) 12913 Diag(var->getLocation(), diag::warn_global_constructor) 12914 << Init->getSourceRange(); 12915 } 12916 } 12917 } 12918 12919 // Require the destructor. 12920 if (const RecordType *recordType = baseType->getAs<RecordType>()) 12921 FinalizeVarWithDestructor(var, recordType); 12922 12923 // If this variable must be emitted, add it as an initializer for the current 12924 // module. 12925 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 12926 Context.addModuleInitializer(ModuleScopes.back().Module, var); 12927 } 12928 12929 /// Determines if a variable's alignment is dependent. 12930 static bool hasDependentAlignment(VarDecl *VD) { 12931 if (VD->getType()->isDependentType()) 12932 return true; 12933 for (auto *I : VD->specific_attrs<AlignedAttr>()) 12934 if (I->isAlignmentDependent()) 12935 return true; 12936 return false; 12937 } 12938 12939 /// Check if VD needs to be dllexport/dllimport due to being in a 12940 /// dllexport/import function. 12941 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) { 12942 assert(VD->isStaticLocal()); 12943 12944 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 12945 12946 // Find outermost function when VD is in lambda function. 12947 while (FD && !getDLLAttr(FD) && 12948 !FD->hasAttr<DLLExportStaticLocalAttr>() && 12949 !FD->hasAttr<DLLImportStaticLocalAttr>()) { 12950 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod()); 12951 } 12952 12953 if (!FD) 12954 return; 12955 12956 // Static locals inherit dll attributes from their function. 12957 if (Attr *A = getDLLAttr(FD)) { 12958 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 12959 NewAttr->setInherited(true); 12960 VD->addAttr(NewAttr); 12961 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) { 12962 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A); 12963 NewAttr->setInherited(true); 12964 VD->addAttr(NewAttr); 12965 12966 // Export this function to enforce exporting this static variable even 12967 // if it is not used in this compilation unit. 12968 if (!FD->hasAttr<DLLExportAttr>()) 12969 FD->addAttr(NewAttr); 12970 12971 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) { 12972 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A); 12973 NewAttr->setInherited(true); 12974 VD->addAttr(NewAttr); 12975 } 12976 } 12977 12978 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 12979 /// any semantic actions necessary after any initializer has been attached. 12980 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 12981 // Note that we are no longer parsing the initializer for this declaration. 12982 ParsingInitForAutoVars.erase(ThisDecl); 12983 12984 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 12985 if (!VD) 12986 return; 12987 12988 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active 12989 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && 12990 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { 12991 if (PragmaClangBSSSection.Valid) 12992 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit( 12993 Context, PragmaClangBSSSection.SectionName, 12994 PragmaClangBSSSection.PragmaLocation, 12995 AttributeCommonInfo::AS_Pragma)); 12996 if (PragmaClangDataSection.Valid) 12997 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit( 12998 Context, PragmaClangDataSection.SectionName, 12999 PragmaClangDataSection.PragmaLocation, 13000 AttributeCommonInfo::AS_Pragma)); 13001 if (PragmaClangRodataSection.Valid) 13002 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit( 13003 Context, PragmaClangRodataSection.SectionName, 13004 PragmaClangRodataSection.PragmaLocation, 13005 AttributeCommonInfo::AS_Pragma)); 13006 if (PragmaClangRelroSection.Valid) 13007 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit( 13008 Context, PragmaClangRelroSection.SectionName, 13009 PragmaClangRelroSection.PragmaLocation, 13010 AttributeCommonInfo::AS_Pragma)); 13011 } 13012 13013 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 13014 for (auto *BD : DD->bindings()) { 13015 FinalizeDeclaration(BD); 13016 } 13017 } 13018 13019 checkAttributesAfterMerging(*this, *VD); 13020 13021 // Perform TLS alignment check here after attributes attached to the variable 13022 // which may affect the alignment have been processed. Only perform the check 13023 // if the target has a maximum TLS alignment (zero means no constraints). 13024 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 13025 // Protect the check so that it's not performed on dependent types and 13026 // dependent alignments (we can't determine the alignment in that case). 13027 if (VD->getTLSKind() && !hasDependentAlignment(VD) && 13028 !VD->isInvalidDecl()) { 13029 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 13030 if (Context.getDeclAlign(VD) > MaxAlignChars) { 13031 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 13032 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 13033 << (unsigned)MaxAlignChars.getQuantity(); 13034 } 13035 } 13036 } 13037 13038 if (VD->isStaticLocal()) { 13039 CheckStaticLocalForDllExport(VD); 13040 13041 if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { 13042 // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__ 13043 // function, only __shared__ variables or variables without any device 13044 // memory qualifiers may be declared with static storage class. 13045 // Note: It is unclear how a function-scope non-const static variable 13046 // without device memory qualifier is implemented, therefore only static 13047 // const variable without device memory qualifier is allowed. 13048 [&]() { 13049 if (!getLangOpts().CUDA) 13050 return; 13051 if (VD->hasAttr<CUDASharedAttr>()) 13052 return; 13053 if (VD->getType().isConstQualified() && 13054 !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>())) 13055 return; 13056 if (CUDADiagIfDeviceCode(VD->getLocation(), 13057 diag::err_device_static_local_var) 13058 << CurrentCUDATarget()) 13059 VD->setInvalidDecl(); 13060 }(); 13061 } 13062 } 13063 13064 // Perform check for initializers of device-side global variables. 13065 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 13066 // 7.5). We must also apply the same checks to all __shared__ 13067 // variables whether they are local or not. CUDA also allows 13068 // constant initializers for __constant__ and __device__ variables. 13069 if (getLangOpts().CUDA) 13070 checkAllowedCUDAInitializer(VD); 13071 13072 // Grab the dllimport or dllexport attribute off of the VarDecl. 13073 const InheritableAttr *DLLAttr = getDLLAttr(VD); 13074 13075 // Imported static data members cannot be defined out-of-line. 13076 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 13077 if (VD->isStaticDataMember() && VD->isOutOfLine() && 13078 VD->isThisDeclarationADefinition()) { 13079 // We allow definitions of dllimport class template static data members 13080 // with a warning. 13081 CXXRecordDecl *Context = 13082 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 13083 bool IsClassTemplateMember = 13084 isa<ClassTemplatePartialSpecializationDecl>(Context) || 13085 Context->getDescribedClassTemplate(); 13086 13087 Diag(VD->getLocation(), 13088 IsClassTemplateMember 13089 ? diag::warn_attribute_dllimport_static_field_definition 13090 : diag::err_attribute_dllimport_static_field_definition); 13091 Diag(IA->getLocation(), diag::note_attribute); 13092 if (!IsClassTemplateMember) 13093 VD->setInvalidDecl(); 13094 } 13095 } 13096 13097 // dllimport/dllexport variables cannot be thread local, their TLS index 13098 // isn't exported with the variable. 13099 if (DLLAttr && VD->getTLSKind()) { 13100 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 13101 if (F && getDLLAttr(F)) { 13102 assert(VD->isStaticLocal()); 13103 // But if this is a static local in a dlimport/dllexport function, the 13104 // function will never be inlined, which means the var would never be 13105 // imported, so having it marked import/export is safe. 13106 } else { 13107 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 13108 << DLLAttr; 13109 VD->setInvalidDecl(); 13110 } 13111 } 13112 13113 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 13114 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 13115 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 13116 VD->dropAttr<UsedAttr>(); 13117 } 13118 } 13119 13120 const DeclContext *DC = VD->getDeclContext(); 13121 // If there's a #pragma GCC visibility in scope, and this isn't a class 13122 // member, set the visibility of this variable. 13123 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 13124 AddPushedVisibilityAttribute(VD); 13125 13126 // FIXME: Warn on unused var template partial specializations. 13127 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 13128 MarkUnusedFileScopedDecl(VD); 13129 13130 // Now we have parsed the initializer and can update the table of magic 13131 // tag values. 13132 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 13133 !VD->getType()->isIntegralOrEnumerationType()) 13134 return; 13135 13136 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 13137 const Expr *MagicValueExpr = VD->getInit(); 13138 if (!MagicValueExpr) { 13139 continue; 13140 } 13141 llvm::APSInt MagicValueInt; 13142 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 13143 Diag(I->getRange().getBegin(), 13144 diag::err_type_tag_for_datatype_not_ice) 13145 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13146 continue; 13147 } 13148 if (MagicValueInt.getActiveBits() > 64) { 13149 Diag(I->getRange().getBegin(), 13150 diag::err_type_tag_for_datatype_too_large) 13151 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13152 continue; 13153 } 13154 uint64_t MagicValue = MagicValueInt.getZExtValue(); 13155 RegisterTypeTagForDatatype(I->getArgumentKind(), 13156 MagicValue, 13157 I->getMatchingCType(), 13158 I->getLayoutCompatible(), 13159 I->getMustBeNull()); 13160 } 13161 } 13162 13163 static bool hasDeducedAuto(DeclaratorDecl *DD) { 13164 auto *VD = dyn_cast<VarDecl>(DD); 13165 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 13166 } 13167 13168 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 13169 ArrayRef<Decl *> Group) { 13170 SmallVector<Decl*, 8> Decls; 13171 13172 if (DS.isTypeSpecOwned()) 13173 Decls.push_back(DS.getRepAsDecl()); 13174 13175 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 13176 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 13177 bool DiagnosedMultipleDecomps = false; 13178 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 13179 bool DiagnosedNonDeducedAuto = false; 13180 13181 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13182 if (Decl *D = Group[i]) { 13183 // For declarators, there are some additional syntactic-ish checks we need 13184 // to perform. 13185 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 13186 if (!FirstDeclaratorInGroup) 13187 FirstDeclaratorInGroup = DD; 13188 if (!FirstDecompDeclaratorInGroup) 13189 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 13190 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 13191 !hasDeducedAuto(DD)) 13192 FirstNonDeducedAutoInGroup = DD; 13193 13194 if (FirstDeclaratorInGroup != DD) { 13195 // A decomposition declaration cannot be combined with any other 13196 // declaration in the same group. 13197 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 13198 Diag(FirstDecompDeclaratorInGroup->getLocation(), 13199 diag::err_decomp_decl_not_alone) 13200 << FirstDeclaratorInGroup->getSourceRange() 13201 << DD->getSourceRange(); 13202 DiagnosedMultipleDecomps = true; 13203 } 13204 13205 // A declarator that uses 'auto' in any way other than to declare a 13206 // variable with a deduced type cannot be combined with any other 13207 // declarator in the same group. 13208 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 13209 Diag(FirstNonDeducedAutoInGroup->getLocation(), 13210 diag::err_auto_non_deduced_not_alone) 13211 << FirstNonDeducedAutoInGroup->getType() 13212 ->hasAutoForTrailingReturnType() 13213 << FirstDeclaratorInGroup->getSourceRange() 13214 << DD->getSourceRange(); 13215 DiagnosedNonDeducedAuto = true; 13216 } 13217 } 13218 } 13219 13220 Decls.push_back(D); 13221 } 13222 } 13223 13224 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 13225 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 13226 handleTagNumbering(Tag, S); 13227 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 13228 getLangOpts().CPlusPlus) 13229 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 13230 } 13231 } 13232 13233 return BuildDeclaratorGroup(Decls); 13234 } 13235 13236 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 13237 /// group, performing any necessary semantic checking. 13238 Sema::DeclGroupPtrTy 13239 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 13240 // C++14 [dcl.spec.auto]p7: (DR1347) 13241 // If the type that replaces the placeholder type is not the same in each 13242 // deduction, the program is ill-formed. 13243 if (Group.size() > 1) { 13244 QualType Deduced; 13245 VarDecl *DeducedDecl = nullptr; 13246 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13247 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 13248 if (!D || D->isInvalidDecl()) 13249 break; 13250 DeducedType *DT = D->getType()->getContainedDeducedType(); 13251 if (!DT || DT->getDeducedType().isNull()) 13252 continue; 13253 if (Deduced.isNull()) { 13254 Deduced = DT->getDeducedType(); 13255 DeducedDecl = D; 13256 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 13257 auto *AT = dyn_cast<AutoType>(DT); 13258 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 13259 diag::err_auto_different_deductions) 13260 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced 13261 << DeducedDecl->getDeclName() << DT->getDeducedType() 13262 << D->getDeclName(); 13263 if (DeducedDecl->hasInit()) 13264 Dia << DeducedDecl->getInit()->getSourceRange(); 13265 if (D->getInit()) 13266 Dia << D->getInit()->getSourceRange(); 13267 D->setInvalidDecl(); 13268 break; 13269 } 13270 } 13271 } 13272 13273 ActOnDocumentableDecls(Group); 13274 13275 return DeclGroupPtrTy::make( 13276 DeclGroupRef::Create(Context, Group.data(), Group.size())); 13277 } 13278 13279 void Sema::ActOnDocumentableDecl(Decl *D) { 13280 ActOnDocumentableDecls(D); 13281 } 13282 13283 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 13284 // Don't parse the comment if Doxygen diagnostics are ignored. 13285 if (Group.empty() || !Group[0]) 13286 return; 13287 13288 if (Diags.isIgnored(diag::warn_doc_param_not_found, 13289 Group[0]->getLocation()) && 13290 Diags.isIgnored(diag::warn_unknown_comment_command_name, 13291 Group[0]->getLocation())) 13292 return; 13293 13294 if (Group.size() >= 2) { 13295 // This is a decl group. Normally it will contain only declarations 13296 // produced from declarator list. But in case we have any definitions or 13297 // additional declaration references: 13298 // 'typedef struct S {} S;' 13299 // 'typedef struct S *S;' 13300 // 'struct S *pS;' 13301 // FinalizeDeclaratorGroup adds these as separate declarations. 13302 Decl *MaybeTagDecl = Group[0]; 13303 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 13304 Group = Group.slice(1); 13305 } 13306 } 13307 13308 // FIMXE: We assume every Decl in the group is in the same file. 13309 // This is false when preprocessor constructs the group from decls in 13310 // different files (e. g. macros or #include). 13311 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor()); 13312 } 13313 13314 /// Common checks for a parameter-declaration that should apply to both function 13315 /// parameters and non-type template parameters. 13316 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) { 13317 // Check that there are no default arguments inside the type of this 13318 // parameter. 13319 if (getLangOpts().CPlusPlus) 13320 CheckExtraCXXDefaultArguments(D); 13321 13322 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 13323 if (D.getCXXScopeSpec().isSet()) { 13324 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 13325 << D.getCXXScopeSpec().getRange(); 13326 } 13327 13328 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a 13329 // simple identifier except [...irrelevant cases...]. 13330 switch (D.getName().getKind()) { 13331 case UnqualifiedIdKind::IK_Identifier: 13332 break; 13333 13334 case UnqualifiedIdKind::IK_OperatorFunctionId: 13335 case UnqualifiedIdKind::IK_ConversionFunctionId: 13336 case UnqualifiedIdKind::IK_LiteralOperatorId: 13337 case UnqualifiedIdKind::IK_ConstructorName: 13338 case UnqualifiedIdKind::IK_DestructorName: 13339 case UnqualifiedIdKind::IK_ImplicitSelfParam: 13340 case UnqualifiedIdKind::IK_DeductionGuideName: 13341 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 13342 << GetNameForDeclarator(D).getName(); 13343 break; 13344 13345 case UnqualifiedIdKind::IK_TemplateId: 13346 case UnqualifiedIdKind::IK_ConstructorTemplateId: 13347 // GetNameForDeclarator would not produce a useful name in this case. 13348 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id); 13349 break; 13350 } 13351 } 13352 13353 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 13354 /// to introduce parameters into function prototype scope. 13355 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 13356 const DeclSpec &DS = D.getDeclSpec(); 13357 13358 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 13359 13360 // C++03 [dcl.stc]p2 also permits 'auto'. 13361 StorageClass SC = SC_None; 13362 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 13363 SC = SC_Register; 13364 // In C++11, the 'register' storage class specifier is deprecated. 13365 // In C++17, it is not allowed, but we tolerate it as an extension. 13366 if (getLangOpts().CPlusPlus11) { 13367 Diag(DS.getStorageClassSpecLoc(), 13368 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 13369 : diag::warn_deprecated_register) 13370 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 13371 } 13372 } else if (getLangOpts().CPlusPlus && 13373 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 13374 SC = SC_Auto; 13375 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 13376 Diag(DS.getStorageClassSpecLoc(), 13377 diag::err_invalid_storage_class_in_func_decl); 13378 D.getMutableDeclSpec().ClearStorageClassSpecs(); 13379 } 13380 13381 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 13382 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 13383 << DeclSpec::getSpecifierName(TSCS); 13384 if (DS.isInlineSpecified()) 13385 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 13386 << getLangOpts().CPlusPlus17; 13387 if (DS.hasConstexprSpecifier()) 13388 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 13389 << 0 << D.getDeclSpec().getConstexprSpecifier(); 13390 13391 DiagnoseFunctionSpecifiers(DS); 13392 13393 CheckFunctionOrTemplateParamDeclarator(S, D); 13394 13395 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13396 QualType parmDeclType = TInfo->getType(); 13397 13398 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 13399 IdentifierInfo *II = D.getIdentifier(); 13400 if (II) { 13401 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 13402 ForVisibleRedeclaration); 13403 LookupName(R, S); 13404 if (R.isSingleResult()) { 13405 NamedDecl *PrevDecl = R.getFoundDecl(); 13406 if (PrevDecl->isTemplateParameter()) { 13407 // Maybe we will complain about the shadowed template parameter. 13408 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13409 // Just pretend that we didn't see the previous declaration. 13410 PrevDecl = nullptr; 13411 } else if (S->isDeclScope(PrevDecl)) { 13412 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 13413 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 13414 13415 // Recover by removing the name 13416 II = nullptr; 13417 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 13418 D.setInvalidType(true); 13419 } 13420 } 13421 } 13422 13423 // Temporarily put parameter variables in the translation unit, not 13424 // the enclosing context. This prevents them from accidentally 13425 // looking like class members in C++. 13426 ParmVarDecl *New = 13427 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(), 13428 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC); 13429 13430 if (D.isInvalidType()) 13431 New->setInvalidDecl(); 13432 13433 assert(S->isFunctionPrototypeScope()); 13434 assert(S->getFunctionPrototypeDepth() >= 1); 13435 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 13436 S->getNextFunctionPrototypeIndex()); 13437 13438 // Add the parameter declaration into this scope. 13439 S->AddDecl(New); 13440 if (II) 13441 IdResolver.AddDecl(New); 13442 13443 ProcessDeclAttributes(S, New, D); 13444 13445 if (D.getDeclSpec().isModulePrivateSpecified()) 13446 Diag(New->getLocation(), diag::err_module_private_local) 13447 << 1 << New->getDeclName() 13448 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 13449 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 13450 13451 if (New->hasAttr<BlocksAttr>()) { 13452 Diag(New->getLocation(), diag::err_block_on_nonlocal); 13453 } 13454 13455 if (getLangOpts().OpenCL) 13456 deduceOpenCLAddressSpace(New); 13457 13458 return New; 13459 } 13460 13461 /// Synthesizes a variable for a parameter arising from a 13462 /// typedef. 13463 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 13464 SourceLocation Loc, 13465 QualType T) { 13466 /* FIXME: setting StartLoc == Loc. 13467 Would it be worth to modify callers so as to provide proper source 13468 location for the unnamed parameters, embedding the parameter's type? */ 13469 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 13470 T, Context.getTrivialTypeSourceInfo(T, Loc), 13471 SC_None, nullptr); 13472 Param->setImplicit(); 13473 return Param; 13474 } 13475 13476 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 13477 // Don't diagnose unused-parameter errors in template instantiations; we 13478 // will already have done so in the template itself. 13479 if (inTemplateInstantiation()) 13480 return; 13481 13482 for (const ParmVarDecl *Parameter : Parameters) { 13483 if (!Parameter->isReferenced() && Parameter->getDeclName() && 13484 !Parameter->hasAttr<UnusedAttr>()) { 13485 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 13486 << Parameter->getDeclName(); 13487 } 13488 } 13489 } 13490 13491 void Sema::DiagnoseSizeOfParametersAndReturnValue( 13492 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 13493 if (LangOpts.NumLargeByValueCopy == 0) // No check. 13494 return; 13495 13496 // Warn if the return value is pass-by-value and larger than the specified 13497 // threshold. 13498 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 13499 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 13500 if (Size > LangOpts.NumLargeByValueCopy) 13501 Diag(D->getLocation(), diag::warn_return_value_size) 13502 << D->getDeclName() << Size; 13503 } 13504 13505 // Warn if any parameter is pass-by-value and larger than the specified 13506 // threshold. 13507 for (const ParmVarDecl *Parameter : Parameters) { 13508 QualType T = Parameter->getType(); 13509 if (T->isDependentType() || !T.isPODType(Context)) 13510 continue; 13511 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 13512 if (Size > LangOpts.NumLargeByValueCopy) 13513 Diag(Parameter->getLocation(), diag::warn_parameter_size) 13514 << Parameter->getDeclName() << Size; 13515 } 13516 } 13517 13518 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 13519 SourceLocation NameLoc, IdentifierInfo *Name, 13520 QualType T, TypeSourceInfo *TSInfo, 13521 StorageClass SC) { 13522 // In ARC, infer a lifetime qualifier for appropriate parameter types. 13523 if (getLangOpts().ObjCAutoRefCount && 13524 T.getObjCLifetime() == Qualifiers::OCL_None && 13525 T->isObjCLifetimeType()) { 13526 13527 Qualifiers::ObjCLifetime lifetime; 13528 13529 // Special cases for arrays: 13530 // - if it's const, use __unsafe_unretained 13531 // - otherwise, it's an error 13532 if (T->isArrayType()) { 13533 if (!T.isConstQualified()) { 13534 if (DelayedDiagnostics.shouldDelayDiagnostics()) 13535 DelayedDiagnostics.add( 13536 sema::DelayedDiagnostic::makeForbiddenType( 13537 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 13538 else 13539 Diag(NameLoc, diag::err_arc_array_param_no_ownership) 13540 << TSInfo->getTypeLoc().getSourceRange(); 13541 } 13542 lifetime = Qualifiers::OCL_ExplicitNone; 13543 } else { 13544 lifetime = T->getObjCARCImplicitLifetime(); 13545 } 13546 T = Context.getLifetimeQualifiedType(T, lifetime); 13547 } 13548 13549 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 13550 Context.getAdjustedParameterType(T), 13551 TSInfo, SC, nullptr); 13552 13553 // Make a note if we created a new pack in the scope of a lambda, so that 13554 // we know that references to that pack must also be expanded within the 13555 // lambda scope. 13556 if (New->isParameterPack()) 13557 if (auto *LSI = getEnclosingLambda()) 13558 LSI->LocalPacks.push_back(New); 13559 13560 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() || 13561 New->getType().hasNonTrivialToPrimitiveCopyCUnion()) 13562 checkNonTrivialCUnion(New->getType(), New->getLocation(), 13563 NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy); 13564 13565 // Parameters can not be abstract class types. 13566 // For record types, this is done by the AbstractClassUsageDiagnoser once 13567 // the class has been completely parsed. 13568 if (!CurContext->isRecord() && 13569 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 13570 AbstractParamType)) 13571 New->setInvalidDecl(); 13572 13573 // Parameter declarators cannot be interface types. All ObjC objects are 13574 // passed by reference. 13575 if (T->isObjCObjectType()) { 13576 SourceLocation TypeEndLoc = 13577 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc()); 13578 Diag(NameLoc, 13579 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 13580 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 13581 T = Context.getObjCObjectPointerType(T); 13582 New->setType(T); 13583 } 13584 13585 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 13586 // duration shall not be qualified by an address-space qualifier." 13587 // Since all parameters have automatic store duration, they can not have 13588 // an address space. 13589 if (T.getAddressSpace() != LangAS::Default && 13590 // OpenCL allows function arguments declared to be an array of a type 13591 // to be qualified with an address space. 13592 !(getLangOpts().OpenCL && 13593 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) { 13594 Diag(NameLoc, diag::err_arg_with_address_space); 13595 New->setInvalidDecl(); 13596 } 13597 13598 return New; 13599 } 13600 13601 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 13602 SourceLocation LocAfterDecls) { 13603 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 13604 13605 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 13606 // for a K&R function. 13607 if (!FTI.hasPrototype) { 13608 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 13609 --i; 13610 if (FTI.Params[i].Param == nullptr) { 13611 SmallString<256> Code; 13612 llvm::raw_svector_ostream(Code) 13613 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 13614 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 13615 << FTI.Params[i].Ident 13616 << FixItHint::CreateInsertion(LocAfterDecls, Code); 13617 13618 // Implicitly declare the argument as type 'int' for lack of a better 13619 // type. 13620 AttributeFactory attrs; 13621 DeclSpec DS(attrs); 13622 const char* PrevSpec; // unused 13623 unsigned DiagID; // unused 13624 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 13625 DiagID, Context.getPrintingPolicy()); 13626 // Use the identifier location for the type source range. 13627 DS.SetRangeStart(FTI.Params[i].IdentLoc); 13628 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 13629 Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext); 13630 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 13631 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 13632 } 13633 } 13634 } 13635 } 13636 13637 Decl * 13638 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 13639 MultiTemplateParamsArg TemplateParameterLists, 13640 SkipBodyInfo *SkipBody) { 13641 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 13642 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 13643 Scope *ParentScope = FnBodyScope->getParent(); 13644 13645 // Check if we are in an `omp begin/end declare variant` scope. If we are, and 13646 // we define a non-templated function definition, we will create a declaration 13647 // instead (=BaseFD), and emit the definition with a mangled name afterwards. 13648 // The base function declaration will have the equivalent of an `omp declare 13649 // variant` annotation which specifies the mangled definition as a 13650 // specialization function under the OpenMP context defined as part of the 13651 // `omp begin declare variant`. 13652 FunctionDecl *BaseFD = nullptr; 13653 if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope() && 13654 TemplateParameterLists.empty()) 13655 BaseFD = ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( 13656 ParentScope, D); 13657 13658 D.setFunctionDefinitionKind(FDK_Definition); 13659 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 13660 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 13661 13662 if (BaseFD) 13663 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope( 13664 cast<FunctionDecl>(Dcl), BaseFD); 13665 13666 return Dcl; 13667 } 13668 13669 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 13670 Consumer.HandleInlineFunctionDefinition(D); 13671 } 13672 13673 static bool 13674 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 13675 const FunctionDecl *&PossiblePrototype) { 13676 // Don't warn about invalid declarations. 13677 if (FD->isInvalidDecl()) 13678 return false; 13679 13680 // Or declarations that aren't global. 13681 if (!FD->isGlobal()) 13682 return false; 13683 13684 // Don't warn about C++ member functions. 13685 if (isa<CXXMethodDecl>(FD)) 13686 return false; 13687 13688 // Don't warn about 'main'. 13689 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext())) 13690 if (IdentifierInfo *II = FD->getIdentifier()) 13691 if (II->isStr("main")) 13692 return false; 13693 13694 // Don't warn about inline functions. 13695 if (FD->isInlined()) 13696 return false; 13697 13698 // Don't warn about function templates. 13699 if (FD->getDescribedFunctionTemplate()) 13700 return false; 13701 13702 // Don't warn about function template specializations. 13703 if (FD->isFunctionTemplateSpecialization()) 13704 return false; 13705 13706 // Don't warn for OpenCL kernels. 13707 if (FD->hasAttr<OpenCLKernelAttr>()) 13708 return false; 13709 13710 // Don't warn on explicitly deleted functions. 13711 if (FD->isDeleted()) 13712 return false; 13713 13714 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 13715 Prev; Prev = Prev->getPreviousDecl()) { 13716 // Ignore any declarations that occur in function or method 13717 // scope, because they aren't visible from the header. 13718 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 13719 continue; 13720 13721 PossiblePrototype = Prev; 13722 return Prev->getType()->isFunctionNoProtoType(); 13723 } 13724 13725 return true; 13726 } 13727 13728 void 13729 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 13730 const FunctionDecl *EffectiveDefinition, 13731 SkipBodyInfo *SkipBody) { 13732 const FunctionDecl *Definition = EffectiveDefinition; 13733 if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) { 13734 // If this is a friend function defined in a class template, it does not 13735 // have a body until it is used, nevertheless it is a definition, see 13736 // [temp.inst]p2: 13737 // 13738 // ... for the purpose of determining whether an instantiated redeclaration 13739 // is valid according to [basic.def.odr] and [class.mem], a declaration that 13740 // corresponds to a definition in the template is considered to be a 13741 // definition. 13742 // 13743 // The following code must produce redefinition error: 13744 // 13745 // template<typename T> struct C20 { friend void func_20() {} }; 13746 // C20<int> c20i; 13747 // void func_20() {} 13748 // 13749 for (auto I : FD->redecls()) { 13750 if (I != FD && !I->isInvalidDecl() && 13751 I->getFriendObjectKind() != Decl::FOK_None) { 13752 if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) { 13753 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { 13754 // A merged copy of the same function, instantiated as a member of 13755 // the same class, is OK. 13756 if (declaresSameEntity(OrigFD, Original) && 13757 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()), 13758 cast<Decl>(FD->getLexicalDeclContext()))) 13759 continue; 13760 } 13761 13762 if (Original->isThisDeclarationADefinition()) { 13763 Definition = I; 13764 break; 13765 } 13766 } 13767 } 13768 } 13769 } 13770 13771 if (!Definition) 13772 // Similar to friend functions a friend function template may be a 13773 // definition and do not have a body if it is instantiated in a class 13774 // template. 13775 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) { 13776 for (auto I : FTD->redecls()) { 13777 auto D = cast<FunctionTemplateDecl>(I); 13778 if (D != FTD) { 13779 assert(!D->isThisDeclarationADefinition() && 13780 "More than one definition in redeclaration chain"); 13781 if (D->getFriendObjectKind() != Decl::FOK_None) 13782 if (FunctionTemplateDecl *FT = 13783 D->getInstantiatedFromMemberTemplate()) { 13784 if (FT->isThisDeclarationADefinition()) { 13785 Definition = D->getTemplatedDecl(); 13786 break; 13787 } 13788 } 13789 } 13790 } 13791 } 13792 13793 if (!Definition) 13794 return; 13795 13796 if (canRedefineFunction(Definition, getLangOpts())) 13797 return; 13798 13799 // Don't emit an error when this is redefinition of a typo-corrected 13800 // definition. 13801 if (TypoCorrectedFunctionDefinitions.count(Definition)) 13802 return; 13803 13804 // If we don't have a visible definition of the function, and it's inline or 13805 // a template, skip the new definition. 13806 if (SkipBody && !hasVisibleDefinition(Definition) && 13807 (Definition->getFormalLinkage() == InternalLinkage || 13808 Definition->isInlined() || 13809 Definition->getDescribedFunctionTemplate() || 13810 Definition->getNumTemplateParameterLists())) { 13811 SkipBody->ShouldSkip = true; 13812 SkipBody->Previous = const_cast<FunctionDecl*>(Definition); 13813 if (auto *TD = Definition->getDescribedFunctionTemplate()) 13814 makeMergedDefinitionVisible(TD); 13815 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 13816 return; 13817 } 13818 13819 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 13820 Definition->getStorageClass() == SC_Extern) 13821 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 13822 << FD->getDeclName() << getLangOpts().CPlusPlus; 13823 else 13824 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 13825 13826 Diag(Definition->getLocation(), diag::note_previous_definition); 13827 FD->setInvalidDecl(); 13828 } 13829 13830 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 13831 Sema &S) { 13832 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 13833 13834 LambdaScopeInfo *LSI = S.PushLambdaScope(); 13835 LSI->CallOperator = CallOperator; 13836 LSI->Lambda = LambdaClass; 13837 LSI->ReturnType = CallOperator->getReturnType(); 13838 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 13839 13840 if (LCD == LCD_None) 13841 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 13842 else if (LCD == LCD_ByCopy) 13843 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 13844 else if (LCD == LCD_ByRef) 13845 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 13846 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 13847 13848 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 13849 LSI->Mutable = !CallOperator->isConst(); 13850 13851 // Add the captures to the LSI so they can be noted as already 13852 // captured within tryCaptureVar. 13853 auto I = LambdaClass->field_begin(); 13854 for (const auto &C : LambdaClass->captures()) { 13855 if (C.capturesVariable()) { 13856 VarDecl *VD = C.getCapturedVar(); 13857 if (VD->isInitCapture()) 13858 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 13859 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 13860 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 13861 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 13862 /*EllipsisLoc*/C.isPackExpansion() 13863 ? C.getEllipsisLoc() : SourceLocation(), 13864 I->getType(), /*Invalid*/false); 13865 13866 } else if (C.capturesThis()) { 13867 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(), 13868 C.getCaptureKind() == LCK_StarThis); 13869 } else { 13870 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(), 13871 I->getType()); 13872 } 13873 ++I; 13874 } 13875 } 13876 13877 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 13878 SkipBodyInfo *SkipBody) { 13879 if (!D) { 13880 // Parsing the function declaration failed in some way. Push on a fake scope 13881 // anyway so we can try to parse the function body. 13882 PushFunctionScope(); 13883 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 13884 return D; 13885 } 13886 13887 FunctionDecl *FD = nullptr; 13888 13889 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 13890 FD = FunTmpl->getTemplatedDecl(); 13891 else 13892 FD = cast<FunctionDecl>(D); 13893 13894 // Do not push if it is a lambda because one is already pushed when building 13895 // the lambda in ActOnStartOfLambdaDefinition(). 13896 if (!isLambdaCallOperator(FD)) 13897 PushExpressionEvaluationContext( 13898 FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated 13899 : ExprEvalContexts.back().Context); 13900 13901 // Check for defining attributes before the check for redefinition. 13902 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 13903 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 13904 FD->dropAttr<AliasAttr>(); 13905 FD->setInvalidDecl(); 13906 } 13907 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 13908 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 13909 FD->dropAttr<IFuncAttr>(); 13910 FD->setInvalidDecl(); 13911 } 13912 13913 // See if this is a redefinition. If 'will have body' is already set, then 13914 // these checks were already performed when it was set. 13915 if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) { 13916 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 13917 13918 // If we're skipping the body, we're done. Don't enter the scope. 13919 if (SkipBody && SkipBody->ShouldSkip) 13920 return D; 13921 } 13922 13923 // Mark this function as "will have a body eventually". This lets users to 13924 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 13925 // this function. 13926 FD->setWillHaveBody(); 13927 13928 // If we are instantiating a generic lambda call operator, push 13929 // a LambdaScopeInfo onto the function stack. But use the information 13930 // that's already been calculated (ActOnLambdaExpr) to prime the current 13931 // LambdaScopeInfo. 13932 // When the template operator is being specialized, the LambdaScopeInfo, 13933 // has to be properly restored so that tryCaptureVariable doesn't try 13934 // and capture any new variables. In addition when calculating potential 13935 // captures during transformation of nested lambdas, it is necessary to 13936 // have the LSI properly restored. 13937 if (isGenericLambdaCallOperatorSpecialization(FD)) { 13938 assert(inTemplateInstantiation() && 13939 "There should be an active template instantiation on the stack " 13940 "when instantiating a generic lambda!"); 13941 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 13942 } else { 13943 // Enter a new function scope 13944 PushFunctionScope(); 13945 } 13946 13947 // Builtin functions cannot be defined. 13948 if (unsigned BuiltinID = FD->getBuiltinID()) { 13949 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 13950 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 13951 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 13952 FD->setInvalidDecl(); 13953 } 13954 } 13955 13956 // The return type of a function definition must be complete 13957 // (C99 6.9.1p3, C++ [dcl.fct]p6). 13958 QualType ResultType = FD->getReturnType(); 13959 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 13960 !FD->isInvalidDecl() && 13961 RequireCompleteType(FD->getLocation(), ResultType, 13962 diag::err_func_def_incomplete_result)) 13963 FD->setInvalidDecl(); 13964 13965 if (FnBodyScope) 13966 PushDeclContext(FnBodyScope, FD); 13967 13968 // Check the validity of our function parameters 13969 CheckParmsForFunctionDef(FD->parameters(), 13970 /*CheckParameterNames=*/true); 13971 13972 // Add non-parameter declarations already in the function to the current 13973 // scope. 13974 if (FnBodyScope) { 13975 for (Decl *NPD : FD->decls()) { 13976 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 13977 if (!NonParmDecl) 13978 continue; 13979 assert(!isa<ParmVarDecl>(NonParmDecl) && 13980 "parameters should not be in newly created FD yet"); 13981 13982 // If the decl has a name, make it accessible in the current scope. 13983 if (NonParmDecl->getDeclName()) 13984 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 13985 13986 // Similarly, dive into enums and fish their constants out, making them 13987 // accessible in this scope. 13988 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 13989 for (auto *EI : ED->enumerators()) 13990 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 13991 } 13992 } 13993 } 13994 13995 // Introduce our parameters into the function scope 13996 for (auto Param : FD->parameters()) { 13997 Param->setOwningFunction(FD); 13998 13999 // If this has an identifier, add it to the scope stack. 14000 if (Param->getIdentifier() && FnBodyScope) { 14001 CheckShadow(FnBodyScope, Param); 14002 14003 PushOnScopeChains(Param, FnBodyScope); 14004 } 14005 } 14006 14007 // Ensure that the function's exception specification is instantiated. 14008 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 14009 ResolveExceptionSpec(D->getLocation(), FPT); 14010 14011 // dllimport cannot be applied to non-inline function definitions. 14012 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 14013 !FD->isTemplateInstantiation()) { 14014 assert(!FD->hasAttr<DLLExportAttr>()); 14015 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 14016 FD->setInvalidDecl(); 14017 return D; 14018 } 14019 // We want to attach documentation to original Decl (which might be 14020 // a function template). 14021 ActOnDocumentableDecl(D); 14022 if (getCurLexicalContext()->isObjCContainer() && 14023 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 14024 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 14025 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 14026 14027 return D; 14028 } 14029 14030 /// Given the set of return statements within a function body, 14031 /// compute the variables that are subject to the named return value 14032 /// optimization. 14033 /// 14034 /// Each of the variables that is subject to the named return value 14035 /// optimization will be marked as NRVO variables in the AST, and any 14036 /// return statement that has a marked NRVO variable as its NRVO candidate can 14037 /// use the named return value optimization. 14038 /// 14039 /// This function applies a very simplistic algorithm for NRVO: if every return 14040 /// statement in the scope of a variable has the same NRVO candidate, that 14041 /// candidate is an NRVO variable. 14042 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 14043 ReturnStmt **Returns = Scope->Returns.data(); 14044 14045 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 14046 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 14047 if (!NRVOCandidate->isNRVOVariable()) 14048 Returns[I]->setNRVOCandidate(nullptr); 14049 } 14050 } 14051 } 14052 14053 bool Sema::canDelayFunctionBody(const Declarator &D) { 14054 // We can't delay parsing the body of a constexpr function template (yet). 14055 if (D.getDeclSpec().hasConstexprSpecifier()) 14056 return false; 14057 14058 // We can't delay parsing the body of a function template with a deduced 14059 // return type (yet). 14060 if (D.getDeclSpec().hasAutoTypeSpec()) { 14061 // If the placeholder introduces a non-deduced trailing return type, 14062 // we can still delay parsing it. 14063 if (D.getNumTypeObjects()) { 14064 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 14065 if (Outer.Kind == DeclaratorChunk::Function && 14066 Outer.Fun.hasTrailingReturnType()) { 14067 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 14068 return Ty.isNull() || !Ty->isUndeducedType(); 14069 } 14070 } 14071 return false; 14072 } 14073 14074 return true; 14075 } 14076 14077 bool Sema::canSkipFunctionBody(Decl *D) { 14078 // We cannot skip the body of a function (or function template) which is 14079 // constexpr, since we may need to evaluate its body in order to parse the 14080 // rest of the file. 14081 // We cannot skip the body of a function with an undeduced return type, 14082 // because any callers of that function need to know the type. 14083 if (const FunctionDecl *FD = D->getAsFunction()) { 14084 if (FD->isConstexpr()) 14085 return false; 14086 // We can't simply call Type::isUndeducedType here, because inside template 14087 // auto can be deduced to a dependent type, which is not considered 14088 // "undeduced". 14089 if (FD->getReturnType()->getContainedDeducedType()) 14090 return false; 14091 } 14092 return Consumer.shouldSkipFunctionBody(D); 14093 } 14094 14095 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 14096 if (!Decl) 14097 return nullptr; 14098 if (FunctionDecl *FD = Decl->getAsFunction()) 14099 FD->setHasSkippedBody(); 14100 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) 14101 MD->setHasSkippedBody(); 14102 return Decl; 14103 } 14104 14105 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 14106 return ActOnFinishFunctionBody(D, BodyArg, false); 14107 } 14108 14109 /// RAII object that pops an ExpressionEvaluationContext when exiting a function 14110 /// body. 14111 class ExitFunctionBodyRAII { 14112 public: 14113 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {} 14114 ~ExitFunctionBodyRAII() { 14115 if (!IsLambda) 14116 S.PopExpressionEvaluationContext(); 14117 } 14118 14119 private: 14120 Sema &S; 14121 bool IsLambda = false; 14122 }; 14123 14124 static void diagnoseImplicitlyRetainedSelf(Sema &S) { 14125 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo; 14126 14127 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) { 14128 if (EscapeInfo.count(BD)) 14129 return EscapeInfo[BD]; 14130 14131 bool R = false; 14132 const BlockDecl *CurBD = BD; 14133 14134 do { 14135 R = !CurBD->doesNotEscape(); 14136 if (R) 14137 break; 14138 CurBD = CurBD->getParent()->getInnermostBlockDecl(); 14139 } while (CurBD); 14140 14141 return EscapeInfo[BD] = R; 14142 }; 14143 14144 // If the location where 'self' is implicitly retained is inside a escaping 14145 // block, emit a diagnostic. 14146 for (const std::pair<SourceLocation, const BlockDecl *> &P : 14147 S.ImplicitlyRetainedSelfLocs) 14148 if (IsOrNestedInEscapingBlock(P.second)) 14149 S.Diag(P.first, diag::warn_implicitly_retains_self) 14150 << FixItHint::CreateInsertion(P.first, "self->"); 14151 } 14152 14153 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 14154 bool IsInstantiation) { 14155 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 14156 14157 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 14158 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 14159 14160 if (getLangOpts().Coroutines && getCurFunction()->isCoroutine()) 14161 CheckCompletedCoroutineBody(FD, Body); 14162 14163 // Do not call PopExpressionEvaluationContext() if it is a lambda because one 14164 // is already popped when finishing the lambda in BuildLambdaExpr(). This is 14165 // meant to pop the context added in ActOnStartOfFunctionDef(). 14166 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD)); 14167 14168 if (FD) { 14169 FD->setBody(Body); 14170 FD->setWillHaveBody(false); 14171 14172 if (getLangOpts().CPlusPlus14) { 14173 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 14174 FD->getReturnType()->isUndeducedType()) { 14175 // If the function has a deduced result type but contains no 'return' 14176 // statements, the result type as written must be exactly 'auto', and 14177 // the deduced result type is 'void'. 14178 if (!FD->getReturnType()->getAs<AutoType>()) { 14179 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 14180 << FD->getReturnType(); 14181 FD->setInvalidDecl(); 14182 } else { 14183 // Substitute 'void' for the 'auto' in the type. 14184 TypeLoc ResultType = getReturnTypeLoc(FD); 14185 Context.adjustDeducedFunctionResultType( 14186 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 14187 } 14188 } 14189 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 14190 // In C++11, we don't use 'auto' deduction rules for lambda call 14191 // operators because we don't support return type deduction. 14192 auto *LSI = getCurLambda(); 14193 if (LSI->HasImplicitReturnType) { 14194 deduceClosureReturnType(*LSI); 14195 14196 // C++11 [expr.prim.lambda]p4: 14197 // [...] if there are no return statements in the compound-statement 14198 // [the deduced type is] the type void 14199 QualType RetType = 14200 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 14201 14202 // Update the return type to the deduced type. 14203 const auto *Proto = FD->getType()->castAs<FunctionProtoType>(); 14204 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 14205 Proto->getExtProtoInfo())); 14206 } 14207 } 14208 14209 // If the function implicitly returns zero (like 'main') or is naked, 14210 // don't complain about missing return statements. 14211 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 14212 WP.disableCheckFallThrough(); 14213 14214 // MSVC permits the use of pure specifier (=0) on function definition, 14215 // defined at class scope, warn about this non-standard construct. 14216 if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine()) 14217 Diag(FD->getLocation(), diag::ext_pure_function_definition); 14218 14219 if (!FD->isInvalidDecl()) { 14220 // Don't diagnose unused parameters of defaulted or deleted functions. 14221 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody()) 14222 DiagnoseUnusedParameters(FD->parameters()); 14223 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 14224 FD->getReturnType(), FD); 14225 14226 // If this is a structor, we need a vtable. 14227 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 14228 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 14229 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 14230 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 14231 14232 // Try to apply the named return value optimization. We have to check 14233 // if we can do this here because lambdas keep return statements around 14234 // to deduce an implicit return type. 14235 if (FD->getReturnType()->isRecordType() && 14236 (!getLangOpts().CPlusPlus || !FD->isDependentContext())) 14237 computeNRVO(Body, getCurFunction()); 14238 } 14239 14240 // GNU warning -Wmissing-prototypes: 14241 // Warn if a global function is defined without a previous 14242 // prototype declaration. This warning is issued even if the 14243 // definition itself provides a prototype. The aim is to detect 14244 // global functions that fail to be declared in header files. 14245 const FunctionDecl *PossiblePrototype = nullptr; 14246 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) { 14247 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 14248 14249 if (PossiblePrototype) { 14250 // We found a declaration that is not a prototype, 14251 // but that could be a zero-parameter prototype 14252 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) { 14253 TypeLoc TL = TI->getTypeLoc(); 14254 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 14255 Diag(PossiblePrototype->getLocation(), 14256 diag::note_declaration_not_a_prototype) 14257 << (FD->getNumParams() != 0) 14258 << (FD->getNumParams() == 0 14259 ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void") 14260 : FixItHint{}); 14261 } 14262 } else { 14263 // Returns true if the token beginning at this Loc is `const`. 14264 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM, 14265 const LangOptions &LangOpts) { 14266 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); 14267 if (LocInfo.first.isInvalid()) 14268 return false; 14269 14270 bool Invalid = false; 14271 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid); 14272 if (Invalid) 14273 return false; 14274 14275 if (LocInfo.second > Buffer.size()) 14276 return false; 14277 14278 const char *LexStart = Buffer.data() + LocInfo.second; 14279 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second); 14280 14281 return StartTok.consume_front("const") && 14282 (StartTok.empty() || isWhitespace(StartTok[0]) || 14283 StartTok.startswith("/*") || StartTok.startswith("//")); 14284 }; 14285 14286 auto findBeginLoc = [&]() { 14287 // If the return type has `const` qualifier, we want to insert 14288 // `static` before `const` (and not before the typename). 14289 if ((FD->getReturnType()->isAnyPointerType() && 14290 FD->getReturnType()->getPointeeType().isConstQualified()) || 14291 FD->getReturnType().isConstQualified()) { 14292 // But only do this if we can determine where the `const` is. 14293 14294 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(), 14295 getLangOpts())) 14296 14297 return FD->getBeginLoc(); 14298 } 14299 return FD->getTypeSpecStartLoc(); 14300 }; 14301 Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 14302 << /* function */ 1 14303 << (FD->getStorageClass() == SC_None 14304 ? FixItHint::CreateInsertion(findBeginLoc(), "static ") 14305 : FixItHint{}); 14306 } 14307 14308 // GNU warning -Wstrict-prototypes 14309 // Warn if K&R function is defined without a previous declaration. 14310 // This warning is issued only if the definition itself does not provide 14311 // a prototype. Only K&R definitions do not provide a prototype. 14312 if (!FD->hasWrittenPrototype()) { 14313 TypeSourceInfo *TI = FD->getTypeSourceInfo(); 14314 TypeLoc TL = TI->getTypeLoc(); 14315 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); 14316 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2; 14317 } 14318 } 14319 14320 // Warn on CPUDispatch with an actual body. 14321 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body) 14322 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body)) 14323 if (!CmpndBody->body_empty()) 14324 Diag(CmpndBody->body_front()->getBeginLoc(), 14325 diag::warn_dispatch_body_ignored); 14326 14327 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 14328 const CXXMethodDecl *KeyFunction; 14329 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 14330 MD->isVirtual() && 14331 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 14332 MD == KeyFunction->getCanonicalDecl()) { 14333 // Update the key-function state if necessary for this ABI. 14334 if (FD->isInlined() && 14335 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 14336 Context.setNonKeyFunction(MD); 14337 14338 // If the newly-chosen key function is already defined, then we 14339 // need to mark the vtable as used retroactively. 14340 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 14341 const FunctionDecl *Definition; 14342 if (KeyFunction && KeyFunction->isDefined(Definition)) 14343 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 14344 } else { 14345 // We just defined they key function; mark the vtable as used. 14346 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 14347 } 14348 } 14349 } 14350 14351 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 14352 "Function parsing confused"); 14353 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 14354 assert(MD == getCurMethodDecl() && "Method parsing confused"); 14355 MD->setBody(Body); 14356 if (!MD->isInvalidDecl()) { 14357 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 14358 MD->getReturnType(), MD); 14359 14360 if (Body) 14361 computeNRVO(Body, getCurFunction()); 14362 } 14363 if (getCurFunction()->ObjCShouldCallSuper) { 14364 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call) 14365 << MD->getSelector().getAsString(); 14366 getCurFunction()->ObjCShouldCallSuper = false; 14367 } 14368 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 14369 const ObjCMethodDecl *InitMethod = nullptr; 14370 bool isDesignated = 14371 MD->isDesignatedInitializerForTheInterface(&InitMethod); 14372 assert(isDesignated && InitMethod); 14373 (void)isDesignated; 14374 14375 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 14376 auto IFace = MD->getClassInterface(); 14377 if (!IFace) 14378 return false; 14379 auto SuperD = IFace->getSuperClass(); 14380 if (!SuperD) 14381 return false; 14382 return SuperD->getIdentifier() == 14383 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 14384 }; 14385 // Don't issue this warning for unavailable inits or direct subclasses 14386 // of NSObject. 14387 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 14388 Diag(MD->getLocation(), 14389 diag::warn_objc_designated_init_missing_super_call); 14390 Diag(InitMethod->getLocation(), 14391 diag::note_objc_designated_init_marked_here); 14392 } 14393 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 14394 } 14395 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 14396 // Don't issue this warning for unavaialable inits. 14397 if (!MD->isUnavailable()) 14398 Diag(MD->getLocation(), 14399 diag::warn_objc_secondary_init_missing_init_call); 14400 getCurFunction()->ObjCWarnForNoInitDelegation = false; 14401 } 14402 14403 diagnoseImplicitlyRetainedSelf(*this); 14404 } else { 14405 // Parsing the function declaration failed in some way. Pop the fake scope 14406 // we pushed on. 14407 PopFunctionScopeInfo(ActivePolicy, dcl); 14408 return nullptr; 14409 } 14410 14411 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 14412 DiagnoseUnguardedAvailabilityViolations(dcl); 14413 14414 assert(!getCurFunction()->ObjCShouldCallSuper && 14415 "This should only be set for ObjC methods, which should have been " 14416 "handled in the block above."); 14417 14418 // Verify and clean out per-function state. 14419 if (Body && (!FD || !FD->isDefaulted())) { 14420 // C++ constructors that have function-try-blocks can't have return 14421 // statements in the handlers of that block. (C++ [except.handle]p14) 14422 // Verify this. 14423 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 14424 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 14425 14426 // Verify that gotos and switch cases don't jump into scopes illegally. 14427 if (getCurFunction()->NeedsScopeChecking() && 14428 !PP.isCodeCompletionEnabled()) 14429 DiagnoseInvalidJumps(Body); 14430 14431 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 14432 if (!Destructor->getParent()->isDependentType()) 14433 CheckDestructor(Destructor); 14434 14435 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 14436 Destructor->getParent()); 14437 } 14438 14439 // If any errors have occurred, clear out any temporaries that may have 14440 // been leftover. This ensures that these temporaries won't be picked up for 14441 // deletion in some later function. 14442 if (getDiagnostics().hasUncompilableErrorOccurred() || 14443 getDiagnostics().getSuppressAllDiagnostics()) { 14444 DiscardCleanupsInEvaluationContext(); 14445 } 14446 if (!getDiagnostics().hasUncompilableErrorOccurred() && 14447 !isa<FunctionTemplateDecl>(dcl)) { 14448 // Since the body is valid, issue any analysis-based warnings that are 14449 // enabled. 14450 ActivePolicy = &WP; 14451 } 14452 14453 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 14454 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose)) 14455 FD->setInvalidDecl(); 14456 14457 if (FD && FD->hasAttr<NakedAttr>()) { 14458 for (const Stmt *S : Body->children()) { 14459 // Allow local register variables without initializer as they don't 14460 // require prologue. 14461 bool RegisterVariables = false; 14462 if (auto *DS = dyn_cast<DeclStmt>(S)) { 14463 for (const auto *Decl : DS->decls()) { 14464 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 14465 RegisterVariables = 14466 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 14467 if (!RegisterVariables) 14468 break; 14469 } 14470 } 14471 } 14472 if (RegisterVariables) 14473 continue; 14474 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 14475 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function); 14476 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 14477 FD->setInvalidDecl(); 14478 break; 14479 } 14480 } 14481 } 14482 14483 assert(ExprCleanupObjects.size() == 14484 ExprEvalContexts.back().NumCleanupObjects && 14485 "Leftover temporaries in function"); 14486 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function"); 14487 assert(MaybeODRUseExprs.empty() && 14488 "Leftover expressions for odr-use checking"); 14489 } 14490 14491 if (!IsInstantiation) 14492 PopDeclContext(); 14493 14494 PopFunctionScopeInfo(ActivePolicy, dcl); 14495 // If any errors have occurred, clear out any temporaries that may have 14496 // been leftover. This ensures that these temporaries won't be picked up for 14497 // deletion in some later function. 14498 if (getDiagnostics().hasUncompilableErrorOccurred()) { 14499 DiscardCleanupsInEvaluationContext(); 14500 } 14501 14502 if (LangOpts.OpenMP || LangOpts.CUDA || LangOpts.SYCLIsDevice) { 14503 auto ES = getEmissionStatus(FD); 14504 if (ES == Sema::FunctionEmissionStatus::Emitted || 14505 ES == Sema::FunctionEmissionStatus::Unknown) 14506 DeclsToCheckForDeferredDiags.push_back(FD); 14507 } 14508 14509 return dcl; 14510 } 14511 14512 /// When we finish delayed parsing of an attribute, we must attach it to the 14513 /// relevant Decl. 14514 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 14515 ParsedAttributes &Attrs) { 14516 // Always attach attributes to the underlying decl. 14517 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 14518 D = TD->getTemplatedDecl(); 14519 ProcessDeclAttributeList(S, D, Attrs); 14520 14521 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 14522 if (Method->isStatic()) 14523 checkThisInStaticMemberFunctionAttributes(Method); 14524 } 14525 14526 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 14527 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 14528 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 14529 IdentifierInfo &II, Scope *S) { 14530 // Find the scope in which the identifier is injected and the corresponding 14531 // DeclContext. 14532 // FIXME: C89 does not say what happens if there is no enclosing block scope. 14533 // In that case, we inject the declaration into the translation unit scope 14534 // instead. 14535 Scope *BlockScope = S; 14536 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) 14537 BlockScope = BlockScope->getParent(); 14538 14539 Scope *ContextScope = BlockScope; 14540 while (!ContextScope->getEntity()) 14541 ContextScope = ContextScope->getParent(); 14542 ContextRAII SavedContext(*this, ContextScope->getEntity()); 14543 14544 // Before we produce a declaration for an implicitly defined 14545 // function, see whether there was a locally-scoped declaration of 14546 // this name as a function or variable. If so, use that 14547 // (non-visible) declaration, and complain about it. 14548 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); 14549 if (ExternCPrev) { 14550 // We still need to inject the function into the enclosing block scope so 14551 // that later (non-call) uses can see it. 14552 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); 14553 14554 // C89 footnote 38: 14555 // If in fact it is not defined as having type "function returning int", 14556 // the behavior is undefined. 14557 if (!isa<FunctionDecl>(ExternCPrev) || 14558 !Context.typesAreCompatible( 14559 cast<FunctionDecl>(ExternCPrev)->getType(), 14560 Context.getFunctionNoProtoType(Context.IntTy))) { 14561 Diag(Loc, diag::ext_use_out_of_scope_declaration) 14562 << ExternCPrev << !getLangOpts().C99; 14563 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 14564 return ExternCPrev; 14565 } 14566 } 14567 14568 // Extension in C99. Legal in C90, but warn about it. 14569 unsigned diag_id; 14570 if (II.getName().startswith("__builtin_")) 14571 diag_id = diag::warn_builtin_unknown; 14572 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. 14573 else if (getLangOpts().OpenCL) 14574 diag_id = diag::err_opencl_implicit_function_decl; 14575 else if (getLangOpts().C99) 14576 diag_id = diag::ext_implicit_function_decl; 14577 else 14578 diag_id = diag::warn_implicit_function_decl; 14579 Diag(Loc, diag_id) << &II; 14580 14581 // If we found a prior declaration of this function, don't bother building 14582 // another one. We've already pushed that one into scope, so there's nothing 14583 // more to do. 14584 if (ExternCPrev) 14585 return ExternCPrev; 14586 14587 // Because typo correction is expensive, only do it if the implicit 14588 // function declaration is going to be treated as an error. 14589 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 14590 TypoCorrection Corrected; 14591 DeclFilterCCC<FunctionDecl> CCC{}; 14592 if (S && (Corrected = 14593 CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName, 14594 S, nullptr, CCC, CTK_NonError))) 14595 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 14596 /*ErrorRecovery*/false); 14597 } 14598 14599 // Set a Declarator for the implicit definition: int foo(); 14600 const char *Dummy; 14601 AttributeFactory attrFactory; 14602 DeclSpec DS(attrFactory); 14603 unsigned DiagID; 14604 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 14605 Context.getPrintingPolicy()); 14606 (void)Error; // Silence warning. 14607 assert(!Error && "Error setting up implicit decl!"); 14608 SourceLocation NoLoc; 14609 Declarator D(DS, DeclaratorContext::BlockContext); 14610 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 14611 /*IsAmbiguous=*/false, 14612 /*LParenLoc=*/NoLoc, 14613 /*Params=*/nullptr, 14614 /*NumParams=*/0, 14615 /*EllipsisLoc=*/NoLoc, 14616 /*RParenLoc=*/NoLoc, 14617 /*RefQualifierIsLvalueRef=*/true, 14618 /*RefQualifierLoc=*/NoLoc, 14619 /*MutableLoc=*/NoLoc, EST_None, 14620 /*ESpecRange=*/SourceRange(), 14621 /*Exceptions=*/nullptr, 14622 /*ExceptionRanges=*/nullptr, 14623 /*NumExceptions=*/0, 14624 /*NoexceptExpr=*/nullptr, 14625 /*ExceptionSpecTokens=*/nullptr, 14626 /*DeclsInPrototype=*/None, Loc, 14627 Loc, D), 14628 std::move(DS.getAttributes()), SourceLocation()); 14629 D.SetIdentifier(&II, Loc); 14630 14631 // Insert this function into the enclosing block scope. 14632 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); 14633 FD->setImplicit(); 14634 14635 AddKnownFunctionAttributes(FD); 14636 14637 return FD; 14638 } 14639 14640 /// If this function is a C++ replaceable global allocation function 14641 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]), 14642 /// adds any function attributes that we know a priori based on the standard. 14643 /// 14644 /// We need to check for duplicate attributes both here and where user-written 14645 /// attributes are applied to declarations. 14646 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction( 14647 FunctionDecl *FD) { 14648 if (FD->isInvalidDecl()) 14649 return; 14650 14651 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New && 14652 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New) 14653 return; 14654 14655 Optional<unsigned> AlignmentParam; 14656 bool IsNothrow = false; 14657 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow)) 14658 return; 14659 14660 // C++2a [basic.stc.dynamic.allocation]p4: 14661 // An allocation function that has a non-throwing exception specification 14662 // indicates failure by returning a null pointer value. Any other allocation 14663 // function never returns a null pointer value and indicates failure only by 14664 // throwing an exception [...] 14665 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>()) 14666 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation())); 14667 14668 // C++2a [basic.stc.dynamic.allocation]p2: 14669 // An allocation function attempts to allocate the requested amount of 14670 // storage. [...] If the request succeeds, the value returned by a 14671 // replaceable allocation function is a [...] pointer value p0 different 14672 // from any previously returned value p1 [...] 14673 // 14674 // However, this particular information is being added in codegen, 14675 // because there is an opt-out switch for it (-fno-assume-sane-operator-new) 14676 14677 // C++2a [basic.stc.dynamic.allocation]p2: 14678 // An allocation function attempts to allocate the requested amount of 14679 // storage. If it is successful, it returns the address of the start of a 14680 // block of storage whose length in bytes is at least as large as the 14681 // requested size. 14682 if (!FD->hasAttr<AllocSizeAttr>()) { 14683 FD->addAttr(AllocSizeAttr::CreateImplicit( 14684 Context, /*ElemSizeParam=*/ParamIdx(1, FD), 14685 /*NumElemsParam=*/ParamIdx(), FD->getLocation())); 14686 } 14687 14688 // C++2a [basic.stc.dynamic.allocation]p3: 14689 // For an allocation function [...], the pointer returned on a successful 14690 // call shall represent the address of storage that is aligned as follows: 14691 // (3.1) If the allocation function takes an argument of type 14692 // std::align_val_t, the storage will have the alignment 14693 // specified by the value of this argument. 14694 if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) { 14695 FD->addAttr(AllocAlignAttr::CreateImplicit( 14696 Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation())); 14697 } 14698 14699 // FIXME: 14700 // C++2a [basic.stc.dynamic.allocation]p3: 14701 // For an allocation function [...], the pointer returned on a successful 14702 // call shall represent the address of storage that is aligned as follows: 14703 // (3.2) Otherwise, if the allocation function is named operator new[], 14704 // the storage is aligned for any object that does not have 14705 // new-extended alignment ([basic.align]) and is no larger than the 14706 // requested size. 14707 // (3.3) Otherwise, the storage is aligned for any object that does not 14708 // have new-extended alignment and is of the requested size. 14709 } 14710 14711 /// Adds any function attributes that we know a priori based on 14712 /// the declaration of this function. 14713 /// 14714 /// These attributes can apply both to implicitly-declared builtins 14715 /// (like __builtin___printf_chk) or to library-declared functions 14716 /// like NSLog or printf. 14717 /// 14718 /// We need to check for duplicate attributes both here and where user-written 14719 /// attributes are applied to declarations. 14720 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 14721 if (FD->isInvalidDecl()) 14722 return; 14723 14724 // If this is a built-in function, map its builtin attributes to 14725 // actual attributes. 14726 if (unsigned BuiltinID = FD->getBuiltinID()) { 14727 // Handle printf-formatting attributes. 14728 unsigned FormatIdx; 14729 bool HasVAListArg; 14730 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 14731 if (!FD->hasAttr<FormatAttr>()) { 14732 const char *fmt = "printf"; 14733 unsigned int NumParams = FD->getNumParams(); 14734 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 14735 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 14736 fmt = "NSString"; 14737 FD->addAttr(FormatAttr::CreateImplicit(Context, 14738 &Context.Idents.get(fmt), 14739 FormatIdx+1, 14740 HasVAListArg ? 0 : FormatIdx+2, 14741 FD->getLocation())); 14742 } 14743 } 14744 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 14745 HasVAListArg)) { 14746 if (!FD->hasAttr<FormatAttr>()) 14747 FD->addAttr(FormatAttr::CreateImplicit(Context, 14748 &Context.Idents.get("scanf"), 14749 FormatIdx+1, 14750 HasVAListArg ? 0 : FormatIdx+2, 14751 FD->getLocation())); 14752 } 14753 14754 // Handle automatically recognized callbacks. 14755 SmallVector<int, 4> Encoding; 14756 if (!FD->hasAttr<CallbackAttr>() && 14757 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding)) 14758 FD->addAttr(CallbackAttr::CreateImplicit( 14759 Context, Encoding.data(), Encoding.size(), FD->getLocation())); 14760 14761 // Mark const if we don't care about errno and that is the only thing 14762 // preventing the function from being const. This allows IRgen to use LLVM 14763 // intrinsics for such functions. 14764 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() && 14765 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) 14766 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14767 14768 // We make "fma" on some platforms const because we know it does not set 14769 // errno in those environments even though it could set errno based on the 14770 // C standard. 14771 const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); 14772 if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) && 14773 !FD->hasAttr<ConstAttr>()) { 14774 switch (BuiltinID) { 14775 case Builtin::BI__builtin_fma: 14776 case Builtin::BI__builtin_fmaf: 14777 case Builtin::BI__builtin_fmal: 14778 case Builtin::BIfma: 14779 case Builtin::BIfmaf: 14780 case Builtin::BIfmal: 14781 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14782 break; 14783 default: 14784 break; 14785 } 14786 } 14787 14788 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 14789 !FD->hasAttr<ReturnsTwiceAttr>()) 14790 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 14791 FD->getLocation())); 14792 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 14793 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 14794 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 14795 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 14796 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 14797 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14798 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 14799 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 14800 // Add the appropriate attribute, depending on the CUDA compilation mode 14801 // and which target the builtin belongs to. For example, during host 14802 // compilation, aux builtins are __device__, while the rest are __host__. 14803 if (getLangOpts().CUDAIsDevice != 14804 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 14805 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 14806 else 14807 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 14808 } 14809 } 14810 14811 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD); 14812 14813 // If C++ exceptions are enabled but we are told extern "C" functions cannot 14814 // throw, add an implicit nothrow attribute to any extern "C" function we come 14815 // across. 14816 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 14817 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 14818 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 14819 if (!FPT || FPT->getExceptionSpecType() == EST_None) 14820 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 14821 } 14822 14823 IdentifierInfo *Name = FD->getIdentifier(); 14824 if (!Name) 14825 return; 14826 if ((!getLangOpts().CPlusPlus && 14827 FD->getDeclContext()->isTranslationUnit()) || 14828 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 14829 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 14830 LinkageSpecDecl::lang_c)) { 14831 // Okay: this could be a libc/libm/Objective-C function we know 14832 // about. 14833 } else 14834 return; 14835 14836 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 14837 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 14838 // target-specific builtins, perhaps? 14839 if (!FD->hasAttr<FormatAttr>()) 14840 FD->addAttr(FormatAttr::CreateImplicit(Context, 14841 &Context.Idents.get("printf"), 2, 14842 Name->isStr("vasprintf") ? 0 : 3, 14843 FD->getLocation())); 14844 } 14845 14846 if (Name->isStr("__CFStringMakeConstantString")) { 14847 // We already have a __builtin___CFStringMakeConstantString, 14848 // but builds that use -fno-constant-cfstrings don't go through that. 14849 if (!FD->hasAttr<FormatArgAttr>()) 14850 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), 14851 FD->getLocation())); 14852 } 14853 } 14854 14855 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 14856 TypeSourceInfo *TInfo) { 14857 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 14858 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 14859 14860 if (!TInfo) { 14861 assert(D.isInvalidType() && "no declarator info for valid type"); 14862 TInfo = Context.getTrivialTypeSourceInfo(T); 14863 } 14864 14865 // Scope manipulation handled by caller. 14866 TypedefDecl *NewTD = 14867 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(), 14868 D.getIdentifierLoc(), D.getIdentifier(), TInfo); 14869 14870 // Bail out immediately if we have an invalid declaration. 14871 if (D.isInvalidType()) { 14872 NewTD->setInvalidDecl(); 14873 return NewTD; 14874 } 14875 14876 if (D.getDeclSpec().isModulePrivateSpecified()) { 14877 if (CurContext->isFunctionOrMethod()) 14878 Diag(NewTD->getLocation(), diag::err_module_private_local) 14879 << 2 << NewTD->getDeclName() 14880 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 14881 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 14882 else 14883 NewTD->setModulePrivate(); 14884 } 14885 14886 // C++ [dcl.typedef]p8: 14887 // If the typedef declaration defines an unnamed class (or 14888 // enum), the first typedef-name declared by the declaration 14889 // to be that class type (or enum type) is used to denote the 14890 // class type (or enum type) for linkage purposes only. 14891 // We need to check whether the type was declared in the declaration. 14892 switch (D.getDeclSpec().getTypeSpecType()) { 14893 case TST_enum: 14894 case TST_struct: 14895 case TST_interface: 14896 case TST_union: 14897 case TST_class: { 14898 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 14899 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 14900 break; 14901 } 14902 14903 default: 14904 break; 14905 } 14906 14907 return NewTD; 14908 } 14909 14910 /// Check that this is a valid underlying type for an enum declaration. 14911 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 14912 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 14913 QualType T = TI->getType(); 14914 14915 if (T->isDependentType()) 14916 return false; 14917 14918 // This doesn't use 'isIntegralType' despite the error message mentioning 14919 // integral type because isIntegralType would also allow enum types in C. 14920 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 14921 if (BT->isInteger()) 14922 return false; 14923 14924 if (T->isExtIntType()) 14925 return false; 14926 14927 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 14928 } 14929 14930 /// Check whether this is a valid redeclaration of a previous enumeration. 14931 /// \return true if the redeclaration was invalid. 14932 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 14933 QualType EnumUnderlyingTy, bool IsFixed, 14934 const EnumDecl *Prev) { 14935 if (IsScoped != Prev->isScoped()) { 14936 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 14937 << Prev->isScoped(); 14938 Diag(Prev->getLocation(), diag::note_previous_declaration); 14939 return true; 14940 } 14941 14942 if (IsFixed && Prev->isFixed()) { 14943 if (!EnumUnderlyingTy->isDependentType() && 14944 !Prev->getIntegerType()->isDependentType() && 14945 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 14946 Prev->getIntegerType())) { 14947 // TODO: Highlight the underlying type of the redeclaration. 14948 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 14949 << EnumUnderlyingTy << Prev->getIntegerType(); 14950 Diag(Prev->getLocation(), diag::note_previous_declaration) 14951 << Prev->getIntegerTypeRange(); 14952 return true; 14953 } 14954 } else if (IsFixed != Prev->isFixed()) { 14955 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 14956 << Prev->isFixed(); 14957 Diag(Prev->getLocation(), diag::note_previous_declaration); 14958 return true; 14959 } 14960 14961 return false; 14962 } 14963 14964 /// Get diagnostic %select index for tag kind for 14965 /// redeclaration diagnostic message. 14966 /// WARNING: Indexes apply to particular diagnostics only! 14967 /// 14968 /// \returns diagnostic %select index. 14969 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 14970 switch (Tag) { 14971 case TTK_Struct: return 0; 14972 case TTK_Interface: return 1; 14973 case TTK_Class: return 2; 14974 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 14975 } 14976 } 14977 14978 /// Determine if tag kind is a class-key compatible with 14979 /// class for redeclaration (class, struct, or __interface). 14980 /// 14981 /// \returns true iff the tag kind is compatible. 14982 static bool isClassCompatTagKind(TagTypeKind Tag) 14983 { 14984 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 14985 } 14986 14987 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 14988 TagTypeKind TTK) { 14989 if (isa<TypedefDecl>(PrevDecl)) 14990 return NTK_Typedef; 14991 else if (isa<TypeAliasDecl>(PrevDecl)) 14992 return NTK_TypeAlias; 14993 else if (isa<ClassTemplateDecl>(PrevDecl)) 14994 return NTK_Template; 14995 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 14996 return NTK_TypeAliasTemplate; 14997 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 14998 return NTK_TemplateTemplateArgument; 14999 switch (TTK) { 15000 case TTK_Struct: 15001 case TTK_Interface: 15002 case TTK_Class: 15003 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 15004 case TTK_Union: 15005 return NTK_NonUnion; 15006 case TTK_Enum: 15007 return NTK_NonEnum; 15008 } 15009 llvm_unreachable("invalid TTK"); 15010 } 15011 15012 /// Determine whether a tag with a given kind is acceptable 15013 /// as a redeclaration of the given tag declaration. 15014 /// 15015 /// \returns true if the new tag kind is acceptable, false otherwise. 15016 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 15017 TagTypeKind NewTag, bool isDefinition, 15018 SourceLocation NewTagLoc, 15019 const IdentifierInfo *Name) { 15020 // C++ [dcl.type.elab]p3: 15021 // The class-key or enum keyword present in the 15022 // elaborated-type-specifier shall agree in kind with the 15023 // declaration to which the name in the elaborated-type-specifier 15024 // refers. This rule also applies to the form of 15025 // elaborated-type-specifier that declares a class-name or 15026 // friend class since it can be construed as referring to the 15027 // definition of the class. Thus, in any 15028 // elaborated-type-specifier, the enum keyword shall be used to 15029 // refer to an enumeration (7.2), the union class-key shall be 15030 // used to refer to a union (clause 9), and either the class or 15031 // struct class-key shall be used to refer to a class (clause 9) 15032 // declared using the class or struct class-key. 15033 TagTypeKind OldTag = Previous->getTagKind(); 15034 if (OldTag != NewTag && 15035 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag))) 15036 return false; 15037 15038 // Tags are compatible, but we might still want to warn on mismatched tags. 15039 // Non-class tags can't be mismatched at this point. 15040 if (!isClassCompatTagKind(NewTag)) 15041 return true; 15042 15043 // Declarations for which -Wmismatched-tags is disabled are entirely ignored 15044 // by our warning analysis. We don't want to warn about mismatches with (eg) 15045 // declarations in system headers that are designed to be specialized, but if 15046 // a user asks us to warn, we should warn if their code contains mismatched 15047 // declarations. 15048 auto IsIgnoredLoc = [&](SourceLocation Loc) { 15049 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch, 15050 Loc); 15051 }; 15052 if (IsIgnoredLoc(NewTagLoc)) 15053 return true; 15054 15055 auto IsIgnored = [&](const TagDecl *Tag) { 15056 return IsIgnoredLoc(Tag->getLocation()); 15057 }; 15058 while (IsIgnored(Previous)) { 15059 Previous = Previous->getPreviousDecl(); 15060 if (!Previous) 15061 return true; 15062 OldTag = Previous->getTagKind(); 15063 } 15064 15065 bool isTemplate = false; 15066 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 15067 isTemplate = Record->getDescribedClassTemplate(); 15068 15069 if (inTemplateInstantiation()) { 15070 if (OldTag != NewTag) { 15071 // In a template instantiation, do not offer fix-its for tag mismatches 15072 // since they usually mess up the template instead of fixing the problem. 15073 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15074 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15075 << getRedeclDiagFromTagKind(OldTag); 15076 // FIXME: Note previous location? 15077 } 15078 return true; 15079 } 15080 15081 if (isDefinition) { 15082 // On definitions, check all previous tags and issue a fix-it for each 15083 // one that doesn't match the current tag. 15084 if (Previous->getDefinition()) { 15085 // Don't suggest fix-its for redefinitions. 15086 return true; 15087 } 15088 15089 bool previousMismatch = false; 15090 for (const TagDecl *I : Previous->redecls()) { 15091 if (I->getTagKind() != NewTag) { 15092 // Ignore previous declarations for which the warning was disabled. 15093 if (IsIgnored(I)) 15094 continue; 15095 15096 if (!previousMismatch) { 15097 previousMismatch = true; 15098 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 15099 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15100 << getRedeclDiagFromTagKind(I->getTagKind()); 15101 } 15102 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 15103 << getRedeclDiagFromTagKind(NewTag) 15104 << FixItHint::CreateReplacement(I->getInnerLocStart(), 15105 TypeWithKeyword::getTagTypeKindName(NewTag)); 15106 } 15107 } 15108 return true; 15109 } 15110 15111 // Identify the prevailing tag kind: this is the kind of the definition (if 15112 // there is a non-ignored definition), or otherwise the kind of the prior 15113 // (non-ignored) declaration. 15114 const TagDecl *PrevDef = Previous->getDefinition(); 15115 if (PrevDef && IsIgnored(PrevDef)) 15116 PrevDef = nullptr; 15117 const TagDecl *Redecl = PrevDef ? PrevDef : Previous; 15118 if (Redecl->getTagKind() != NewTag) { 15119 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15120 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15121 << getRedeclDiagFromTagKind(OldTag); 15122 Diag(Redecl->getLocation(), diag::note_previous_use); 15123 15124 // If there is a previous definition, suggest a fix-it. 15125 if (PrevDef) { 15126 Diag(NewTagLoc, diag::note_struct_class_suggestion) 15127 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 15128 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 15129 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 15130 } 15131 } 15132 15133 return true; 15134 } 15135 15136 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 15137 /// from an outer enclosing namespace or file scope inside a friend declaration. 15138 /// This should provide the commented out code in the following snippet: 15139 /// namespace N { 15140 /// struct X; 15141 /// namespace M { 15142 /// struct Y { friend struct /*N::*/ X; }; 15143 /// } 15144 /// } 15145 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 15146 SourceLocation NameLoc) { 15147 // While the decl is in a namespace, do repeated lookup of that name and see 15148 // if we get the same namespace back. If we do not, continue until 15149 // translation unit scope, at which point we have a fully qualified NNS. 15150 SmallVector<IdentifierInfo *, 4> Namespaces; 15151 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15152 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 15153 // This tag should be declared in a namespace, which can only be enclosed by 15154 // other namespaces. Bail if there's an anonymous namespace in the chain. 15155 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 15156 if (!Namespace || Namespace->isAnonymousNamespace()) 15157 return FixItHint(); 15158 IdentifierInfo *II = Namespace->getIdentifier(); 15159 Namespaces.push_back(II); 15160 NamedDecl *Lookup = SemaRef.LookupSingleName( 15161 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 15162 if (Lookup == Namespace) 15163 break; 15164 } 15165 15166 // Once we have all the namespaces, reverse them to go outermost first, and 15167 // build an NNS. 15168 SmallString<64> Insertion; 15169 llvm::raw_svector_ostream OS(Insertion); 15170 if (DC->isTranslationUnit()) 15171 OS << "::"; 15172 std::reverse(Namespaces.begin(), Namespaces.end()); 15173 for (auto *II : Namespaces) 15174 OS << II->getName() << "::"; 15175 return FixItHint::CreateInsertion(NameLoc, Insertion); 15176 } 15177 15178 /// Determine whether a tag originally declared in context \p OldDC can 15179 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup 15180 /// found a declaration in \p OldDC as a previous decl, perhaps through a 15181 /// using-declaration). 15182 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 15183 DeclContext *NewDC) { 15184 OldDC = OldDC->getRedeclContext(); 15185 NewDC = NewDC->getRedeclContext(); 15186 15187 if (OldDC->Equals(NewDC)) 15188 return true; 15189 15190 // In MSVC mode, we allow a redeclaration if the contexts are related (either 15191 // encloses the other). 15192 if (S.getLangOpts().MSVCCompat && 15193 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 15194 return true; 15195 15196 return false; 15197 } 15198 15199 /// This is invoked when we see 'struct foo' or 'struct {'. In the 15200 /// former case, Name will be non-null. In the later case, Name will be null. 15201 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 15202 /// reference/declaration/definition of a tag. 15203 /// 15204 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 15205 /// trailing-type-specifier) other than one in an alias-declaration. 15206 /// 15207 /// \param SkipBody If non-null, will be set to indicate if the caller should 15208 /// skip the definition of this tag and treat it as if it were a declaration. 15209 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 15210 SourceLocation KWLoc, CXXScopeSpec &SS, 15211 IdentifierInfo *Name, SourceLocation NameLoc, 15212 const ParsedAttributesView &Attrs, AccessSpecifier AS, 15213 SourceLocation ModulePrivateLoc, 15214 MultiTemplateParamsArg TemplateParameterLists, 15215 bool &OwnedDecl, bool &IsDependent, 15216 SourceLocation ScopedEnumKWLoc, 15217 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, 15218 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 15219 SkipBodyInfo *SkipBody) { 15220 // If this is not a definition, it must have a name. 15221 IdentifierInfo *OrigName = Name; 15222 assert((Name != nullptr || TUK == TUK_Definition) && 15223 "Nameless record must be a definition!"); 15224 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 15225 15226 OwnedDecl = false; 15227 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 15228 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 15229 15230 // FIXME: Check member specializations more carefully. 15231 bool isMemberSpecialization = false; 15232 bool Invalid = false; 15233 15234 // We only need to do this matching if we have template parameters 15235 // or a scope specifier, which also conveniently avoids this work 15236 // for non-C++ cases. 15237 if (TemplateParameterLists.size() > 0 || 15238 (SS.isNotEmpty() && TUK != TUK_Reference)) { 15239 if (TemplateParameterList *TemplateParams = 15240 MatchTemplateParametersToScopeSpecifier( 15241 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 15242 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 15243 if (Kind == TTK_Enum) { 15244 Diag(KWLoc, diag::err_enum_template); 15245 return nullptr; 15246 } 15247 15248 if (TemplateParams->size() > 0) { 15249 // This is a declaration or definition of a class template (which may 15250 // be a member of another template). 15251 15252 if (Invalid) 15253 return nullptr; 15254 15255 OwnedDecl = false; 15256 DeclResult Result = CheckClassTemplate( 15257 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams, 15258 AS, ModulePrivateLoc, 15259 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1, 15260 TemplateParameterLists.data(), SkipBody); 15261 return Result.get(); 15262 } else { 15263 // The "template<>" header is extraneous. 15264 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 15265 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 15266 isMemberSpecialization = true; 15267 } 15268 } 15269 } 15270 15271 // Figure out the underlying type if this a enum declaration. We need to do 15272 // this early, because it's needed to detect if this is an incompatible 15273 // redeclaration. 15274 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 15275 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; 15276 15277 if (Kind == TTK_Enum) { 15278 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { 15279 // No underlying type explicitly specified, or we failed to parse the 15280 // type, default to int. 15281 EnumUnderlying = Context.IntTy.getTypePtr(); 15282 } else if (UnderlyingType.get()) { 15283 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 15284 // integral type; any cv-qualification is ignored. 15285 TypeSourceInfo *TI = nullptr; 15286 GetTypeFromParser(UnderlyingType.get(), &TI); 15287 EnumUnderlying = TI; 15288 15289 if (CheckEnumUnderlyingType(TI)) 15290 // Recover by falling back to int. 15291 EnumUnderlying = Context.IntTy.getTypePtr(); 15292 15293 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 15294 UPPC_FixedUnderlyingType)) 15295 EnumUnderlying = Context.IntTy.getTypePtr(); 15296 15297 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) { 15298 // For MSVC ABI compatibility, unfixed enums must use an underlying type 15299 // of 'int'. However, if this is an unfixed forward declaration, don't set 15300 // the underlying type unless the user enables -fms-compatibility. This 15301 // makes unfixed forward declared enums incomplete and is more conforming. 15302 if (TUK == TUK_Definition || getLangOpts().MSVCCompat) 15303 EnumUnderlying = Context.IntTy.getTypePtr(); 15304 } 15305 } 15306 15307 DeclContext *SearchDC = CurContext; 15308 DeclContext *DC = CurContext; 15309 bool isStdBadAlloc = false; 15310 bool isStdAlignValT = false; 15311 15312 RedeclarationKind Redecl = forRedeclarationInCurContext(); 15313 if (TUK == TUK_Friend || TUK == TUK_Reference) 15314 Redecl = NotForRedeclaration; 15315 15316 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C 15317 /// implemented asks for structural equivalence checking, the returned decl 15318 /// here is passed back to the parser, allowing the tag body to be parsed. 15319 auto createTagFromNewDecl = [&]() -> TagDecl * { 15320 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage"); 15321 // If there is an identifier, use the location of the identifier as the 15322 // location of the decl, otherwise use the location of the struct/union 15323 // keyword. 15324 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 15325 TagDecl *New = nullptr; 15326 15327 if (Kind == TTK_Enum) { 15328 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, 15329 ScopedEnum, ScopedEnumUsesClassTag, IsFixed); 15330 // If this is an undefined enum, bail. 15331 if (TUK != TUK_Definition && !Invalid) 15332 return nullptr; 15333 if (EnumUnderlying) { 15334 EnumDecl *ED = cast<EnumDecl>(New); 15335 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) 15336 ED->setIntegerTypeSourceInfo(TI); 15337 else 15338 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); 15339 ED->setPromotionType(ED->getIntegerType()); 15340 } 15341 } else { // struct/union 15342 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 15343 nullptr); 15344 } 15345 15346 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 15347 // Add alignment attributes if necessary; these attributes are checked 15348 // when the ASTContext lays out the structure. 15349 // 15350 // It is important for implementing the correct semantics that this 15351 // happen here (in ActOnTag). The #pragma pack stack is 15352 // maintained as a result of parser callbacks which can occur at 15353 // many points during the parsing of a struct declaration (because 15354 // the #pragma tokens are effectively skipped over during the 15355 // parsing of the struct). 15356 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 15357 AddAlignmentAttributesForRecord(RD); 15358 AddMsStructLayoutForRecord(RD); 15359 } 15360 } 15361 New->setLexicalDeclContext(CurContext); 15362 return New; 15363 }; 15364 15365 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 15366 if (Name && SS.isNotEmpty()) { 15367 // We have a nested-name tag ('struct foo::bar'). 15368 15369 // Check for invalid 'foo::'. 15370 if (SS.isInvalid()) { 15371 Name = nullptr; 15372 goto CreateNewDecl; 15373 } 15374 15375 // If this is a friend or a reference to a class in a dependent 15376 // context, don't try to make a decl for it. 15377 if (TUK == TUK_Friend || TUK == TUK_Reference) { 15378 DC = computeDeclContext(SS, false); 15379 if (!DC) { 15380 IsDependent = true; 15381 return nullptr; 15382 } 15383 } else { 15384 DC = computeDeclContext(SS, true); 15385 if (!DC) { 15386 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 15387 << SS.getRange(); 15388 return nullptr; 15389 } 15390 } 15391 15392 if (RequireCompleteDeclContext(SS, DC)) 15393 return nullptr; 15394 15395 SearchDC = DC; 15396 // Look-up name inside 'foo::'. 15397 LookupQualifiedName(Previous, DC); 15398 15399 if (Previous.isAmbiguous()) 15400 return nullptr; 15401 15402 if (Previous.empty()) { 15403 // Name lookup did not find anything. However, if the 15404 // nested-name-specifier refers to the current instantiation, 15405 // and that current instantiation has any dependent base 15406 // classes, we might find something at instantiation time: treat 15407 // this as a dependent elaborated-type-specifier. 15408 // But this only makes any sense for reference-like lookups. 15409 if (Previous.wasNotFoundInCurrentInstantiation() && 15410 (TUK == TUK_Reference || TUK == TUK_Friend)) { 15411 IsDependent = true; 15412 return nullptr; 15413 } 15414 15415 // A tag 'foo::bar' must already exist. 15416 Diag(NameLoc, diag::err_not_tag_in_scope) 15417 << Kind << Name << DC << SS.getRange(); 15418 Name = nullptr; 15419 Invalid = true; 15420 goto CreateNewDecl; 15421 } 15422 } else if (Name) { 15423 // C++14 [class.mem]p14: 15424 // If T is the name of a class, then each of the following shall have a 15425 // name different from T: 15426 // -- every member of class T that is itself a type 15427 if (TUK != TUK_Reference && TUK != TUK_Friend && 15428 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 15429 return nullptr; 15430 15431 // If this is a named struct, check to see if there was a previous forward 15432 // declaration or definition. 15433 // FIXME: We're looking into outer scopes here, even when we 15434 // shouldn't be. Doing so can result in ambiguities that we 15435 // shouldn't be diagnosing. 15436 LookupName(Previous, S); 15437 15438 // When declaring or defining a tag, ignore ambiguities introduced 15439 // by types using'ed into this scope. 15440 if (Previous.isAmbiguous() && 15441 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 15442 LookupResult::Filter F = Previous.makeFilter(); 15443 while (F.hasNext()) { 15444 NamedDecl *ND = F.next(); 15445 if (!ND->getDeclContext()->getRedeclContext()->Equals( 15446 SearchDC->getRedeclContext())) 15447 F.erase(); 15448 } 15449 F.done(); 15450 } 15451 15452 // C++11 [namespace.memdef]p3: 15453 // If the name in a friend declaration is neither qualified nor 15454 // a template-id and the declaration is a function or an 15455 // elaborated-type-specifier, the lookup to determine whether 15456 // the entity has been previously declared shall not consider 15457 // any scopes outside the innermost enclosing namespace. 15458 // 15459 // MSVC doesn't implement the above rule for types, so a friend tag 15460 // declaration may be a redeclaration of a type declared in an enclosing 15461 // scope. They do implement this rule for friend functions. 15462 // 15463 // Does it matter that this should be by scope instead of by 15464 // semantic context? 15465 if (!Previous.empty() && TUK == TUK_Friend) { 15466 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 15467 LookupResult::Filter F = Previous.makeFilter(); 15468 bool FriendSawTagOutsideEnclosingNamespace = false; 15469 while (F.hasNext()) { 15470 NamedDecl *ND = F.next(); 15471 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15472 if (DC->isFileContext() && 15473 !EnclosingNS->Encloses(ND->getDeclContext())) { 15474 if (getLangOpts().MSVCCompat) 15475 FriendSawTagOutsideEnclosingNamespace = true; 15476 else 15477 F.erase(); 15478 } 15479 } 15480 F.done(); 15481 15482 // Diagnose this MSVC extension in the easy case where lookup would have 15483 // unambiguously found something outside the enclosing namespace. 15484 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 15485 NamedDecl *ND = Previous.getFoundDecl(); 15486 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 15487 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 15488 } 15489 } 15490 15491 // Note: there used to be some attempt at recovery here. 15492 if (Previous.isAmbiguous()) 15493 return nullptr; 15494 15495 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 15496 // FIXME: This makes sure that we ignore the contexts associated 15497 // with C structs, unions, and enums when looking for a matching 15498 // tag declaration or definition. See the similar lookup tweak 15499 // in Sema::LookupName; is there a better way to deal with this? 15500 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 15501 SearchDC = SearchDC->getParent(); 15502 } 15503 } 15504 15505 if (Previous.isSingleResult() && 15506 Previous.getFoundDecl()->isTemplateParameter()) { 15507 // Maybe we will complain about the shadowed template parameter. 15508 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 15509 // Just pretend that we didn't see the previous declaration. 15510 Previous.clear(); 15511 } 15512 15513 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 15514 DC->Equals(getStdNamespace())) { 15515 if (Name->isStr("bad_alloc")) { 15516 // This is a declaration of or a reference to "std::bad_alloc". 15517 isStdBadAlloc = true; 15518 15519 // If std::bad_alloc has been implicitly declared (but made invisible to 15520 // name lookup), fill in this implicit declaration as the previous 15521 // declaration, so that the declarations get chained appropriately. 15522 if (Previous.empty() && StdBadAlloc) 15523 Previous.addDecl(getStdBadAlloc()); 15524 } else if (Name->isStr("align_val_t")) { 15525 isStdAlignValT = true; 15526 if (Previous.empty() && StdAlignValT) 15527 Previous.addDecl(getStdAlignValT()); 15528 } 15529 } 15530 15531 // If we didn't find a previous declaration, and this is a reference 15532 // (or friend reference), move to the correct scope. In C++, we 15533 // also need to do a redeclaration lookup there, just in case 15534 // there's a shadow friend decl. 15535 if (Name && Previous.empty() && 15536 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { 15537 if (Invalid) goto CreateNewDecl; 15538 assert(SS.isEmpty()); 15539 15540 if (TUK == TUK_Reference || IsTemplateParamOrArg) { 15541 // C++ [basic.scope.pdecl]p5: 15542 // -- for an elaborated-type-specifier of the form 15543 // 15544 // class-key identifier 15545 // 15546 // if the elaborated-type-specifier is used in the 15547 // decl-specifier-seq or parameter-declaration-clause of a 15548 // function defined in namespace scope, the identifier is 15549 // declared as a class-name in the namespace that contains 15550 // the declaration; otherwise, except as a friend 15551 // declaration, the identifier is declared in the smallest 15552 // non-class, non-function-prototype scope that contains the 15553 // declaration. 15554 // 15555 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 15556 // C structs and unions. 15557 // 15558 // It is an error in C++ to declare (rather than define) an enum 15559 // type, including via an elaborated type specifier. We'll 15560 // diagnose that later; for now, declare the enum in the same 15561 // scope as we would have picked for any other tag type. 15562 // 15563 // GNU C also supports this behavior as part of its incomplete 15564 // enum types extension, while GNU C++ does not. 15565 // 15566 // Find the context where we'll be declaring the tag. 15567 // FIXME: We would like to maintain the current DeclContext as the 15568 // lexical context, 15569 SearchDC = getTagInjectionContext(SearchDC); 15570 15571 // Find the scope where we'll be declaring the tag. 15572 S = getTagInjectionScope(S, getLangOpts()); 15573 } else { 15574 assert(TUK == TUK_Friend); 15575 // C++ [namespace.memdef]p3: 15576 // If a friend declaration in a non-local class first declares a 15577 // class or function, the friend class or function is a member of 15578 // the innermost enclosing namespace. 15579 SearchDC = SearchDC->getEnclosingNamespaceContext(); 15580 } 15581 15582 // In C++, we need to do a redeclaration lookup to properly 15583 // diagnose some problems. 15584 // FIXME: redeclaration lookup is also used (with and without C++) to find a 15585 // hidden declaration so that we don't get ambiguity errors when using a 15586 // type declared by an elaborated-type-specifier. In C that is not correct 15587 // and we should instead merge compatible types found by lookup. 15588 if (getLangOpts().CPlusPlus) { 15589 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 15590 LookupQualifiedName(Previous, SearchDC); 15591 } else { 15592 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 15593 LookupName(Previous, S); 15594 } 15595 } 15596 15597 // If we have a known previous declaration to use, then use it. 15598 if (Previous.empty() && SkipBody && SkipBody->Previous) 15599 Previous.addDecl(SkipBody->Previous); 15600 15601 if (!Previous.empty()) { 15602 NamedDecl *PrevDecl = Previous.getFoundDecl(); 15603 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 15604 15605 // It's okay to have a tag decl in the same scope as a typedef 15606 // which hides a tag decl in the same scope. Finding this 15607 // insanity with a redeclaration lookup can only actually happen 15608 // in C++. 15609 // 15610 // This is also okay for elaborated-type-specifiers, which is 15611 // technically forbidden by the current standard but which is 15612 // okay according to the likely resolution of an open issue; 15613 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 15614 if (getLangOpts().CPlusPlus) { 15615 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 15616 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 15617 TagDecl *Tag = TT->getDecl(); 15618 if (Tag->getDeclName() == Name && 15619 Tag->getDeclContext()->getRedeclContext() 15620 ->Equals(TD->getDeclContext()->getRedeclContext())) { 15621 PrevDecl = Tag; 15622 Previous.clear(); 15623 Previous.addDecl(Tag); 15624 Previous.resolveKind(); 15625 } 15626 } 15627 } 15628 } 15629 15630 // If this is a redeclaration of a using shadow declaration, it must 15631 // declare a tag in the same context. In MSVC mode, we allow a 15632 // redefinition if either context is within the other. 15633 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 15634 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 15635 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 15636 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 15637 !(OldTag && isAcceptableTagRedeclContext( 15638 *this, OldTag->getDeclContext(), SearchDC))) { 15639 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 15640 Diag(Shadow->getTargetDecl()->getLocation(), 15641 diag::note_using_decl_target); 15642 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) 15643 << 0; 15644 // Recover by ignoring the old declaration. 15645 Previous.clear(); 15646 goto CreateNewDecl; 15647 } 15648 } 15649 15650 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 15651 // If this is a use of a previous tag, or if the tag is already declared 15652 // in the same scope (so that the definition/declaration completes or 15653 // rementions the tag), reuse the decl. 15654 if (TUK == TUK_Reference || TUK == TUK_Friend || 15655 isDeclInScope(DirectPrevDecl, SearchDC, S, 15656 SS.isNotEmpty() || isMemberSpecialization)) { 15657 // Make sure that this wasn't declared as an enum and now used as a 15658 // struct or something similar. 15659 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 15660 TUK == TUK_Definition, KWLoc, 15661 Name)) { 15662 bool SafeToContinue 15663 = (PrevTagDecl->getTagKind() != TTK_Enum && 15664 Kind != TTK_Enum); 15665 if (SafeToContinue) 15666 Diag(KWLoc, diag::err_use_with_wrong_tag) 15667 << Name 15668 << FixItHint::CreateReplacement(SourceRange(KWLoc), 15669 PrevTagDecl->getKindName()); 15670 else 15671 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 15672 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 15673 15674 if (SafeToContinue) 15675 Kind = PrevTagDecl->getTagKind(); 15676 else { 15677 // Recover by making this an anonymous redefinition. 15678 Name = nullptr; 15679 Previous.clear(); 15680 Invalid = true; 15681 } 15682 } 15683 15684 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 15685 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 15686 if (TUK == TUK_Reference || TUK == TUK_Friend) 15687 return PrevTagDecl; 15688 15689 QualType EnumUnderlyingTy; 15690 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 15691 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 15692 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 15693 EnumUnderlyingTy = QualType(T, 0); 15694 15695 // All conflicts with previous declarations are recovered by 15696 // returning the previous declaration, unless this is a definition, 15697 // in which case we want the caller to bail out. 15698 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 15699 ScopedEnum, EnumUnderlyingTy, 15700 IsFixed, PrevEnum)) 15701 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 15702 } 15703 15704 // C++11 [class.mem]p1: 15705 // A member shall not be declared twice in the member-specification, 15706 // except that a nested class or member class template can be declared 15707 // and then later defined. 15708 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 15709 S->isDeclScope(PrevDecl)) { 15710 Diag(NameLoc, diag::ext_member_redeclared); 15711 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 15712 } 15713 15714 if (!Invalid) { 15715 // If this is a use, just return the declaration we found, unless 15716 // we have attributes. 15717 if (TUK == TUK_Reference || TUK == TUK_Friend) { 15718 if (!Attrs.empty()) { 15719 // FIXME: Diagnose these attributes. For now, we create a new 15720 // declaration to hold them. 15721 } else if (TUK == TUK_Reference && 15722 (PrevTagDecl->getFriendObjectKind() == 15723 Decl::FOK_Undeclared || 15724 PrevDecl->getOwningModule() != getCurrentModule()) && 15725 SS.isEmpty()) { 15726 // This declaration is a reference to an existing entity, but 15727 // has different visibility from that entity: it either makes 15728 // a friend visible or it makes a type visible in a new module. 15729 // In either case, create a new declaration. We only do this if 15730 // the declaration would have meant the same thing if no prior 15731 // declaration were found, that is, if it was found in the same 15732 // scope where we would have injected a declaration. 15733 if (!getTagInjectionContext(CurContext)->getRedeclContext() 15734 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 15735 return PrevTagDecl; 15736 // This is in the injected scope, create a new declaration in 15737 // that scope. 15738 S = getTagInjectionScope(S, getLangOpts()); 15739 } else { 15740 return PrevTagDecl; 15741 } 15742 } 15743 15744 // Diagnose attempts to redefine a tag. 15745 if (TUK == TUK_Definition) { 15746 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 15747 // If we're defining a specialization and the previous definition 15748 // is from an implicit instantiation, don't emit an error 15749 // here; we'll catch this in the general case below. 15750 bool IsExplicitSpecializationAfterInstantiation = false; 15751 if (isMemberSpecialization) { 15752 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 15753 IsExplicitSpecializationAfterInstantiation = 15754 RD->getTemplateSpecializationKind() != 15755 TSK_ExplicitSpecialization; 15756 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 15757 IsExplicitSpecializationAfterInstantiation = 15758 ED->getTemplateSpecializationKind() != 15759 TSK_ExplicitSpecialization; 15760 } 15761 15762 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do 15763 // not keep more that one definition around (merge them). However, 15764 // ensure the decl passes the structural compatibility check in 15765 // C11 6.2.7/1 (or 6.1.2.6/1 in C89). 15766 NamedDecl *Hidden = nullptr; 15767 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 15768 // There is a definition of this tag, but it is not visible. We 15769 // explicitly make use of C++'s one definition rule here, and 15770 // assume that this definition is identical to the hidden one 15771 // we already have. Make the existing definition visible and 15772 // use it in place of this one. 15773 if (!getLangOpts().CPlusPlus) { 15774 // Postpone making the old definition visible until after we 15775 // complete parsing the new one and do the structural 15776 // comparison. 15777 SkipBody->CheckSameAsPrevious = true; 15778 SkipBody->New = createTagFromNewDecl(); 15779 SkipBody->Previous = Def; 15780 return Def; 15781 } else { 15782 SkipBody->ShouldSkip = true; 15783 SkipBody->Previous = Def; 15784 makeMergedDefinitionVisible(Hidden); 15785 // Carry on and handle it like a normal definition. We'll 15786 // skip starting the definitiion later. 15787 } 15788 } else if (!IsExplicitSpecializationAfterInstantiation) { 15789 // A redeclaration in function prototype scope in C isn't 15790 // visible elsewhere, so merely issue a warning. 15791 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 15792 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 15793 else 15794 Diag(NameLoc, diag::err_redefinition) << Name; 15795 notePreviousDefinition(Def, 15796 NameLoc.isValid() ? NameLoc : KWLoc); 15797 // If this is a redefinition, recover by making this 15798 // struct be anonymous, which will make any later 15799 // references get the previous definition. 15800 Name = nullptr; 15801 Previous.clear(); 15802 Invalid = true; 15803 } 15804 } else { 15805 // If the type is currently being defined, complain 15806 // about a nested redefinition. 15807 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 15808 if (TD->isBeingDefined()) { 15809 Diag(NameLoc, diag::err_nested_redefinition) << Name; 15810 Diag(PrevTagDecl->getLocation(), 15811 diag::note_previous_definition); 15812 Name = nullptr; 15813 Previous.clear(); 15814 Invalid = true; 15815 } 15816 } 15817 15818 // Okay, this is definition of a previously declared or referenced 15819 // tag. We're going to create a new Decl for it. 15820 } 15821 15822 // Okay, we're going to make a redeclaration. If this is some kind 15823 // of reference, make sure we build the redeclaration in the same DC 15824 // as the original, and ignore the current access specifier. 15825 if (TUK == TUK_Friend || TUK == TUK_Reference) { 15826 SearchDC = PrevTagDecl->getDeclContext(); 15827 AS = AS_none; 15828 } 15829 } 15830 // If we get here we have (another) forward declaration or we 15831 // have a definition. Just create a new decl. 15832 15833 } else { 15834 // If we get here, this is a definition of a new tag type in a nested 15835 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 15836 // new decl/type. We set PrevDecl to NULL so that the entities 15837 // have distinct types. 15838 Previous.clear(); 15839 } 15840 // If we get here, we're going to create a new Decl. If PrevDecl 15841 // is non-NULL, it's a definition of the tag declared by 15842 // PrevDecl. If it's NULL, we have a new definition. 15843 15844 // Otherwise, PrevDecl is not a tag, but was found with tag 15845 // lookup. This is only actually possible in C++, where a few 15846 // things like templates still live in the tag namespace. 15847 } else { 15848 // Use a better diagnostic if an elaborated-type-specifier 15849 // found the wrong kind of type on the first 15850 // (non-redeclaration) lookup. 15851 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 15852 !Previous.isForRedeclaration()) { 15853 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 15854 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 15855 << Kind; 15856 Diag(PrevDecl->getLocation(), diag::note_declared_at); 15857 Invalid = true; 15858 15859 // Otherwise, only diagnose if the declaration is in scope. 15860 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 15861 SS.isNotEmpty() || isMemberSpecialization)) { 15862 // do nothing 15863 15864 // Diagnose implicit declarations introduced by elaborated types. 15865 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 15866 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 15867 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 15868 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 15869 Invalid = true; 15870 15871 // Otherwise it's a declaration. Call out a particularly common 15872 // case here. 15873 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 15874 unsigned Kind = 0; 15875 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 15876 Diag(NameLoc, diag::err_tag_definition_of_typedef) 15877 << Name << Kind << TND->getUnderlyingType(); 15878 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 15879 Invalid = true; 15880 15881 // Otherwise, diagnose. 15882 } else { 15883 // The tag name clashes with something else in the target scope, 15884 // issue an error and recover by making this tag be anonymous. 15885 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 15886 notePreviousDefinition(PrevDecl, NameLoc); 15887 Name = nullptr; 15888 Invalid = true; 15889 } 15890 15891 // The existing declaration isn't relevant to us; we're in a 15892 // new scope, so clear out the previous declaration. 15893 Previous.clear(); 15894 } 15895 } 15896 15897 CreateNewDecl: 15898 15899 TagDecl *PrevDecl = nullptr; 15900 if (Previous.isSingleResult()) 15901 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 15902 15903 // If there is an identifier, use the location of the identifier as the 15904 // location of the decl, otherwise use the location of the struct/union 15905 // keyword. 15906 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 15907 15908 // Otherwise, create a new declaration. If there is a previous 15909 // declaration of the same entity, the two will be linked via 15910 // PrevDecl. 15911 TagDecl *New; 15912 15913 if (Kind == TTK_Enum) { 15914 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 15915 // enum X { A, B, C } D; D should chain to X. 15916 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 15917 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 15918 ScopedEnumUsesClassTag, IsFixed); 15919 15920 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 15921 StdAlignValT = cast<EnumDecl>(New); 15922 15923 // If this is an undefined enum, warn. 15924 if (TUK != TUK_Definition && !Invalid) { 15925 TagDecl *Def; 15926 if (IsFixed && cast<EnumDecl>(New)->isFixed()) { 15927 // C++0x: 7.2p2: opaque-enum-declaration. 15928 // Conflicts are diagnosed above. Do nothing. 15929 } 15930 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 15931 Diag(Loc, diag::ext_forward_ref_enum_def) 15932 << New; 15933 Diag(Def->getLocation(), diag::note_previous_definition); 15934 } else { 15935 unsigned DiagID = diag::ext_forward_ref_enum; 15936 if (getLangOpts().MSVCCompat) 15937 DiagID = diag::ext_ms_forward_ref_enum; 15938 else if (getLangOpts().CPlusPlus) 15939 DiagID = diag::err_forward_ref_enum; 15940 Diag(Loc, DiagID); 15941 } 15942 } 15943 15944 if (EnumUnderlying) { 15945 EnumDecl *ED = cast<EnumDecl>(New); 15946 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 15947 ED->setIntegerTypeSourceInfo(TI); 15948 else 15949 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 15950 ED->setPromotionType(ED->getIntegerType()); 15951 assert(ED->isComplete() && "enum with type should be complete"); 15952 } 15953 } else { 15954 // struct/union/class 15955 15956 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 15957 // struct X { int A; } D; D should chain to X. 15958 if (getLangOpts().CPlusPlus) { 15959 // FIXME: Look for a way to use RecordDecl for simple structs. 15960 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 15961 cast_or_null<CXXRecordDecl>(PrevDecl)); 15962 15963 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 15964 StdBadAlloc = cast<CXXRecordDecl>(New); 15965 } else 15966 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 15967 cast_or_null<RecordDecl>(PrevDecl)); 15968 } 15969 15970 // C++11 [dcl.type]p3: 15971 // A type-specifier-seq shall not define a class or enumeration [...]. 15972 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && 15973 TUK == TUK_Definition) { 15974 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 15975 << Context.getTagDeclType(New); 15976 Invalid = true; 15977 } 15978 15979 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && 15980 DC->getDeclKind() == Decl::Enum) { 15981 Diag(New->getLocation(), diag::err_type_defined_in_enum) 15982 << Context.getTagDeclType(New); 15983 Invalid = true; 15984 } 15985 15986 // Maybe add qualifier info. 15987 if (SS.isNotEmpty()) { 15988 if (SS.isSet()) { 15989 // If this is either a declaration or a definition, check the 15990 // nested-name-specifier against the current context. 15991 if ((TUK == TUK_Definition || TUK == TUK_Declaration) && 15992 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, 15993 isMemberSpecialization)) 15994 Invalid = true; 15995 15996 New->setQualifierInfo(SS.getWithLocInContext(Context)); 15997 if (TemplateParameterLists.size() > 0) { 15998 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 15999 } 16000 } 16001 else 16002 Invalid = true; 16003 } 16004 16005 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 16006 // Add alignment attributes if necessary; these attributes are checked when 16007 // the ASTContext lays out the structure. 16008 // 16009 // It is important for implementing the correct semantics that this 16010 // happen here (in ActOnTag). The #pragma pack stack is 16011 // maintained as a result of parser callbacks which can occur at 16012 // many points during the parsing of a struct declaration (because 16013 // the #pragma tokens are effectively skipped over during the 16014 // parsing of the struct). 16015 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 16016 AddAlignmentAttributesForRecord(RD); 16017 AddMsStructLayoutForRecord(RD); 16018 } 16019 } 16020 16021 if (ModulePrivateLoc.isValid()) { 16022 if (isMemberSpecialization) 16023 Diag(New->getLocation(), diag::err_module_private_specialization) 16024 << 2 16025 << FixItHint::CreateRemoval(ModulePrivateLoc); 16026 // __module_private__ does not apply to local classes. However, we only 16027 // diagnose this as an error when the declaration specifiers are 16028 // freestanding. Here, we just ignore the __module_private__. 16029 else if (!SearchDC->isFunctionOrMethod()) 16030 New->setModulePrivate(); 16031 } 16032 16033 // If this is a specialization of a member class (of a class template), 16034 // check the specialization. 16035 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 16036 Invalid = true; 16037 16038 // If we're declaring or defining a tag in function prototype scope in C, 16039 // note that this type can only be used within the function and add it to 16040 // the list of decls to inject into the function definition scope. 16041 if ((Name || Kind == TTK_Enum) && 16042 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 16043 if (getLangOpts().CPlusPlus) { 16044 // C++ [dcl.fct]p6: 16045 // Types shall not be defined in return or parameter types. 16046 if (TUK == TUK_Definition && !IsTypeSpecifier) { 16047 Diag(Loc, diag::err_type_defined_in_param_type) 16048 << Name; 16049 Invalid = true; 16050 } 16051 } else if (!PrevDecl) { 16052 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 16053 } 16054 } 16055 16056 if (Invalid) 16057 New->setInvalidDecl(); 16058 16059 // Set the lexical context. If the tag has a C++ scope specifier, the 16060 // lexical context will be different from the semantic context. 16061 New->setLexicalDeclContext(CurContext); 16062 16063 // Mark this as a friend decl if applicable. 16064 // In Microsoft mode, a friend declaration also acts as a forward 16065 // declaration so we always pass true to setObjectOfFriendDecl to make 16066 // the tag name visible. 16067 if (TUK == TUK_Friend) 16068 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 16069 16070 // Set the access specifier. 16071 if (!Invalid && SearchDC->isRecord()) 16072 SetMemberAccessSpecifier(New, PrevDecl, AS); 16073 16074 if (PrevDecl) 16075 CheckRedeclarationModuleOwnership(New, PrevDecl); 16076 16077 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) 16078 New->startDefinition(); 16079 16080 ProcessDeclAttributeList(S, New, Attrs); 16081 AddPragmaAttributes(S, New); 16082 16083 // If this has an identifier, add it to the scope stack. 16084 if (TUK == TUK_Friend) { 16085 // We might be replacing an existing declaration in the lookup tables; 16086 // if so, borrow its access specifier. 16087 if (PrevDecl) 16088 New->setAccess(PrevDecl->getAccess()); 16089 16090 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 16091 DC->makeDeclVisibleInContext(New); 16092 if (Name) // can be null along some error paths 16093 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 16094 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 16095 } else if (Name) { 16096 S = getNonFieldDeclScope(S); 16097 PushOnScopeChains(New, S, true); 16098 } else { 16099 CurContext->addDecl(New); 16100 } 16101 16102 // If this is the C FILE type, notify the AST context. 16103 if (IdentifierInfo *II = New->getIdentifier()) 16104 if (!New->isInvalidDecl() && 16105 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 16106 II->isStr("FILE")) 16107 Context.setFILEDecl(New); 16108 16109 if (PrevDecl) 16110 mergeDeclAttributes(New, PrevDecl); 16111 16112 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) 16113 inferGslOwnerPointerAttribute(CXXRD); 16114 16115 // If there's a #pragma GCC visibility in scope, set the visibility of this 16116 // record. 16117 AddPushedVisibilityAttribute(New); 16118 16119 if (isMemberSpecialization && !New->isInvalidDecl()) 16120 CompleteMemberSpecialization(New, Previous); 16121 16122 OwnedDecl = true; 16123 // In C++, don't return an invalid declaration. We can't recover well from 16124 // the cases where we make the type anonymous. 16125 if (Invalid && getLangOpts().CPlusPlus) { 16126 if (New->isBeingDefined()) 16127 if (auto RD = dyn_cast<RecordDecl>(New)) 16128 RD->completeDefinition(); 16129 return nullptr; 16130 } else if (SkipBody && SkipBody->ShouldSkip) { 16131 return SkipBody->Previous; 16132 } else { 16133 return New; 16134 } 16135 } 16136 16137 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 16138 AdjustDeclIfTemplate(TagD); 16139 TagDecl *Tag = cast<TagDecl>(TagD); 16140 16141 // Enter the tag context. 16142 PushDeclContext(S, Tag); 16143 16144 ActOnDocumentableDecl(TagD); 16145 16146 // If there's a #pragma GCC visibility in scope, set the visibility of this 16147 // record. 16148 AddPushedVisibilityAttribute(Tag); 16149 } 16150 16151 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, 16152 SkipBodyInfo &SkipBody) { 16153 if (!hasStructuralCompatLayout(Prev, SkipBody.New)) 16154 return false; 16155 16156 // Make the previous decl visible. 16157 makeMergedDefinitionVisible(SkipBody.Previous); 16158 return true; 16159 } 16160 16161 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 16162 assert(isa<ObjCContainerDecl>(IDecl) && 16163 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 16164 DeclContext *OCD = cast<DeclContext>(IDecl); 16165 assert(OCD->getLexicalParent() == CurContext && 16166 "The next DeclContext should be lexically contained in the current one."); 16167 CurContext = OCD; 16168 return IDecl; 16169 } 16170 16171 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 16172 SourceLocation FinalLoc, 16173 bool IsFinalSpelledSealed, 16174 SourceLocation LBraceLoc) { 16175 AdjustDeclIfTemplate(TagD); 16176 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 16177 16178 FieldCollector->StartClass(); 16179 16180 if (!Record->getIdentifier()) 16181 return; 16182 16183 if (FinalLoc.isValid()) 16184 Record->addAttr(FinalAttr::Create( 16185 Context, FinalLoc, AttributeCommonInfo::AS_Keyword, 16186 static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed))); 16187 16188 // C++ [class]p2: 16189 // [...] The class-name is also inserted into the scope of the 16190 // class itself; this is known as the injected-class-name. For 16191 // purposes of access checking, the injected-class-name is treated 16192 // as if it were a public member name. 16193 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create( 16194 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(), 16195 Record->getLocation(), Record->getIdentifier(), 16196 /*PrevDecl=*/nullptr, 16197 /*DelayTypeCreation=*/true); 16198 Context.getTypeDeclType(InjectedClassName, Record); 16199 InjectedClassName->setImplicit(); 16200 InjectedClassName->setAccess(AS_public); 16201 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 16202 InjectedClassName->setDescribedClassTemplate(Template); 16203 PushOnScopeChains(InjectedClassName, S); 16204 assert(InjectedClassName->isInjectedClassName() && 16205 "Broken injected-class-name"); 16206 } 16207 16208 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 16209 SourceRange BraceRange) { 16210 AdjustDeclIfTemplate(TagD); 16211 TagDecl *Tag = cast<TagDecl>(TagD); 16212 Tag->setBraceRange(BraceRange); 16213 16214 // Make sure we "complete" the definition even it is invalid. 16215 if (Tag->isBeingDefined()) { 16216 assert(Tag->isInvalidDecl() && "We should already have completed it"); 16217 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16218 RD->completeDefinition(); 16219 } 16220 16221 if (isa<CXXRecordDecl>(Tag)) { 16222 FieldCollector->FinishClass(); 16223 } 16224 16225 // Exit this scope of this tag's definition. 16226 PopDeclContext(); 16227 16228 if (getCurLexicalContext()->isObjCContainer() && 16229 Tag->getDeclContext()->isFileContext()) 16230 Tag->setTopLevelDeclInObjCContainer(); 16231 16232 // Notify the consumer that we've defined a tag. 16233 if (!Tag->isInvalidDecl()) 16234 Consumer.HandleTagDeclDefinition(Tag); 16235 } 16236 16237 void Sema::ActOnObjCContainerFinishDefinition() { 16238 // Exit this scope of this interface definition. 16239 PopDeclContext(); 16240 } 16241 16242 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 16243 assert(DC == CurContext && "Mismatch of container contexts"); 16244 OriginalLexicalContext = DC; 16245 ActOnObjCContainerFinishDefinition(); 16246 } 16247 16248 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 16249 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 16250 OriginalLexicalContext = nullptr; 16251 } 16252 16253 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 16254 AdjustDeclIfTemplate(TagD); 16255 TagDecl *Tag = cast<TagDecl>(TagD); 16256 Tag->setInvalidDecl(); 16257 16258 // Make sure we "complete" the definition even it is invalid. 16259 if (Tag->isBeingDefined()) { 16260 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16261 RD->completeDefinition(); 16262 } 16263 16264 // We're undoing ActOnTagStartDefinition here, not 16265 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 16266 // the FieldCollector. 16267 16268 PopDeclContext(); 16269 } 16270 16271 // Note that FieldName may be null for anonymous bitfields. 16272 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 16273 IdentifierInfo *FieldName, 16274 QualType FieldTy, bool IsMsStruct, 16275 Expr *BitWidth, bool *ZeroWidth) { 16276 assert(BitWidth); 16277 if (BitWidth->containsErrors()) 16278 return ExprError(); 16279 16280 // Default to true; that shouldn't confuse checks for emptiness 16281 if (ZeroWidth) 16282 *ZeroWidth = true; 16283 16284 // C99 6.7.2.1p4 - verify the field type. 16285 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 16286 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 16287 // Handle incomplete and sizeless types with a specific error. 16288 if (RequireCompleteSizedType(FieldLoc, FieldTy, 16289 diag::err_field_incomplete_or_sizeless)) 16290 return ExprError(); 16291 if (FieldName) 16292 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 16293 << FieldName << FieldTy << BitWidth->getSourceRange(); 16294 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 16295 << FieldTy << BitWidth->getSourceRange(); 16296 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 16297 UPPC_BitFieldWidth)) 16298 return ExprError(); 16299 16300 // If the bit-width is type- or value-dependent, don't try to check 16301 // it now. 16302 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 16303 return BitWidth; 16304 16305 llvm::APSInt Value; 16306 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 16307 if (ICE.isInvalid()) 16308 return ICE; 16309 BitWidth = ICE.get(); 16310 16311 if (Value != 0 && ZeroWidth) 16312 *ZeroWidth = false; 16313 16314 // Zero-width bitfield is ok for anonymous field. 16315 if (Value == 0 && FieldName) 16316 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 16317 16318 if (Value.isSigned() && Value.isNegative()) { 16319 if (FieldName) 16320 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 16321 << FieldName << Value.toString(10); 16322 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 16323 << Value.toString(10); 16324 } 16325 16326 if (!FieldTy->isDependentType()) { 16327 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 16328 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 16329 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 16330 16331 // Over-wide bitfields are an error in C or when using the MSVC bitfield 16332 // ABI. 16333 bool CStdConstraintViolation = 16334 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 16335 bool MSBitfieldViolation = 16336 Value.ugt(TypeStorageSize) && 16337 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 16338 if (CStdConstraintViolation || MSBitfieldViolation) { 16339 unsigned DiagWidth = 16340 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 16341 if (FieldName) 16342 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 16343 << FieldName << (unsigned)Value.getZExtValue() 16344 << !CStdConstraintViolation << DiagWidth; 16345 16346 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) 16347 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation 16348 << DiagWidth; 16349 } 16350 16351 // Warn on types where the user might conceivably expect to get all 16352 // specified bits as value bits: that's all integral types other than 16353 // 'bool'. 16354 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) { 16355 if (FieldName) 16356 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 16357 << FieldName << (unsigned)Value.getZExtValue() 16358 << (unsigned)TypeWidth; 16359 else 16360 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width) 16361 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth; 16362 } 16363 } 16364 16365 return BitWidth; 16366 } 16367 16368 /// ActOnField - Each field of a C struct/union is passed into this in order 16369 /// to create a FieldDecl object for it. 16370 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 16371 Declarator &D, Expr *BitfieldWidth) { 16372 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 16373 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 16374 /*InitStyle=*/ICIS_NoInit, AS_public); 16375 return Res; 16376 } 16377 16378 /// HandleField - Analyze a field of a C struct or a C++ data member. 16379 /// 16380 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 16381 SourceLocation DeclStart, 16382 Declarator &D, Expr *BitWidth, 16383 InClassInitStyle InitStyle, 16384 AccessSpecifier AS) { 16385 if (D.isDecompositionDeclarator()) { 16386 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 16387 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 16388 << Decomp.getSourceRange(); 16389 return nullptr; 16390 } 16391 16392 IdentifierInfo *II = D.getIdentifier(); 16393 SourceLocation Loc = DeclStart; 16394 if (II) Loc = D.getIdentifierLoc(); 16395 16396 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16397 QualType T = TInfo->getType(); 16398 if (getLangOpts().CPlusPlus) { 16399 CheckExtraCXXDefaultArguments(D); 16400 16401 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 16402 UPPC_DataMemberType)) { 16403 D.setInvalidType(); 16404 T = Context.IntTy; 16405 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 16406 } 16407 } 16408 16409 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 16410 16411 if (D.getDeclSpec().isInlineSpecified()) 16412 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 16413 << getLangOpts().CPlusPlus17; 16414 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 16415 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 16416 diag::err_invalid_thread) 16417 << DeclSpec::getSpecifierName(TSCS); 16418 16419 // Check to see if this name was declared as a member previously 16420 NamedDecl *PrevDecl = nullptr; 16421 LookupResult Previous(*this, II, Loc, LookupMemberName, 16422 ForVisibleRedeclaration); 16423 LookupName(Previous, S); 16424 switch (Previous.getResultKind()) { 16425 case LookupResult::Found: 16426 case LookupResult::FoundUnresolvedValue: 16427 PrevDecl = Previous.getAsSingle<NamedDecl>(); 16428 break; 16429 16430 case LookupResult::FoundOverloaded: 16431 PrevDecl = Previous.getRepresentativeDecl(); 16432 break; 16433 16434 case LookupResult::NotFound: 16435 case LookupResult::NotFoundInCurrentInstantiation: 16436 case LookupResult::Ambiguous: 16437 break; 16438 } 16439 Previous.suppressDiagnostics(); 16440 16441 if (PrevDecl && PrevDecl->isTemplateParameter()) { 16442 // Maybe we will complain about the shadowed template parameter. 16443 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 16444 // Just pretend that we didn't see the previous declaration. 16445 PrevDecl = nullptr; 16446 } 16447 16448 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 16449 PrevDecl = nullptr; 16450 16451 bool Mutable 16452 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 16453 SourceLocation TSSL = D.getBeginLoc(); 16454 FieldDecl *NewFD 16455 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 16456 TSSL, AS, PrevDecl, &D); 16457 16458 if (NewFD->isInvalidDecl()) 16459 Record->setInvalidDecl(); 16460 16461 if (D.getDeclSpec().isModulePrivateSpecified()) 16462 NewFD->setModulePrivate(); 16463 16464 if (NewFD->isInvalidDecl() && PrevDecl) { 16465 // Don't introduce NewFD into scope; there's already something 16466 // with the same name in the same scope. 16467 } else if (II) { 16468 PushOnScopeChains(NewFD, S); 16469 } else 16470 Record->addDecl(NewFD); 16471 16472 return NewFD; 16473 } 16474 16475 /// Build a new FieldDecl and check its well-formedness. 16476 /// 16477 /// This routine builds a new FieldDecl given the fields name, type, 16478 /// record, etc. \p PrevDecl should refer to any previous declaration 16479 /// with the same name and in the same scope as the field to be 16480 /// created. 16481 /// 16482 /// \returns a new FieldDecl. 16483 /// 16484 /// \todo The Declarator argument is a hack. It will be removed once 16485 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 16486 TypeSourceInfo *TInfo, 16487 RecordDecl *Record, SourceLocation Loc, 16488 bool Mutable, Expr *BitWidth, 16489 InClassInitStyle InitStyle, 16490 SourceLocation TSSL, 16491 AccessSpecifier AS, NamedDecl *PrevDecl, 16492 Declarator *D) { 16493 IdentifierInfo *II = Name.getAsIdentifierInfo(); 16494 bool InvalidDecl = false; 16495 if (D) InvalidDecl = D->isInvalidType(); 16496 16497 // If we receive a broken type, recover by assuming 'int' and 16498 // marking this declaration as invalid. 16499 if (T.isNull() || T->containsErrors()) { 16500 InvalidDecl = true; 16501 T = Context.IntTy; 16502 } 16503 16504 QualType EltTy = Context.getBaseElementType(T); 16505 if (!EltTy->isDependentType() && !EltTy->containsErrors()) { 16506 if (RequireCompleteSizedType(Loc, EltTy, 16507 diag::err_field_incomplete_or_sizeless)) { 16508 // Fields of incomplete type force their record to be invalid. 16509 Record->setInvalidDecl(); 16510 InvalidDecl = true; 16511 } else { 16512 NamedDecl *Def; 16513 EltTy->isIncompleteType(&Def); 16514 if (Def && Def->isInvalidDecl()) { 16515 Record->setInvalidDecl(); 16516 InvalidDecl = true; 16517 } 16518 } 16519 } 16520 16521 // TR 18037 does not allow fields to be declared with address space 16522 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() || 16523 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { 16524 Diag(Loc, diag::err_field_with_address_space); 16525 Record->setInvalidDecl(); 16526 InvalidDecl = true; 16527 } 16528 16529 if (LangOpts.OpenCL) { 16530 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 16531 // used as structure or union field: image, sampler, event or block types. 16532 if (T->isEventT() || T->isImageType() || T->isSamplerT() || 16533 T->isBlockPointerType()) { 16534 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 16535 Record->setInvalidDecl(); 16536 InvalidDecl = true; 16537 } 16538 // OpenCL v1.2 s6.9.c: bitfields are not supported. 16539 if (BitWidth) { 16540 Diag(Loc, diag::err_opencl_bitfields); 16541 InvalidDecl = true; 16542 } 16543 } 16544 16545 // Anonymous bit-fields cannot be cv-qualified (CWG 2229). 16546 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && 16547 T.hasQualifiers()) { 16548 InvalidDecl = true; 16549 Diag(Loc, diag::err_anon_bitfield_qualifiers); 16550 } 16551 16552 // C99 6.7.2.1p8: A member of a structure or union may have any type other 16553 // than a variably modified type. 16554 if (!InvalidDecl && T->isVariablyModifiedType()) { 16555 bool SizeIsNegative; 16556 llvm::APSInt Oversized; 16557 16558 TypeSourceInfo *FixedTInfo = 16559 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 16560 SizeIsNegative, 16561 Oversized); 16562 if (FixedTInfo) { 16563 Diag(Loc, diag::warn_illegal_constant_array_size); 16564 TInfo = FixedTInfo; 16565 T = FixedTInfo->getType(); 16566 } else { 16567 if (SizeIsNegative) 16568 Diag(Loc, diag::err_typecheck_negative_array_size); 16569 else if (Oversized.getBoolValue()) 16570 Diag(Loc, diag::err_array_too_large) 16571 << Oversized.toString(10); 16572 else 16573 Diag(Loc, diag::err_typecheck_field_variable_size); 16574 InvalidDecl = true; 16575 } 16576 } 16577 16578 // Fields can not have abstract class types 16579 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 16580 diag::err_abstract_type_in_decl, 16581 AbstractFieldType)) 16582 InvalidDecl = true; 16583 16584 bool ZeroWidth = false; 16585 if (InvalidDecl) 16586 BitWidth = nullptr; 16587 // If this is declared as a bit-field, check the bit-field. 16588 if (BitWidth) { 16589 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 16590 &ZeroWidth).get(); 16591 if (!BitWidth) { 16592 InvalidDecl = true; 16593 BitWidth = nullptr; 16594 ZeroWidth = false; 16595 } 16596 16597 // Only data members can have in-class initializers. 16598 if (BitWidth && !II && InitStyle) { 16599 Diag(Loc, diag::err_anon_bitfield_init); 16600 InvalidDecl = true; 16601 BitWidth = nullptr; 16602 ZeroWidth = false; 16603 } 16604 } 16605 16606 // Check that 'mutable' is consistent with the type of the declaration. 16607 if (!InvalidDecl && Mutable) { 16608 unsigned DiagID = 0; 16609 if (T->isReferenceType()) 16610 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 16611 : diag::err_mutable_reference; 16612 else if (T.isConstQualified()) 16613 DiagID = diag::err_mutable_const; 16614 16615 if (DiagID) { 16616 SourceLocation ErrLoc = Loc; 16617 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 16618 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 16619 Diag(ErrLoc, DiagID); 16620 if (DiagID != diag::ext_mutable_reference) { 16621 Mutable = false; 16622 InvalidDecl = true; 16623 } 16624 } 16625 } 16626 16627 // C++11 [class.union]p8 (DR1460): 16628 // At most one variant member of a union may have a 16629 // brace-or-equal-initializer. 16630 if (InitStyle != ICIS_NoInit) 16631 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 16632 16633 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 16634 BitWidth, Mutable, InitStyle); 16635 if (InvalidDecl) 16636 NewFD->setInvalidDecl(); 16637 16638 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 16639 Diag(Loc, diag::err_duplicate_member) << II; 16640 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 16641 NewFD->setInvalidDecl(); 16642 } 16643 16644 if (!InvalidDecl && getLangOpts().CPlusPlus) { 16645 if (Record->isUnion()) { 16646 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 16647 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 16648 if (RDecl->getDefinition()) { 16649 // C++ [class.union]p1: An object of a class with a non-trivial 16650 // constructor, a non-trivial copy constructor, a non-trivial 16651 // destructor, or a non-trivial copy assignment operator 16652 // cannot be a member of a union, nor can an array of such 16653 // objects. 16654 if (CheckNontrivialField(NewFD)) 16655 NewFD->setInvalidDecl(); 16656 } 16657 } 16658 16659 // C++ [class.union]p1: If a union contains a member of reference type, 16660 // the program is ill-formed, except when compiling with MSVC extensions 16661 // enabled. 16662 if (EltTy->isReferenceType()) { 16663 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 16664 diag::ext_union_member_of_reference_type : 16665 diag::err_union_member_of_reference_type) 16666 << NewFD->getDeclName() << EltTy; 16667 if (!getLangOpts().MicrosoftExt) 16668 NewFD->setInvalidDecl(); 16669 } 16670 } 16671 } 16672 16673 // FIXME: We need to pass in the attributes given an AST 16674 // representation, not a parser representation. 16675 if (D) { 16676 // FIXME: The current scope is almost... but not entirely... correct here. 16677 ProcessDeclAttributes(getCurScope(), NewFD, *D); 16678 16679 if (NewFD->hasAttrs()) 16680 CheckAlignasUnderalignment(NewFD); 16681 } 16682 16683 // In auto-retain/release, infer strong retension for fields of 16684 // retainable type. 16685 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 16686 NewFD->setInvalidDecl(); 16687 16688 if (T.isObjCGCWeak()) 16689 Diag(Loc, diag::warn_attribute_weak_on_field); 16690 16691 NewFD->setAccess(AS); 16692 return NewFD; 16693 } 16694 16695 bool Sema::CheckNontrivialField(FieldDecl *FD) { 16696 assert(FD); 16697 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 16698 16699 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 16700 return false; 16701 16702 QualType EltTy = Context.getBaseElementType(FD->getType()); 16703 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 16704 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 16705 if (RDecl->getDefinition()) { 16706 // We check for copy constructors before constructors 16707 // because otherwise we'll never get complaints about 16708 // copy constructors. 16709 16710 CXXSpecialMember member = CXXInvalid; 16711 // We're required to check for any non-trivial constructors. Since the 16712 // implicit default constructor is suppressed if there are any 16713 // user-declared constructors, we just need to check that there is a 16714 // trivial default constructor and a trivial copy constructor. (We don't 16715 // worry about move constructors here, since this is a C++98 check.) 16716 if (RDecl->hasNonTrivialCopyConstructor()) 16717 member = CXXCopyConstructor; 16718 else if (!RDecl->hasTrivialDefaultConstructor()) 16719 member = CXXDefaultConstructor; 16720 else if (RDecl->hasNonTrivialCopyAssignment()) 16721 member = CXXCopyAssignment; 16722 else if (RDecl->hasNonTrivialDestructor()) 16723 member = CXXDestructor; 16724 16725 if (member != CXXInvalid) { 16726 if (!getLangOpts().CPlusPlus11 && 16727 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 16728 // Objective-C++ ARC: it is an error to have a non-trivial field of 16729 // a union. However, system headers in Objective-C programs 16730 // occasionally have Objective-C lifetime objects within unions, 16731 // and rather than cause the program to fail, we make those 16732 // members unavailable. 16733 SourceLocation Loc = FD->getLocation(); 16734 if (getSourceManager().isInSystemHeader(Loc)) { 16735 if (!FD->hasAttr<UnavailableAttr>()) 16736 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 16737 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 16738 return false; 16739 } 16740 } 16741 16742 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 16743 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 16744 diag::err_illegal_union_or_anon_struct_member) 16745 << FD->getParent()->isUnion() << FD->getDeclName() << member; 16746 DiagnoseNontrivial(RDecl, member); 16747 return !getLangOpts().CPlusPlus11; 16748 } 16749 } 16750 } 16751 16752 return false; 16753 } 16754 16755 /// TranslateIvarVisibility - Translate visibility from a token ID to an 16756 /// AST enum value. 16757 static ObjCIvarDecl::AccessControl 16758 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 16759 switch (ivarVisibility) { 16760 default: llvm_unreachable("Unknown visitibility kind"); 16761 case tok::objc_private: return ObjCIvarDecl::Private; 16762 case tok::objc_public: return ObjCIvarDecl::Public; 16763 case tok::objc_protected: return ObjCIvarDecl::Protected; 16764 case tok::objc_package: return ObjCIvarDecl::Package; 16765 } 16766 } 16767 16768 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 16769 /// in order to create an IvarDecl object for it. 16770 Decl *Sema::ActOnIvar(Scope *S, 16771 SourceLocation DeclStart, 16772 Declarator &D, Expr *BitfieldWidth, 16773 tok::ObjCKeywordKind Visibility) { 16774 16775 IdentifierInfo *II = D.getIdentifier(); 16776 Expr *BitWidth = (Expr*)BitfieldWidth; 16777 SourceLocation Loc = DeclStart; 16778 if (II) Loc = D.getIdentifierLoc(); 16779 16780 // FIXME: Unnamed fields can be handled in various different ways, for 16781 // example, unnamed unions inject all members into the struct namespace! 16782 16783 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16784 QualType T = TInfo->getType(); 16785 16786 if (BitWidth) { 16787 // 6.7.2.1p3, 6.7.2.1p4 16788 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 16789 if (!BitWidth) 16790 D.setInvalidType(); 16791 } else { 16792 // Not a bitfield. 16793 16794 // validate II. 16795 16796 } 16797 if (T->isReferenceType()) { 16798 Diag(Loc, diag::err_ivar_reference_type); 16799 D.setInvalidType(); 16800 } 16801 // C99 6.7.2.1p8: A member of a structure or union may have any type other 16802 // than a variably modified type. 16803 else if (T->isVariablyModifiedType()) { 16804 Diag(Loc, diag::err_typecheck_ivar_variable_size); 16805 D.setInvalidType(); 16806 } 16807 16808 // Get the visibility (access control) for this ivar. 16809 ObjCIvarDecl::AccessControl ac = 16810 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 16811 : ObjCIvarDecl::None; 16812 // Must set ivar's DeclContext to its enclosing interface. 16813 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 16814 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 16815 return nullptr; 16816 ObjCContainerDecl *EnclosingContext; 16817 if (ObjCImplementationDecl *IMPDecl = 16818 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 16819 if (LangOpts.ObjCRuntime.isFragile()) { 16820 // Case of ivar declared in an implementation. Context is that of its class. 16821 EnclosingContext = IMPDecl->getClassInterface(); 16822 assert(EnclosingContext && "Implementation has no class interface!"); 16823 } 16824 else 16825 EnclosingContext = EnclosingDecl; 16826 } else { 16827 if (ObjCCategoryDecl *CDecl = 16828 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 16829 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 16830 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 16831 return nullptr; 16832 } 16833 } 16834 EnclosingContext = EnclosingDecl; 16835 } 16836 16837 // Construct the decl. 16838 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 16839 DeclStart, Loc, II, T, 16840 TInfo, ac, (Expr *)BitfieldWidth); 16841 16842 if (II) { 16843 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 16844 ForVisibleRedeclaration); 16845 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 16846 && !isa<TagDecl>(PrevDecl)) { 16847 Diag(Loc, diag::err_duplicate_member) << II; 16848 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 16849 NewID->setInvalidDecl(); 16850 } 16851 } 16852 16853 // Process attributes attached to the ivar. 16854 ProcessDeclAttributes(S, NewID, D); 16855 16856 if (D.isInvalidType()) 16857 NewID->setInvalidDecl(); 16858 16859 // In ARC, infer 'retaining' for ivars of retainable type. 16860 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 16861 NewID->setInvalidDecl(); 16862 16863 if (D.getDeclSpec().isModulePrivateSpecified()) 16864 NewID->setModulePrivate(); 16865 16866 if (II) { 16867 // FIXME: When interfaces are DeclContexts, we'll need to add 16868 // these to the interface. 16869 S->AddDecl(NewID); 16870 IdResolver.AddDecl(NewID); 16871 } 16872 16873 if (LangOpts.ObjCRuntime.isNonFragile() && 16874 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 16875 Diag(Loc, diag::warn_ivars_in_interface); 16876 16877 return NewID; 16878 } 16879 16880 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 16881 /// class and class extensions. For every class \@interface and class 16882 /// extension \@interface, if the last ivar is a bitfield of any type, 16883 /// then add an implicit `char :0` ivar to the end of that interface. 16884 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 16885 SmallVectorImpl<Decl *> &AllIvarDecls) { 16886 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 16887 return; 16888 16889 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 16890 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 16891 16892 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) 16893 return; 16894 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 16895 if (!ID) { 16896 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 16897 if (!CD->IsClassExtension()) 16898 return; 16899 } 16900 // No need to add this to end of @implementation. 16901 else 16902 return; 16903 } 16904 // All conditions are met. Add a new bitfield to the tail end of ivars. 16905 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 16906 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 16907 16908 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 16909 DeclLoc, DeclLoc, nullptr, 16910 Context.CharTy, 16911 Context.getTrivialTypeSourceInfo(Context.CharTy, 16912 DeclLoc), 16913 ObjCIvarDecl::Private, BW, 16914 true); 16915 AllIvarDecls.push_back(Ivar); 16916 } 16917 16918 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 16919 ArrayRef<Decl *> Fields, SourceLocation LBrac, 16920 SourceLocation RBrac, 16921 const ParsedAttributesView &Attrs) { 16922 assert(EnclosingDecl && "missing record or interface decl"); 16923 16924 // If this is an Objective-C @implementation or category and we have 16925 // new fields here we should reset the layout of the interface since 16926 // it will now change. 16927 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 16928 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 16929 switch (DC->getKind()) { 16930 default: break; 16931 case Decl::ObjCCategory: 16932 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 16933 break; 16934 case Decl::ObjCImplementation: 16935 Context. 16936 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 16937 break; 16938 } 16939 } 16940 16941 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 16942 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl); 16943 16944 // Start counting up the number of named members; make sure to include 16945 // members of anonymous structs and unions in the total. 16946 unsigned NumNamedMembers = 0; 16947 if (Record) { 16948 for (const auto *I : Record->decls()) { 16949 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 16950 if (IFD->getDeclName()) 16951 ++NumNamedMembers; 16952 } 16953 } 16954 16955 // Verify that all the fields are okay. 16956 SmallVector<FieldDecl*, 32> RecFields; 16957 16958 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 16959 i != end; ++i) { 16960 FieldDecl *FD = cast<FieldDecl>(*i); 16961 16962 // Get the type for the field. 16963 const Type *FDTy = FD->getType().getTypePtr(); 16964 16965 if (!FD->isAnonymousStructOrUnion()) { 16966 // Remember all fields written by the user. 16967 RecFields.push_back(FD); 16968 } 16969 16970 // If the field is already invalid for some reason, don't emit more 16971 // diagnostics about it. 16972 if (FD->isInvalidDecl()) { 16973 EnclosingDecl->setInvalidDecl(); 16974 continue; 16975 } 16976 16977 // C99 6.7.2.1p2: 16978 // A structure or union shall not contain a member with 16979 // incomplete or function type (hence, a structure shall not 16980 // contain an instance of itself, but may contain a pointer to 16981 // an instance of itself), except that the last member of a 16982 // structure with more than one named member may have incomplete 16983 // array type; such a structure (and any union containing, 16984 // possibly recursively, a member that is such a structure) 16985 // shall not be a member of a structure or an element of an 16986 // array. 16987 bool IsLastField = (i + 1 == Fields.end()); 16988 if (FDTy->isFunctionType()) { 16989 // Field declared as a function. 16990 Diag(FD->getLocation(), diag::err_field_declared_as_function) 16991 << FD->getDeclName(); 16992 FD->setInvalidDecl(); 16993 EnclosingDecl->setInvalidDecl(); 16994 continue; 16995 } else if (FDTy->isIncompleteArrayType() && 16996 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { 16997 if (Record) { 16998 // Flexible array member. 16999 // Microsoft and g++ is more permissive regarding flexible array. 17000 // It will accept flexible array in union and also 17001 // as the sole element of a struct/class. 17002 unsigned DiagID = 0; 17003 if (!Record->isUnion() && !IsLastField) { 17004 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) 17005 << FD->getDeclName() << FD->getType() << Record->getTagKind(); 17006 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); 17007 FD->setInvalidDecl(); 17008 EnclosingDecl->setInvalidDecl(); 17009 continue; 17010 } else if (Record->isUnion()) 17011 DiagID = getLangOpts().MicrosoftExt 17012 ? diag::ext_flexible_array_union_ms 17013 : getLangOpts().CPlusPlus 17014 ? diag::ext_flexible_array_union_gnu 17015 : diag::err_flexible_array_union; 17016 else if (NumNamedMembers < 1) 17017 DiagID = getLangOpts().MicrosoftExt 17018 ? diag::ext_flexible_array_empty_aggregate_ms 17019 : getLangOpts().CPlusPlus 17020 ? diag::ext_flexible_array_empty_aggregate_gnu 17021 : diag::err_flexible_array_empty_aggregate; 17022 17023 if (DiagID) 17024 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 17025 << Record->getTagKind(); 17026 // While the layout of types that contain virtual bases is not specified 17027 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 17028 // virtual bases after the derived members. This would make a flexible 17029 // array member declared at the end of an object not adjacent to the end 17030 // of the type. 17031 if (CXXRecord && CXXRecord->getNumVBases() != 0) 17032 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 17033 << FD->getDeclName() << Record->getTagKind(); 17034 if (!getLangOpts().C99) 17035 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 17036 << FD->getDeclName() << Record->getTagKind(); 17037 17038 // If the element type has a non-trivial destructor, we would not 17039 // implicitly destroy the elements, so disallow it for now. 17040 // 17041 // FIXME: GCC allows this. We should probably either implicitly delete 17042 // the destructor of the containing class, or just allow this. 17043 QualType BaseElem = Context.getBaseElementType(FD->getType()); 17044 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 17045 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 17046 << FD->getDeclName() << FD->getType(); 17047 FD->setInvalidDecl(); 17048 EnclosingDecl->setInvalidDecl(); 17049 continue; 17050 } 17051 // Okay, we have a legal flexible array member at the end of the struct. 17052 Record->setHasFlexibleArrayMember(true); 17053 } else { 17054 // In ObjCContainerDecl ivars with incomplete array type are accepted, 17055 // unless they are followed by another ivar. That check is done 17056 // elsewhere, after synthesized ivars are known. 17057 } 17058 } else if (!FDTy->isDependentType() && 17059 RequireCompleteSizedType( 17060 FD->getLocation(), FD->getType(), 17061 diag::err_field_incomplete_or_sizeless)) { 17062 // Incomplete type 17063 FD->setInvalidDecl(); 17064 EnclosingDecl->setInvalidDecl(); 17065 continue; 17066 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 17067 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 17068 // A type which contains a flexible array member is considered to be a 17069 // flexible array member. 17070 Record->setHasFlexibleArrayMember(true); 17071 if (!Record->isUnion()) { 17072 // If this is a struct/class and this is not the last element, reject 17073 // it. Note that GCC supports variable sized arrays in the middle of 17074 // structures. 17075 if (!IsLastField) 17076 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 17077 << FD->getDeclName() << FD->getType(); 17078 else { 17079 // We support flexible arrays at the end of structs in 17080 // other structs as an extension. 17081 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 17082 << FD->getDeclName(); 17083 } 17084 } 17085 } 17086 if (isa<ObjCContainerDecl>(EnclosingDecl) && 17087 RequireNonAbstractType(FD->getLocation(), FD->getType(), 17088 diag::err_abstract_type_in_decl, 17089 AbstractIvarType)) { 17090 // Ivars can not have abstract class types 17091 FD->setInvalidDecl(); 17092 } 17093 if (Record && FDTTy->getDecl()->hasObjectMember()) 17094 Record->setHasObjectMember(true); 17095 if (Record && FDTTy->getDecl()->hasVolatileMember()) 17096 Record->setHasVolatileMember(true); 17097 } else if (FDTy->isObjCObjectType()) { 17098 /// A field cannot be an Objective-c object 17099 Diag(FD->getLocation(), diag::err_statically_allocated_object) 17100 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 17101 QualType T = Context.getObjCObjectPointerType(FD->getType()); 17102 FD->setType(T); 17103 } else if (Record && Record->isUnion() && 17104 FD->getType().hasNonTrivialObjCLifetime() && 17105 getSourceManager().isInSystemHeader(FD->getLocation()) && 17106 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() && 17107 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong || 17108 !Context.hasDirectOwnershipQualifier(FD->getType()))) { 17109 // For backward compatibility, fields of C unions declared in system 17110 // headers that have non-trivial ObjC ownership qualifications are marked 17111 // as unavailable unless the qualifier is explicit and __strong. This can 17112 // break ABI compatibility between programs compiled with ARC and MRR, but 17113 // is a better option than rejecting programs using those unions under 17114 // ARC. 17115 FD->addAttr(UnavailableAttr::CreateImplicit( 17116 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, 17117 FD->getLocation())); 17118 } else if (getLangOpts().ObjC && 17119 getLangOpts().getGC() != LangOptions::NonGC && Record && 17120 !Record->hasObjectMember()) { 17121 if (FD->getType()->isObjCObjectPointerType() || 17122 FD->getType().isObjCGCStrong()) 17123 Record->setHasObjectMember(true); 17124 else if (Context.getAsArrayType(FD->getType())) { 17125 QualType BaseType = Context.getBaseElementType(FD->getType()); 17126 if (BaseType->isRecordType() && 17127 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember()) 17128 Record->setHasObjectMember(true); 17129 else if (BaseType->isObjCObjectPointerType() || 17130 BaseType.isObjCGCStrong()) 17131 Record->setHasObjectMember(true); 17132 } 17133 } 17134 17135 if (Record && !getLangOpts().CPlusPlus && 17136 !shouldIgnoreForRecordTriviality(FD)) { 17137 QualType FT = FD->getType(); 17138 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) { 17139 Record->setNonTrivialToPrimitiveDefaultInitialize(true); 17140 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 17141 Record->isUnion()) 17142 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true); 17143 } 17144 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); 17145 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) { 17146 Record->setNonTrivialToPrimitiveCopy(true); 17147 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion()) 17148 Record->setHasNonTrivialToPrimitiveCopyCUnion(true); 17149 } 17150 if (FT.isDestructedType()) { 17151 Record->setNonTrivialToPrimitiveDestroy(true); 17152 Record->setParamDestroyedInCallee(true); 17153 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion()) 17154 Record->setHasNonTrivialToPrimitiveDestructCUnion(true); 17155 } 17156 17157 if (const auto *RT = FT->getAs<RecordType>()) { 17158 if (RT->getDecl()->getArgPassingRestrictions() == 17159 RecordDecl::APK_CanNeverPassInRegs) 17160 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17161 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) 17162 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17163 } 17164 17165 if (Record && FD->getType().isVolatileQualified()) 17166 Record->setHasVolatileMember(true); 17167 // Keep track of the number of named members. 17168 if (FD->getIdentifier()) 17169 ++NumNamedMembers; 17170 } 17171 17172 // Okay, we successfully defined 'Record'. 17173 if (Record) { 17174 bool Completed = false; 17175 if (CXXRecord) { 17176 if (!CXXRecord->isInvalidDecl()) { 17177 // Set access bits correctly on the directly-declared conversions. 17178 for (CXXRecordDecl::conversion_iterator 17179 I = CXXRecord->conversion_begin(), 17180 E = CXXRecord->conversion_end(); I != E; ++I) 17181 I.setAccess((*I)->getAccess()); 17182 } 17183 17184 // Add any implicitly-declared members to this class. 17185 AddImplicitlyDeclaredMembersToClass(CXXRecord); 17186 17187 if (!CXXRecord->isDependentType()) { 17188 if (!CXXRecord->isInvalidDecl()) { 17189 // If we have virtual base classes, we may end up finding multiple 17190 // final overriders for a given virtual function. Check for this 17191 // problem now. 17192 if (CXXRecord->getNumVBases()) { 17193 CXXFinalOverriderMap FinalOverriders; 17194 CXXRecord->getFinalOverriders(FinalOverriders); 17195 17196 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 17197 MEnd = FinalOverriders.end(); 17198 M != MEnd; ++M) { 17199 for (OverridingMethods::iterator SO = M->second.begin(), 17200 SOEnd = M->second.end(); 17201 SO != SOEnd; ++SO) { 17202 assert(SO->second.size() > 0 && 17203 "Virtual function without overriding functions?"); 17204 if (SO->second.size() == 1) 17205 continue; 17206 17207 // C++ [class.virtual]p2: 17208 // In a derived class, if a virtual member function of a base 17209 // class subobject has more than one final overrider the 17210 // program is ill-formed. 17211 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 17212 << (const NamedDecl *)M->first << Record; 17213 Diag(M->first->getLocation(), 17214 diag::note_overridden_virtual_function); 17215 for (OverridingMethods::overriding_iterator 17216 OM = SO->second.begin(), 17217 OMEnd = SO->second.end(); 17218 OM != OMEnd; ++OM) 17219 Diag(OM->Method->getLocation(), diag::note_final_overrider) 17220 << (const NamedDecl *)M->first << OM->Method->getParent(); 17221 17222 Record->setInvalidDecl(); 17223 } 17224 } 17225 CXXRecord->completeDefinition(&FinalOverriders); 17226 Completed = true; 17227 } 17228 } 17229 } 17230 } 17231 17232 if (!Completed) 17233 Record->completeDefinition(); 17234 17235 // Handle attributes before checking the layout. 17236 ProcessDeclAttributeList(S, Record, Attrs); 17237 17238 // We may have deferred checking for a deleted destructor. Check now. 17239 if (CXXRecord) { 17240 auto *Dtor = CXXRecord->getDestructor(); 17241 if (Dtor && Dtor->isImplicit() && 17242 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { 17243 CXXRecord->setImplicitDestructorIsDeleted(); 17244 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 17245 } 17246 } 17247 17248 if (Record->hasAttrs()) { 17249 CheckAlignasUnderalignment(Record); 17250 17251 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 17252 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 17253 IA->getRange(), IA->getBestCase(), 17254 IA->getInheritanceModel()); 17255 } 17256 17257 // Check if the structure/union declaration is a type that can have zero 17258 // size in C. For C this is a language extension, for C++ it may cause 17259 // compatibility problems. 17260 bool CheckForZeroSize; 17261 if (!getLangOpts().CPlusPlus) { 17262 CheckForZeroSize = true; 17263 } else { 17264 // For C++ filter out types that cannot be referenced in C code. 17265 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 17266 CheckForZeroSize = 17267 CXXRecord->getLexicalDeclContext()->isExternCContext() && 17268 !CXXRecord->isDependentType() && 17269 CXXRecord->isCLike(); 17270 } 17271 if (CheckForZeroSize) { 17272 bool ZeroSize = true; 17273 bool IsEmpty = true; 17274 unsigned NonBitFields = 0; 17275 for (RecordDecl::field_iterator I = Record->field_begin(), 17276 E = Record->field_end(); 17277 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 17278 IsEmpty = false; 17279 if (I->isUnnamedBitfield()) { 17280 if (!I->isZeroLengthBitField(Context)) 17281 ZeroSize = false; 17282 } else { 17283 ++NonBitFields; 17284 QualType FieldType = I->getType(); 17285 if (FieldType->isIncompleteType() || 17286 !Context.getTypeSizeInChars(FieldType).isZero()) 17287 ZeroSize = false; 17288 } 17289 } 17290 17291 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 17292 // allowed in C++, but warn if its declaration is inside 17293 // extern "C" block. 17294 if (ZeroSize) { 17295 Diag(RecLoc, getLangOpts().CPlusPlus ? 17296 diag::warn_zero_size_struct_union_in_extern_c : 17297 diag::warn_zero_size_struct_union_compat) 17298 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 17299 } 17300 17301 // Structs without named members are extension in C (C99 6.7.2.1p7), 17302 // but are accepted by GCC. 17303 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 17304 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 17305 diag::ext_no_named_members_in_struct_union) 17306 << Record->isUnion(); 17307 } 17308 } 17309 } else { 17310 ObjCIvarDecl **ClsFields = 17311 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 17312 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 17313 ID->setEndOfDefinitionLoc(RBrac); 17314 // Add ivar's to class's DeclContext. 17315 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17316 ClsFields[i]->setLexicalDeclContext(ID); 17317 ID->addDecl(ClsFields[i]); 17318 } 17319 // Must enforce the rule that ivars in the base classes may not be 17320 // duplicates. 17321 if (ID->getSuperClass()) 17322 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 17323 } else if (ObjCImplementationDecl *IMPDecl = 17324 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 17325 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 17326 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 17327 // Ivar declared in @implementation never belongs to the implementation. 17328 // Only it is in implementation's lexical context. 17329 ClsFields[I]->setLexicalDeclContext(IMPDecl); 17330 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 17331 IMPDecl->setIvarLBraceLoc(LBrac); 17332 IMPDecl->setIvarRBraceLoc(RBrac); 17333 } else if (ObjCCategoryDecl *CDecl = 17334 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 17335 // case of ivars in class extension; all other cases have been 17336 // reported as errors elsewhere. 17337 // FIXME. Class extension does not have a LocEnd field. 17338 // CDecl->setLocEnd(RBrac); 17339 // Add ivar's to class extension's DeclContext. 17340 // Diagnose redeclaration of private ivars. 17341 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 17342 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17343 if (IDecl) { 17344 if (const ObjCIvarDecl *ClsIvar = 17345 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 17346 Diag(ClsFields[i]->getLocation(), 17347 diag::err_duplicate_ivar_declaration); 17348 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 17349 continue; 17350 } 17351 for (const auto *Ext : IDecl->known_extensions()) { 17352 if (const ObjCIvarDecl *ClsExtIvar 17353 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 17354 Diag(ClsFields[i]->getLocation(), 17355 diag::err_duplicate_ivar_declaration); 17356 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 17357 continue; 17358 } 17359 } 17360 } 17361 ClsFields[i]->setLexicalDeclContext(CDecl); 17362 CDecl->addDecl(ClsFields[i]); 17363 } 17364 CDecl->setIvarLBraceLoc(LBrac); 17365 CDecl->setIvarRBraceLoc(RBrac); 17366 } 17367 } 17368 } 17369 17370 /// Determine whether the given integral value is representable within 17371 /// the given type T. 17372 static bool isRepresentableIntegerValue(ASTContext &Context, 17373 llvm::APSInt &Value, 17374 QualType T) { 17375 assert((T->isIntegralType(Context) || T->isEnumeralType()) && 17376 "Integral type required!"); 17377 unsigned BitWidth = Context.getIntWidth(T); 17378 17379 if (Value.isUnsigned() || Value.isNonNegative()) { 17380 if (T->isSignedIntegerOrEnumerationType()) 17381 --BitWidth; 17382 return Value.getActiveBits() <= BitWidth; 17383 } 17384 return Value.getMinSignedBits() <= BitWidth; 17385 } 17386 17387 // Given an integral type, return the next larger integral type 17388 // (or a NULL type of no such type exists). 17389 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 17390 // FIXME: Int128/UInt128 support, which also needs to be introduced into 17391 // enum checking below. 17392 assert((T->isIntegralType(Context) || 17393 T->isEnumeralType()) && "Integral type required!"); 17394 const unsigned NumTypes = 4; 17395 QualType SignedIntegralTypes[NumTypes] = { 17396 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 17397 }; 17398 QualType UnsignedIntegralTypes[NumTypes] = { 17399 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 17400 Context.UnsignedLongLongTy 17401 }; 17402 17403 unsigned BitWidth = Context.getTypeSize(T); 17404 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 17405 : UnsignedIntegralTypes; 17406 for (unsigned I = 0; I != NumTypes; ++I) 17407 if (Context.getTypeSize(Types[I]) > BitWidth) 17408 return Types[I]; 17409 17410 return QualType(); 17411 } 17412 17413 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 17414 EnumConstantDecl *LastEnumConst, 17415 SourceLocation IdLoc, 17416 IdentifierInfo *Id, 17417 Expr *Val) { 17418 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 17419 llvm::APSInt EnumVal(IntWidth); 17420 QualType EltTy; 17421 17422 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 17423 Val = nullptr; 17424 17425 if (Val) 17426 Val = DefaultLvalueConversion(Val).get(); 17427 17428 if (Val) { 17429 if (Enum->isDependentType() || Val->isTypeDependent()) 17430 EltTy = Context.DependentTy; 17431 else { 17432 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) { 17433 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 17434 // constant-expression in the enumerator-definition shall be a converted 17435 // constant expression of the underlying type. 17436 EltTy = Enum->getIntegerType(); 17437 ExprResult Converted = 17438 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 17439 CCEK_Enumerator); 17440 if (Converted.isInvalid()) 17441 Val = nullptr; 17442 else 17443 Val = Converted.get(); 17444 } else if (!Val->isValueDependent() && 17445 !(Val = VerifyIntegerConstantExpression(Val, 17446 &EnumVal).get())) { 17447 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 17448 } else { 17449 if (Enum->isComplete()) { 17450 EltTy = Enum->getIntegerType(); 17451 17452 // In Obj-C and Microsoft mode, require the enumeration value to be 17453 // representable in the underlying type of the enumeration. In C++11, 17454 // we perform a non-narrowing conversion as part of converted constant 17455 // expression checking. 17456 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 17457 if (Context.getTargetInfo() 17458 .getTriple() 17459 .isWindowsMSVCEnvironment()) { 17460 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 17461 } else { 17462 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 17463 } 17464 } 17465 17466 // Cast to the underlying type. 17467 Val = ImpCastExprToType(Val, EltTy, 17468 EltTy->isBooleanType() ? CK_IntegralToBoolean 17469 : CK_IntegralCast) 17470 .get(); 17471 } else if (getLangOpts().CPlusPlus) { 17472 // C++11 [dcl.enum]p5: 17473 // If the underlying type is not fixed, the type of each enumerator 17474 // is the type of its initializing value: 17475 // - If an initializer is specified for an enumerator, the 17476 // initializing value has the same type as the expression. 17477 EltTy = Val->getType(); 17478 } else { 17479 // C99 6.7.2.2p2: 17480 // The expression that defines the value of an enumeration constant 17481 // shall be an integer constant expression that has a value 17482 // representable as an int. 17483 17484 // Complain if the value is not representable in an int. 17485 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 17486 Diag(IdLoc, diag::ext_enum_value_not_int) 17487 << EnumVal.toString(10) << Val->getSourceRange() 17488 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 17489 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 17490 // Force the type of the expression to 'int'. 17491 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 17492 } 17493 EltTy = Val->getType(); 17494 } 17495 } 17496 } 17497 } 17498 17499 if (!Val) { 17500 if (Enum->isDependentType()) 17501 EltTy = Context.DependentTy; 17502 else if (!LastEnumConst) { 17503 // C++0x [dcl.enum]p5: 17504 // If the underlying type is not fixed, the type of each enumerator 17505 // is the type of its initializing value: 17506 // - If no initializer is specified for the first enumerator, the 17507 // initializing value has an unspecified integral type. 17508 // 17509 // GCC uses 'int' for its unspecified integral type, as does 17510 // C99 6.7.2.2p3. 17511 if (Enum->isFixed()) { 17512 EltTy = Enum->getIntegerType(); 17513 } 17514 else { 17515 EltTy = Context.IntTy; 17516 } 17517 } else { 17518 // Assign the last value + 1. 17519 EnumVal = LastEnumConst->getInitVal(); 17520 ++EnumVal; 17521 EltTy = LastEnumConst->getType(); 17522 17523 // Check for overflow on increment. 17524 if (EnumVal < LastEnumConst->getInitVal()) { 17525 // C++0x [dcl.enum]p5: 17526 // If the underlying type is not fixed, the type of each enumerator 17527 // is the type of its initializing value: 17528 // 17529 // - Otherwise the type of the initializing value is the same as 17530 // the type of the initializing value of the preceding enumerator 17531 // unless the incremented value is not representable in that type, 17532 // in which case the type is an unspecified integral type 17533 // sufficient to contain the incremented value. If no such type 17534 // exists, the program is ill-formed. 17535 QualType T = getNextLargerIntegralType(Context, EltTy); 17536 if (T.isNull() || Enum->isFixed()) { 17537 // There is no integral type larger enough to represent this 17538 // value. Complain, then allow the value to wrap around. 17539 EnumVal = LastEnumConst->getInitVal(); 17540 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 17541 ++EnumVal; 17542 if (Enum->isFixed()) 17543 // When the underlying type is fixed, this is ill-formed. 17544 Diag(IdLoc, diag::err_enumerator_wrapped) 17545 << EnumVal.toString(10) 17546 << EltTy; 17547 else 17548 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 17549 << EnumVal.toString(10); 17550 } else { 17551 EltTy = T; 17552 } 17553 17554 // Retrieve the last enumerator's value, extent that type to the 17555 // type that is supposed to be large enough to represent the incremented 17556 // value, then increment. 17557 EnumVal = LastEnumConst->getInitVal(); 17558 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 17559 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 17560 ++EnumVal; 17561 17562 // If we're not in C++, diagnose the overflow of enumerator values, 17563 // which in C99 means that the enumerator value is not representable in 17564 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 17565 // permits enumerator values that are representable in some larger 17566 // integral type. 17567 if (!getLangOpts().CPlusPlus && !T.isNull()) 17568 Diag(IdLoc, diag::warn_enum_value_overflow); 17569 } else if (!getLangOpts().CPlusPlus && 17570 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 17571 // Enforce C99 6.7.2.2p2 even when we compute the next value. 17572 Diag(IdLoc, diag::ext_enum_value_not_int) 17573 << EnumVal.toString(10) << 1; 17574 } 17575 } 17576 } 17577 17578 if (!EltTy->isDependentType()) { 17579 // Make the enumerator value match the signedness and size of the 17580 // enumerator's type. 17581 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 17582 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 17583 } 17584 17585 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 17586 Val, EnumVal); 17587 } 17588 17589 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 17590 SourceLocation IILoc) { 17591 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 17592 !getLangOpts().CPlusPlus) 17593 return SkipBodyInfo(); 17594 17595 // We have an anonymous enum definition. Look up the first enumerator to 17596 // determine if we should merge the definition with an existing one and 17597 // skip the body. 17598 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 17599 forRedeclarationInCurContext()); 17600 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 17601 if (!PrevECD) 17602 return SkipBodyInfo(); 17603 17604 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 17605 NamedDecl *Hidden; 17606 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 17607 SkipBodyInfo Skip; 17608 Skip.Previous = Hidden; 17609 return Skip; 17610 } 17611 17612 return SkipBodyInfo(); 17613 } 17614 17615 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 17616 SourceLocation IdLoc, IdentifierInfo *Id, 17617 const ParsedAttributesView &Attrs, 17618 SourceLocation EqualLoc, Expr *Val) { 17619 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 17620 EnumConstantDecl *LastEnumConst = 17621 cast_or_null<EnumConstantDecl>(lastEnumConst); 17622 17623 // The scope passed in may not be a decl scope. Zip up the scope tree until 17624 // we find one that is. 17625 S = getNonFieldDeclScope(S); 17626 17627 // Verify that there isn't already something declared with this name in this 17628 // scope. 17629 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration); 17630 LookupName(R, S); 17631 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>(); 17632 17633 if (PrevDecl && PrevDecl->isTemplateParameter()) { 17634 // Maybe we will complain about the shadowed template parameter. 17635 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 17636 // Just pretend that we didn't see the previous declaration. 17637 PrevDecl = nullptr; 17638 } 17639 17640 // C++ [class.mem]p15: 17641 // If T is the name of a class, then each of the following shall have a name 17642 // different from T: 17643 // - every enumerator of every member of class T that is an unscoped 17644 // enumerated type 17645 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) 17646 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 17647 DeclarationNameInfo(Id, IdLoc)); 17648 17649 EnumConstantDecl *New = 17650 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 17651 if (!New) 17652 return nullptr; 17653 17654 if (PrevDecl) { 17655 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) { 17656 // Check for other kinds of shadowing not already handled. 17657 CheckShadow(New, PrevDecl, R); 17658 } 17659 17660 // When in C++, we may get a TagDecl with the same name; in this case the 17661 // enum constant will 'hide' the tag. 17662 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 17663 "Received TagDecl when not in C++!"); 17664 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 17665 if (isa<EnumConstantDecl>(PrevDecl)) 17666 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 17667 else 17668 Diag(IdLoc, diag::err_redefinition) << Id; 17669 notePreviousDefinition(PrevDecl, IdLoc); 17670 return nullptr; 17671 } 17672 } 17673 17674 // Process attributes. 17675 ProcessDeclAttributeList(S, New, Attrs); 17676 AddPragmaAttributes(S, New); 17677 17678 // Register this decl in the current scope stack. 17679 New->setAccess(TheEnumDecl->getAccess()); 17680 PushOnScopeChains(New, S); 17681 17682 ActOnDocumentableDecl(New); 17683 17684 return New; 17685 } 17686 17687 // Returns true when the enum initial expression does not trigger the 17688 // duplicate enum warning. A few common cases are exempted as follows: 17689 // Element2 = Element1 17690 // Element2 = Element1 + 1 17691 // Element2 = Element1 - 1 17692 // Where Element2 and Element1 are from the same enum. 17693 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 17694 Expr *InitExpr = ECD->getInitExpr(); 17695 if (!InitExpr) 17696 return true; 17697 InitExpr = InitExpr->IgnoreImpCasts(); 17698 17699 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 17700 if (!BO->isAdditiveOp()) 17701 return true; 17702 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 17703 if (!IL) 17704 return true; 17705 if (IL->getValue() != 1) 17706 return true; 17707 17708 InitExpr = BO->getLHS(); 17709 } 17710 17711 // This checks if the elements are from the same enum. 17712 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 17713 if (!DRE) 17714 return true; 17715 17716 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 17717 if (!EnumConstant) 17718 return true; 17719 17720 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 17721 Enum) 17722 return true; 17723 17724 return false; 17725 } 17726 17727 // Emits a warning when an element is implicitly set a value that 17728 // a previous element has already been set to. 17729 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 17730 EnumDecl *Enum, QualType EnumType) { 17731 // Avoid anonymous enums 17732 if (!Enum->getIdentifier()) 17733 return; 17734 17735 // Only check for small enums. 17736 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 17737 return; 17738 17739 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 17740 return; 17741 17742 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 17743 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; 17744 17745 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 17746 17747 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map. 17748 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap; 17749 17750 // Use int64_t as a key to avoid needing special handling for map keys. 17751 auto EnumConstantToKey = [](const EnumConstantDecl *D) { 17752 llvm::APSInt Val = D->getInitVal(); 17753 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); 17754 }; 17755 17756 DuplicatesVector DupVector; 17757 ValueToVectorMap EnumMap; 17758 17759 // Populate the EnumMap with all values represented by enum constants without 17760 // an initializer. 17761 for (auto *Element : Elements) { 17762 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); 17763 17764 // Null EnumConstantDecl means a previous diagnostic has been emitted for 17765 // this constant. Skip this enum since it may be ill-formed. 17766 if (!ECD) { 17767 return; 17768 } 17769 17770 // Constants with initalizers are handled in the next loop. 17771 if (ECD->getInitExpr()) 17772 continue; 17773 17774 // Duplicate values are handled in the next loop. 17775 EnumMap.insert({EnumConstantToKey(ECD), ECD}); 17776 } 17777 17778 if (EnumMap.size() == 0) 17779 return; 17780 17781 // Create vectors for any values that has duplicates. 17782 for (auto *Element : Elements) { 17783 // The last loop returned if any constant was null. 17784 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); 17785 if (!ValidDuplicateEnum(ECD, Enum)) 17786 continue; 17787 17788 auto Iter = EnumMap.find(EnumConstantToKey(ECD)); 17789 if (Iter == EnumMap.end()) 17790 continue; 17791 17792 DeclOrVector& Entry = Iter->second; 17793 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 17794 // Ensure constants are different. 17795 if (D == ECD) 17796 continue; 17797 17798 // Create new vector and push values onto it. 17799 auto Vec = std::make_unique<ECDVector>(); 17800 Vec->push_back(D); 17801 Vec->push_back(ECD); 17802 17803 // Update entry to point to the duplicates vector. 17804 Entry = Vec.get(); 17805 17806 // Store the vector somewhere we can consult later for quick emission of 17807 // diagnostics. 17808 DupVector.emplace_back(std::move(Vec)); 17809 continue; 17810 } 17811 17812 ECDVector *Vec = Entry.get<ECDVector*>(); 17813 // Make sure constants are not added more than once. 17814 if (*Vec->begin() == ECD) 17815 continue; 17816 17817 Vec->push_back(ECD); 17818 } 17819 17820 // Emit diagnostics. 17821 for (const auto &Vec : DupVector) { 17822 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 17823 17824 // Emit warning for one enum constant. 17825 auto *FirstECD = Vec->front(); 17826 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) 17827 << FirstECD << FirstECD->getInitVal().toString(10) 17828 << FirstECD->getSourceRange(); 17829 17830 // Emit one note for each of the remaining enum constants with 17831 // the same value. 17832 for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end())) 17833 S.Diag(ECD->getLocation(), diag::note_duplicate_element) 17834 << ECD << ECD->getInitVal().toString(10) 17835 << ECD->getSourceRange(); 17836 } 17837 } 17838 17839 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 17840 bool AllowMask) const { 17841 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 17842 assert(ED->isCompleteDefinition() && "expected enum definition"); 17843 17844 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 17845 llvm::APInt &FlagBits = R.first->second; 17846 17847 if (R.second) { 17848 for (auto *E : ED->enumerators()) { 17849 const auto &EVal = E->getInitVal(); 17850 // Only single-bit enumerators introduce new flag values. 17851 if (EVal.isPowerOf2()) 17852 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 17853 } 17854 } 17855 17856 // A value is in a flag enum if either its bits are a subset of the enum's 17857 // flag bits (the first condition) or we are allowing masks and the same is 17858 // true of its complement (the second condition). When masks are allowed, we 17859 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 17860 // 17861 // While it's true that any value could be used as a mask, the assumption is 17862 // that a mask will have all of the insignificant bits set. Anything else is 17863 // likely a logic error. 17864 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 17865 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 17866 } 17867 17868 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 17869 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S, 17870 const ParsedAttributesView &Attrs) { 17871 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 17872 QualType EnumType = Context.getTypeDeclType(Enum); 17873 17874 ProcessDeclAttributeList(S, Enum, Attrs); 17875 17876 if (Enum->isDependentType()) { 17877 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 17878 EnumConstantDecl *ECD = 17879 cast_or_null<EnumConstantDecl>(Elements[i]); 17880 if (!ECD) continue; 17881 17882 ECD->setType(EnumType); 17883 } 17884 17885 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 17886 return; 17887 } 17888 17889 // TODO: If the result value doesn't fit in an int, it must be a long or long 17890 // long value. ISO C does not support this, but GCC does as an extension, 17891 // emit a warning. 17892 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 17893 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 17894 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 17895 17896 // Verify that all the values are okay, compute the size of the values, and 17897 // reverse the list. 17898 unsigned NumNegativeBits = 0; 17899 unsigned NumPositiveBits = 0; 17900 17901 // Keep track of whether all elements have type int. 17902 bool AllElementsInt = true; 17903 17904 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 17905 EnumConstantDecl *ECD = 17906 cast_or_null<EnumConstantDecl>(Elements[i]); 17907 if (!ECD) continue; // Already issued a diagnostic. 17908 17909 const llvm::APSInt &InitVal = ECD->getInitVal(); 17910 17911 // Keep track of the size of positive and negative values. 17912 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 17913 NumPositiveBits = std::max(NumPositiveBits, 17914 (unsigned)InitVal.getActiveBits()); 17915 else 17916 NumNegativeBits = std::max(NumNegativeBits, 17917 (unsigned)InitVal.getMinSignedBits()); 17918 17919 // Keep track of whether every enum element has type int (very common). 17920 if (AllElementsInt) 17921 AllElementsInt = ECD->getType() == Context.IntTy; 17922 } 17923 17924 // Figure out the type that should be used for this enum. 17925 QualType BestType; 17926 unsigned BestWidth; 17927 17928 // C++0x N3000 [conv.prom]p3: 17929 // An rvalue of an unscoped enumeration type whose underlying 17930 // type is not fixed can be converted to an rvalue of the first 17931 // of the following types that can represent all the values of 17932 // the enumeration: int, unsigned int, long int, unsigned long 17933 // int, long long int, or unsigned long long int. 17934 // C99 6.4.4.3p2: 17935 // An identifier declared as an enumeration constant has type int. 17936 // The C99 rule is modified by a gcc extension 17937 QualType BestPromotionType; 17938 17939 bool Packed = Enum->hasAttr<PackedAttr>(); 17940 // -fshort-enums is the equivalent to specifying the packed attribute on all 17941 // enum definitions. 17942 if (LangOpts.ShortEnums) 17943 Packed = true; 17944 17945 // If the enum already has a type because it is fixed or dictated by the 17946 // target, promote that type instead of analyzing the enumerators. 17947 if (Enum->isComplete()) { 17948 BestType = Enum->getIntegerType(); 17949 if (BestType->isPromotableIntegerType()) 17950 BestPromotionType = Context.getPromotedIntegerType(BestType); 17951 else 17952 BestPromotionType = BestType; 17953 17954 BestWidth = Context.getIntWidth(BestType); 17955 } 17956 else if (NumNegativeBits) { 17957 // If there is a negative value, figure out the smallest integer type (of 17958 // int/long/longlong) that fits. 17959 // If it's packed, check also if it fits a char or a short. 17960 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 17961 BestType = Context.SignedCharTy; 17962 BestWidth = CharWidth; 17963 } else if (Packed && NumNegativeBits <= ShortWidth && 17964 NumPositiveBits < ShortWidth) { 17965 BestType = Context.ShortTy; 17966 BestWidth = ShortWidth; 17967 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 17968 BestType = Context.IntTy; 17969 BestWidth = IntWidth; 17970 } else { 17971 BestWidth = Context.getTargetInfo().getLongWidth(); 17972 17973 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 17974 BestType = Context.LongTy; 17975 } else { 17976 BestWidth = Context.getTargetInfo().getLongLongWidth(); 17977 17978 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 17979 Diag(Enum->getLocation(), diag::ext_enum_too_large); 17980 BestType = Context.LongLongTy; 17981 } 17982 } 17983 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 17984 } else { 17985 // If there is no negative value, figure out the smallest type that fits 17986 // all of the enumerator values. 17987 // If it's packed, check also if it fits a char or a short. 17988 if (Packed && NumPositiveBits <= CharWidth) { 17989 BestType = Context.UnsignedCharTy; 17990 BestPromotionType = Context.IntTy; 17991 BestWidth = CharWidth; 17992 } else if (Packed && NumPositiveBits <= ShortWidth) { 17993 BestType = Context.UnsignedShortTy; 17994 BestPromotionType = Context.IntTy; 17995 BestWidth = ShortWidth; 17996 } else if (NumPositiveBits <= IntWidth) { 17997 BestType = Context.UnsignedIntTy; 17998 BestWidth = IntWidth; 17999 BestPromotionType 18000 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18001 ? Context.UnsignedIntTy : Context.IntTy; 18002 } else if (NumPositiveBits <= 18003 (BestWidth = Context.getTargetInfo().getLongWidth())) { 18004 BestType = Context.UnsignedLongTy; 18005 BestPromotionType 18006 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18007 ? Context.UnsignedLongTy : Context.LongTy; 18008 } else { 18009 BestWidth = Context.getTargetInfo().getLongLongWidth(); 18010 assert(NumPositiveBits <= BestWidth && 18011 "How could an initializer get larger than ULL?"); 18012 BestType = Context.UnsignedLongLongTy; 18013 BestPromotionType 18014 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18015 ? Context.UnsignedLongLongTy : Context.LongLongTy; 18016 } 18017 } 18018 18019 // Loop over all of the enumerator constants, changing their types to match 18020 // the type of the enum if needed. 18021 for (auto *D : Elements) { 18022 auto *ECD = cast_or_null<EnumConstantDecl>(D); 18023 if (!ECD) continue; // Already issued a diagnostic. 18024 18025 // Standard C says the enumerators have int type, but we allow, as an 18026 // extension, the enumerators to be larger than int size. If each 18027 // enumerator value fits in an int, type it as an int, otherwise type it the 18028 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 18029 // that X has type 'int', not 'unsigned'. 18030 18031 // Determine whether the value fits into an int. 18032 llvm::APSInt InitVal = ECD->getInitVal(); 18033 18034 // If it fits into an integer type, force it. Otherwise force it to match 18035 // the enum decl type. 18036 QualType NewTy; 18037 unsigned NewWidth; 18038 bool NewSign; 18039 if (!getLangOpts().CPlusPlus && 18040 !Enum->isFixed() && 18041 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 18042 NewTy = Context.IntTy; 18043 NewWidth = IntWidth; 18044 NewSign = true; 18045 } else if (ECD->getType() == BestType) { 18046 // Already the right type! 18047 if (getLangOpts().CPlusPlus) 18048 // C++ [dcl.enum]p4: Following the closing brace of an 18049 // enum-specifier, each enumerator has the type of its 18050 // enumeration. 18051 ECD->setType(EnumType); 18052 continue; 18053 } else { 18054 NewTy = BestType; 18055 NewWidth = BestWidth; 18056 NewSign = BestType->isSignedIntegerOrEnumerationType(); 18057 } 18058 18059 // Adjust the APSInt value. 18060 InitVal = InitVal.extOrTrunc(NewWidth); 18061 InitVal.setIsSigned(NewSign); 18062 ECD->setInitVal(InitVal); 18063 18064 // Adjust the Expr initializer and type. 18065 if (ECD->getInitExpr() && 18066 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 18067 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 18068 CK_IntegralCast, 18069 ECD->getInitExpr(), 18070 /*base paths*/ nullptr, 18071 VK_RValue)); 18072 if (getLangOpts().CPlusPlus) 18073 // C++ [dcl.enum]p4: Following the closing brace of an 18074 // enum-specifier, each enumerator has the type of its 18075 // enumeration. 18076 ECD->setType(EnumType); 18077 else 18078 ECD->setType(NewTy); 18079 } 18080 18081 Enum->completeDefinition(BestType, BestPromotionType, 18082 NumPositiveBits, NumNegativeBits); 18083 18084 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 18085 18086 if (Enum->isClosedFlag()) { 18087 for (Decl *D : Elements) { 18088 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 18089 if (!ECD) continue; // Already issued a diagnostic. 18090 18091 llvm::APSInt InitVal = ECD->getInitVal(); 18092 if (InitVal != 0 && !InitVal.isPowerOf2() && 18093 !IsValueInFlagEnum(Enum, InitVal, true)) 18094 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 18095 << ECD << Enum; 18096 } 18097 } 18098 18099 // Now that the enum type is defined, ensure it's not been underaligned. 18100 if (Enum->hasAttrs()) 18101 CheckAlignasUnderalignment(Enum); 18102 } 18103 18104 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 18105 SourceLocation StartLoc, 18106 SourceLocation EndLoc) { 18107 StringLiteral *AsmString = cast<StringLiteral>(expr); 18108 18109 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 18110 AsmString, StartLoc, 18111 EndLoc); 18112 CurContext->addDecl(New); 18113 return New; 18114 } 18115 18116 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 18117 IdentifierInfo* AliasName, 18118 SourceLocation PragmaLoc, 18119 SourceLocation NameLoc, 18120 SourceLocation AliasNameLoc) { 18121 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 18122 LookupOrdinaryName); 18123 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc), 18124 AttributeCommonInfo::AS_Pragma); 18125 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit( 18126 Context, AliasName->getName(), /*LiteralLabel=*/true, Info); 18127 18128 // If a declaration that: 18129 // 1) declares a function or a variable 18130 // 2) has external linkage 18131 // already exists, add a label attribute to it. 18132 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18133 if (isDeclExternC(PrevDecl)) 18134 PrevDecl->addAttr(Attr); 18135 else 18136 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 18137 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 18138 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 18139 } else 18140 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 18141 } 18142 18143 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 18144 SourceLocation PragmaLoc, 18145 SourceLocation NameLoc) { 18146 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 18147 18148 if (PrevDecl) { 18149 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma)); 18150 } else { 18151 (void)WeakUndeclaredIdentifiers.insert( 18152 std::pair<IdentifierInfo*,WeakInfo> 18153 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 18154 } 18155 } 18156 18157 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 18158 IdentifierInfo* AliasName, 18159 SourceLocation PragmaLoc, 18160 SourceLocation NameLoc, 18161 SourceLocation AliasNameLoc) { 18162 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 18163 LookupOrdinaryName); 18164 WeakInfo W = WeakInfo(Name, NameLoc); 18165 18166 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18167 if (!PrevDecl->hasAttr<AliasAttr>()) 18168 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 18169 DeclApplyPragmaWeak(TUScope, ND, W); 18170 } else { 18171 (void)WeakUndeclaredIdentifiers.insert( 18172 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 18173 } 18174 } 18175 18176 Decl *Sema::getObjCDeclContext() const { 18177 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 18178 } 18179 18180 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD, 18181 bool Final) { 18182 // SYCL functions can be template, so we check if they have appropriate 18183 // attribute prior to checking if it is a template. 18184 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>()) 18185 return FunctionEmissionStatus::Emitted; 18186 18187 // Templates are emitted when they're instantiated. 18188 if (FD->isDependentContext()) 18189 return FunctionEmissionStatus::TemplateDiscarded; 18190 18191 FunctionEmissionStatus OMPES = FunctionEmissionStatus::Unknown; 18192 if (LangOpts.OpenMPIsDevice) { 18193 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18194 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18195 if (DevTy.hasValue()) { 18196 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host) 18197 OMPES = FunctionEmissionStatus::OMPDiscarded; 18198 else if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost || 18199 *DevTy == OMPDeclareTargetDeclAttr::DT_Any) { 18200 OMPES = FunctionEmissionStatus::Emitted; 18201 } 18202 } 18203 } else if (LangOpts.OpenMP) { 18204 // In OpenMP 4.5 all the functions are host functions. 18205 if (LangOpts.OpenMP <= 45) { 18206 OMPES = FunctionEmissionStatus::Emitted; 18207 } else { 18208 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18209 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18210 // In OpenMP 5.0 or above, DevTy may be changed later by 18211 // #pragma omp declare target to(*) device_type(*). Therefore DevTy 18212 // having no value does not imply host. The emission status will be 18213 // checked again at the end of compilation unit. 18214 if (DevTy.hasValue()) { 18215 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) { 18216 OMPES = FunctionEmissionStatus::OMPDiscarded; 18217 } else if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host || 18218 *DevTy == OMPDeclareTargetDeclAttr::DT_Any) 18219 OMPES = FunctionEmissionStatus::Emitted; 18220 } else if (Final) 18221 OMPES = FunctionEmissionStatus::Emitted; 18222 } 18223 } 18224 if (OMPES == FunctionEmissionStatus::OMPDiscarded || 18225 (OMPES == FunctionEmissionStatus::Emitted && !LangOpts.CUDA)) 18226 return OMPES; 18227 18228 if (LangOpts.CUDA) { 18229 // When compiling for device, host functions are never emitted. Similarly, 18230 // when compiling for host, device and global functions are never emitted. 18231 // (Technically, we do emit a host-side stub for global functions, but this 18232 // doesn't count for our purposes here.) 18233 Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD); 18234 if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host) 18235 return FunctionEmissionStatus::CUDADiscarded; 18236 if (!LangOpts.CUDAIsDevice && 18237 (T == Sema::CFT_Device || T == Sema::CFT_Global)) 18238 return FunctionEmissionStatus::CUDADiscarded; 18239 18240 // Check whether this function is externally visible -- if so, it's 18241 // known-emitted. 18242 // 18243 // We have to check the GVA linkage of the function's *definition* -- if we 18244 // only have a declaration, we don't know whether or not the function will 18245 // be emitted, because (say) the definition could include "inline". 18246 FunctionDecl *Def = FD->getDefinition(); 18247 18248 if (Def && 18249 !isDiscardableGVALinkage(getASTContext().GetGVALinkageForFunction(Def)) 18250 && (!LangOpts.OpenMP || OMPES == FunctionEmissionStatus::Emitted)) 18251 return FunctionEmissionStatus::Emitted; 18252 } 18253 18254 // Otherwise, the function is known-emitted if it's in our set of 18255 // known-emitted functions. 18256 return FunctionEmissionStatus::Unknown; 18257 } 18258 18259 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) { 18260 // Host-side references to a __global__ function refer to the stub, so the 18261 // function itself is never emitted and therefore should not be marked. 18262 // If we have host fn calls kernel fn calls host+device, the HD function 18263 // does not get instantiated on the host. We model this by omitting at the 18264 // call to the kernel from the callgraph. This ensures that, when compiling 18265 // for host, only HD functions actually called from the host get marked as 18266 // known-emitted. 18267 return LangOpts.CUDA && !LangOpts.CUDAIsDevice && 18268 IdentifyCUDATarget(Callee) == CFT_Global; 18269 } 18270