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 (SS->isValid() && SS->getScopeRep()->containsErrors()) { 754 SuggestedType = 755 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get(); 756 } else if (isDependentScopeSpecifier(*SS)) { 757 unsigned DiagID = diag::err_typename_missing; 758 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 759 DiagID = diag::ext_typename_missing; 760 761 Diag(SS->getRange().getBegin(), DiagID) 762 << SS->getScopeRep() << II->getName() 763 << SourceRange(SS->getRange().getBegin(), IILoc) 764 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 765 SuggestedType = ActOnTypenameType(S, SourceLocation(), 766 *SS, *II, IILoc).get(); 767 } else { 768 assert(SS && SS->isInvalid() && 769 "Invalid scope specifier has already been diagnosed"); 770 } 771 } 772 773 /// Determine whether the given result set contains either a type name 774 /// or 775 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 776 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 777 NextToken.is(tok::less); 778 779 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 780 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 781 return true; 782 783 if (CheckTemplate && isa<TemplateDecl>(*I)) 784 return true; 785 } 786 787 return false; 788 } 789 790 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 791 Scope *S, CXXScopeSpec &SS, 792 IdentifierInfo *&Name, 793 SourceLocation NameLoc) { 794 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 795 SemaRef.LookupParsedName(R, S, &SS); 796 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 797 StringRef FixItTagName; 798 switch (Tag->getTagKind()) { 799 case TTK_Class: 800 FixItTagName = "class "; 801 break; 802 803 case TTK_Enum: 804 FixItTagName = "enum "; 805 break; 806 807 case TTK_Struct: 808 FixItTagName = "struct "; 809 break; 810 811 case TTK_Interface: 812 FixItTagName = "__interface "; 813 break; 814 815 case TTK_Union: 816 FixItTagName = "union "; 817 break; 818 } 819 820 StringRef TagName = FixItTagName.drop_back(); 821 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 822 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 823 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 824 825 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 826 I != IEnd; ++I) 827 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 828 << Name << TagName; 829 830 // Replace lookup results with just the tag decl. 831 Result.clear(Sema::LookupTagName); 832 SemaRef.LookupParsedName(Result, S, &SS); 833 return true; 834 } 835 836 return false; 837 } 838 839 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 840 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 841 QualType T, SourceLocation NameLoc) { 842 ASTContext &Context = S.Context; 843 844 TypeLocBuilder Builder; 845 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 846 847 T = S.getElaboratedType(ETK_None, SS, T); 848 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 849 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 850 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 851 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 852 } 853 854 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, 855 IdentifierInfo *&Name, 856 SourceLocation NameLoc, 857 const Token &NextToken, 858 CorrectionCandidateCallback *CCC) { 859 DeclarationNameInfo NameInfo(Name, NameLoc); 860 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 861 862 assert(NextToken.isNot(tok::coloncolon) && 863 "parse nested name specifiers before calling ClassifyName"); 864 if (getLangOpts().CPlusPlus && SS.isSet() && 865 isCurrentClassName(*Name, S, &SS)) { 866 // Per [class.qual]p2, this names the constructors of SS, not the 867 // injected-class-name. We don't have a classification for that. 868 // There's not much point caching this result, since the parser 869 // will reject it later. 870 return NameClassification::Unknown(); 871 } 872 873 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 874 LookupParsedName(Result, S, &SS, !CurMethod); 875 876 if (SS.isInvalid()) 877 return NameClassification::Error(); 878 879 // For unqualified lookup in a class template in MSVC mode, look into 880 // dependent base classes where the primary class template is known. 881 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { 882 if (ParsedType TypeInBase = 883 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) 884 return TypeInBase; 885 } 886 887 // Perform lookup for Objective-C instance variables (including automatically 888 // synthesized instance variables), if we're in an Objective-C method. 889 // FIXME: This lookup really, really needs to be folded in to the normal 890 // unqualified lookup mechanism. 891 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 892 DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name); 893 if (Ivar.isInvalid()) 894 return NameClassification::Error(); 895 if (Ivar.isUsable()) 896 return NameClassification::NonType(cast<NamedDecl>(Ivar.get())); 897 898 // We defer builtin creation until after ivar lookup inside ObjC methods. 899 if (Result.empty()) 900 LookupBuiltin(Result); 901 } 902 903 bool SecondTry = false; 904 bool IsFilteredTemplateName = false; 905 906 Corrected: 907 switch (Result.getResultKind()) { 908 case LookupResult::NotFound: 909 // If an unqualified-id is followed by a '(', then we have a function 910 // call. 911 if (SS.isEmpty() && NextToken.is(tok::l_paren)) { 912 // In C++, this is an ADL-only call. 913 // FIXME: Reference? 914 if (getLangOpts().CPlusPlus) 915 return NameClassification::UndeclaredNonType(); 916 917 // C90 6.3.2.2: 918 // If the expression that precedes the parenthesized argument list in a 919 // function call consists solely of an identifier, and if no 920 // declaration is visible for this identifier, the identifier is 921 // implicitly declared exactly as if, in the innermost block containing 922 // the function call, the declaration 923 // 924 // extern int identifier (); 925 // 926 // appeared. 927 // 928 // We also allow this in C99 as an extension. 929 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) 930 return NameClassification::NonType(D); 931 } 932 933 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) { 934 // In C++20 onwards, this could be an ADL-only call to a function 935 // template, and we're required to assume that this is a template name. 936 // 937 // FIXME: Find a way to still do typo correction in this case. 938 TemplateName Template = 939 Context.getAssumedTemplateName(NameInfo.getName()); 940 return NameClassification::UndeclaredTemplate(Template); 941 } 942 943 // In C, we first see whether there is a tag type by the same name, in 944 // which case it's likely that the user just forgot to write "enum", 945 // "struct", or "union". 946 if (!getLangOpts().CPlusPlus && !SecondTry && 947 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 948 break; 949 } 950 951 // Perform typo correction to determine if there is another name that is 952 // close to this name. 953 if (!SecondTry && CCC) { 954 SecondTry = true; 955 if (TypoCorrection Corrected = 956 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S, 957 &SS, *CCC, CTK_ErrorRecovery)) { 958 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 959 unsigned QualifiedDiag = diag::err_no_member_suggest; 960 961 NamedDecl *FirstDecl = Corrected.getFoundDecl(); 962 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); 963 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 964 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 965 UnqualifiedDiag = diag::err_no_template_suggest; 966 QualifiedDiag = diag::err_no_member_template_suggest; 967 } else if (UnderlyingFirstDecl && 968 (isa<TypeDecl>(UnderlyingFirstDecl) || 969 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 970 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 971 UnqualifiedDiag = diag::err_unknown_typename_suggest; 972 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 973 } 974 975 if (SS.isEmpty()) { 976 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 977 } else {// FIXME: is this even reachable? Test it. 978 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 979 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 980 Name->getName().equals(CorrectedStr); 981 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 982 << Name << computeDeclContext(SS, false) 983 << DroppedSpecifier << SS.getRange()); 984 } 985 986 // Update the name, so that the caller has the new name. 987 Name = Corrected.getCorrectionAsIdentifierInfo(); 988 989 // Typo correction corrected to a keyword. 990 if (Corrected.isKeyword()) 991 return Name; 992 993 // Also update the LookupResult... 994 // FIXME: This should probably go away at some point 995 Result.clear(); 996 Result.setLookupName(Corrected.getCorrection()); 997 if (FirstDecl) 998 Result.addDecl(FirstDecl); 999 1000 // If we found an Objective-C instance variable, let 1001 // LookupInObjCMethod build the appropriate expression to 1002 // reference the ivar. 1003 // FIXME: This is a gross hack. 1004 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 1005 DeclResult R = 1006 LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier()); 1007 if (R.isInvalid()) 1008 return NameClassification::Error(); 1009 if (R.isUsable()) 1010 return NameClassification::NonType(Ivar); 1011 } 1012 1013 goto Corrected; 1014 } 1015 } 1016 1017 // We failed to correct; just fall through and let the parser deal with it. 1018 Result.suppressDiagnostics(); 1019 return NameClassification::Unknown(); 1020 1021 case LookupResult::NotFoundInCurrentInstantiation: { 1022 // We performed name lookup into the current instantiation, and there were 1023 // dependent bases, so we treat this result the same way as any other 1024 // dependent nested-name-specifier. 1025 1026 // C++ [temp.res]p2: 1027 // A name used in a template declaration or definition and that is 1028 // dependent on a template-parameter is assumed not to name a type 1029 // unless the applicable name lookup finds a type name or the name is 1030 // qualified by the keyword typename. 1031 // 1032 // FIXME: If the next token is '<', we might want to ask the parser to 1033 // perform some heroics to see if we actually have a 1034 // template-argument-list, which would indicate a missing 'template' 1035 // keyword here. 1036 return NameClassification::DependentNonType(); 1037 } 1038 1039 case LookupResult::Found: 1040 case LookupResult::FoundOverloaded: 1041 case LookupResult::FoundUnresolvedValue: 1042 break; 1043 1044 case LookupResult::Ambiguous: 1045 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1046 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true, 1047 /*AllowDependent=*/false)) { 1048 // C++ [temp.local]p3: 1049 // A lookup that finds an injected-class-name (10.2) can result in an 1050 // ambiguity in certain cases (for example, if it is found in more than 1051 // one base class). If all of the injected-class-names that are found 1052 // refer to specializations of the same class template, and if the name 1053 // is followed by a template-argument-list, the reference refers to the 1054 // class template itself and not a specialization thereof, and is not 1055 // ambiguous. 1056 // 1057 // This filtering can make an ambiguous result into an unambiguous one, 1058 // so try again after filtering out template names. 1059 FilterAcceptableTemplateNames(Result); 1060 if (!Result.isAmbiguous()) { 1061 IsFilteredTemplateName = true; 1062 break; 1063 } 1064 } 1065 1066 // Diagnose the ambiguity and return an error. 1067 return NameClassification::Error(); 1068 } 1069 1070 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1071 (IsFilteredTemplateName || 1072 hasAnyAcceptableTemplateNames( 1073 Result, /*AllowFunctionTemplates=*/true, 1074 /*AllowDependent=*/false, 1075 /*AllowNonTemplateFunctions*/ SS.isEmpty() && 1076 getLangOpts().CPlusPlus20))) { 1077 // C++ [temp.names]p3: 1078 // After name lookup (3.4) finds that a name is a template-name or that 1079 // an operator-function-id or a literal- operator-id refers to a set of 1080 // overloaded functions any member of which is a function template if 1081 // this is followed by a <, the < is always taken as the delimiter of a 1082 // template-argument-list and never as the less-than operator. 1083 // C++2a [temp.names]p2: 1084 // A name is also considered to refer to a template if it is an 1085 // unqualified-id followed by a < and name lookup finds either one 1086 // or more functions or finds nothing. 1087 if (!IsFilteredTemplateName) 1088 FilterAcceptableTemplateNames(Result); 1089 1090 bool IsFunctionTemplate; 1091 bool IsVarTemplate; 1092 TemplateName Template; 1093 if (Result.end() - Result.begin() > 1) { 1094 IsFunctionTemplate = true; 1095 Template = Context.getOverloadedTemplateName(Result.begin(), 1096 Result.end()); 1097 } else if (!Result.empty()) { 1098 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl( 1099 *Result.begin(), /*AllowFunctionTemplates=*/true, 1100 /*AllowDependent=*/false)); 1101 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 1102 IsVarTemplate = isa<VarTemplateDecl>(TD); 1103 1104 if (SS.isNotEmpty()) 1105 Template = 1106 Context.getQualifiedTemplateName(SS.getScopeRep(), 1107 /*TemplateKeyword=*/false, TD); 1108 else 1109 Template = TemplateName(TD); 1110 } else { 1111 // All results were non-template functions. This is a function template 1112 // name. 1113 IsFunctionTemplate = true; 1114 Template = Context.getAssumedTemplateName(NameInfo.getName()); 1115 } 1116 1117 if (IsFunctionTemplate) { 1118 // Function templates always go through overload resolution, at which 1119 // point we'll perform the various checks (e.g., accessibility) we need 1120 // to based on which function we selected. 1121 Result.suppressDiagnostics(); 1122 1123 return NameClassification::FunctionTemplate(Template); 1124 } 1125 1126 return IsVarTemplate ? NameClassification::VarTemplate(Template) 1127 : NameClassification::TypeTemplate(Template); 1128 } 1129 1130 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 1131 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 1132 DiagnoseUseOfDecl(Type, NameLoc); 1133 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 1134 QualType T = Context.getTypeDeclType(Type); 1135 if (SS.isNotEmpty()) 1136 return buildNestedType(*this, SS, T, NameLoc); 1137 return ParsedType::make(T); 1138 } 1139 1140 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 1141 if (!Class) { 1142 // FIXME: It's unfortunate that we don't have a Type node for handling this. 1143 if (ObjCCompatibleAliasDecl *Alias = 1144 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 1145 Class = Alias->getClassInterface(); 1146 } 1147 1148 if (Class) { 1149 DiagnoseUseOfDecl(Class, NameLoc); 1150 1151 if (NextToken.is(tok::period)) { 1152 // Interface. <something> is parsed as a property reference expression. 1153 // Just return "unknown" as a fall-through for now. 1154 Result.suppressDiagnostics(); 1155 return NameClassification::Unknown(); 1156 } 1157 1158 QualType T = Context.getObjCInterfaceType(Class); 1159 return ParsedType::make(T); 1160 } 1161 1162 if (isa<ConceptDecl>(FirstDecl)) 1163 return NameClassification::Concept( 1164 TemplateName(cast<TemplateDecl>(FirstDecl))); 1165 1166 // We can have a type template here if we're classifying a template argument. 1167 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) && 1168 !isa<VarTemplateDecl>(FirstDecl)) 1169 return NameClassification::TypeTemplate( 1170 TemplateName(cast<TemplateDecl>(FirstDecl))); 1171 1172 // Check for a tag type hidden by a non-type decl in a few cases where it 1173 // seems likely a type is wanted instead of the non-type that was found. 1174 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); 1175 if ((NextToken.is(tok::identifier) || 1176 (NextIsOp && 1177 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 1178 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 1179 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 1180 DiagnoseUseOfDecl(Type, NameLoc); 1181 QualType T = Context.getTypeDeclType(Type); 1182 if (SS.isNotEmpty()) 1183 return buildNestedType(*this, SS, T, NameLoc); 1184 return ParsedType::make(T); 1185 } 1186 1187 // FIXME: This is context-dependent. We need to defer building the member 1188 // expression until the classification is consumed. 1189 if (FirstDecl->isCXXClassMember()) 1190 return NameClassification::ContextIndependentExpr( 1191 BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, nullptr, 1192 S)); 1193 1194 // If we already know which single declaration is referenced, just annotate 1195 // that declaration directly. 1196 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1197 if (Result.isSingleResult() && !ADL) 1198 return NameClassification::NonType(Result.getRepresentativeDecl()); 1199 1200 // Build an UnresolvedLookupExpr. Note that this doesn't depend on the 1201 // context in which we performed classification, so it's safe to do now. 1202 return NameClassification::ContextIndependentExpr( 1203 BuildDeclarationNameExpr(SS, Result, ADL)); 1204 } 1205 1206 ExprResult 1207 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, 1208 SourceLocation NameLoc) { 1209 assert(getLangOpts().CPlusPlus && "ADL-only call in C?"); 1210 CXXScopeSpec SS; 1211 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 1212 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 1213 } 1214 1215 ExprResult 1216 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, 1217 IdentifierInfo *Name, 1218 SourceLocation NameLoc, 1219 bool IsAddressOfOperand) { 1220 DeclarationNameInfo NameInfo(Name, NameLoc); 1221 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 1222 NameInfo, IsAddressOfOperand, 1223 /*TemplateArgs=*/nullptr); 1224 } 1225 1226 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, 1227 NamedDecl *Found, 1228 SourceLocation NameLoc, 1229 const Token &NextToken) { 1230 if (getCurMethodDecl() && SS.isEmpty()) 1231 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl())) 1232 return BuildIvarRefExpr(S, NameLoc, Ivar); 1233 1234 // Reconstruct the lookup result. 1235 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName); 1236 Result.addDecl(Found); 1237 Result.resolveKind(); 1238 1239 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1240 return BuildDeclarationNameExpr(SS, Result, ADL); 1241 } 1242 1243 Sema::TemplateNameKindForDiagnostics 1244 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) { 1245 auto *TD = Name.getAsTemplateDecl(); 1246 if (!TD) 1247 return TemplateNameKindForDiagnostics::DependentTemplate; 1248 if (isa<ClassTemplateDecl>(TD)) 1249 return TemplateNameKindForDiagnostics::ClassTemplate; 1250 if (isa<FunctionTemplateDecl>(TD)) 1251 return TemplateNameKindForDiagnostics::FunctionTemplate; 1252 if (isa<VarTemplateDecl>(TD)) 1253 return TemplateNameKindForDiagnostics::VarTemplate; 1254 if (isa<TypeAliasTemplateDecl>(TD)) 1255 return TemplateNameKindForDiagnostics::AliasTemplate; 1256 if (isa<TemplateTemplateParmDecl>(TD)) 1257 return TemplateNameKindForDiagnostics::TemplateTemplateParam; 1258 if (isa<ConceptDecl>(TD)) 1259 return TemplateNameKindForDiagnostics::Concept; 1260 return TemplateNameKindForDiagnostics::DependentTemplate; 1261 } 1262 1263 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 1264 assert(DC->getLexicalParent() == CurContext && 1265 "The next DeclContext should be lexically contained in the current one."); 1266 CurContext = DC; 1267 S->setEntity(DC); 1268 } 1269 1270 void Sema::PopDeclContext() { 1271 assert(CurContext && "DeclContext imbalance!"); 1272 1273 CurContext = CurContext->getLexicalParent(); 1274 assert(CurContext && "Popped translation unit!"); 1275 } 1276 1277 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, 1278 Decl *D) { 1279 // Unlike PushDeclContext, the context to which we return is not necessarily 1280 // the containing DC of TD, because the new context will be some pre-existing 1281 // TagDecl definition instead of a fresh one. 1282 auto Result = static_cast<SkippedDefinitionContext>(CurContext); 1283 CurContext = cast<TagDecl>(D)->getDefinition(); 1284 assert(CurContext && "skipping definition of undefined tag"); 1285 // Start lookups from the parent of the current context; we don't want to look 1286 // into the pre-existing complete definition. 1287 S->setEntity(CurContext->getLookupParent()); 1288 return Result; 1289 } 1290 1291 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { 1292 CurContext = static_cast<decltype(CurContext)>(Context); 1293 } 1294 1295 /// EnterDeclaratorContext - Used when we must lookup names in the context 1296 /// of a declarator's nested name specifier. 1297 /// 1298 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1299 // C++0x [basic.lookup.unqual]p13: 1300 // A name used in the definition of a static data member of class 1301 // X (after the qualified-id of the static member) is looked up as 1302 // if the name was used in a member function of X. 1303 // C++0x [basic.lookup.unqual]p14: 1304 // If a variable member of a namespace is defined outside of the 1305 // scope of its namespace then any name used in the definition of 1306 // the variable member (after the declarator-id) is looked up as 1307 // if the definition of the variable member occurred in its 1308 // namespace. 1309 // Both of these imply that we should push a scope whose context 1310 // is the semantic context of the declaration. We can't use 1311 // PushDeclContext here because that context is not necessarily 1312 // lexically contained in the current context. Fortunately, 1313 // the containing scope should have the appropriate information. 1314 1315 assert(!S->getEntity() && "scope already has entity"); 1316 1317 #ifndef NDEBUG 1318 Scope *Ancestor = S->getParent(); 1319 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1320 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1321 #endif 1322 1323 CurContext = DC; 1324 S->setEntity(DC); 1325 1326 if (S->getParent()->isTemplateParamScope()) { 1327 // Also set the corresponding entities for all immediately-enclosing 1328 // template parameter scopes. 1329 EnterTemplatedContext(S->getParent(), DC); 1330 } 1331 } 1332 1333 void Sema::ExitDeclaratorContext(Scope *S) { 1334 assert(S->getEntity() == CurContext && "Context imbalance!"); 1335 1336 // Switch back to the lexical context. The safety of this is 1337 // enforced by an assert in EnterDeclaratorContext. 1338 Scope *Ancestor = S->getParent(); 1339 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1340 CurContext = Ancestor->getEntity(); 1341 1342 // We don't need to do anything with the scope, which is going to 1343 // disappear. 1344 } 1345 1346 void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) { 1347 assert(S->isTemplateParamScope() && 1348 "expected to be initializing a template parameter scope"); 1349 1350 // C++20 [temp.local]p7: 1351 // In the definition of a member of a class template that appears outside 1352 // of the class template definition, the name of a member of the class 1353 // template hides the name of a template-parameter of any enclosing class 1354 // templates (but not a template-parameter of the member if the member is a 1355 // class or function template). 1356 // C++20 [temp.local]p9: 1357 // In the definition of a class template or in the definition of a member 1358 // of such a template that appears outside of the template definition, for 1359 // each non-dependent base class (13.8.2.1), if the name of the base class 1360 // or the name of a member of the base class is the same as the name of a 1361 // template-parameter, the base class name or member name hides the 1362 // template-parameter name (6.4.10). 1363 // 1364 // This means that a template parameter scope should be searched immediately 1365 // after searching the DeclContext for which it is a template parameter 1366 // scope. For example, for 1367 // template<typename T> template<typename U> template<typename V> 1368 // void N::A<T>::B<U>::f(...) 1369 // we search V then B<U> (and base classes) then U then A<T> (and base 1370 // classes) then T then N then ::. 1371 unsigned ScopeDepth = getTemplateDepth(S); 1372 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) { 1373 DeclContext *SearchDCAfterScope = DC; 1374 for (; DC; DC = DC->getLookupParent()) { 1375 if (const TemplateParameterList *TPL = 1376 cast<Decl>(DC)->getDescribedTemplateParams()) { 1377 unsigned DCDepth = TPL->getDepth() + 1; 1378 if (DCDepth > ScopeDepth) 1379 continue; 1380 if (ScopeDepth == DCDepth) 1381 SearchDCAfterScope = DC = DC->getLookupParent(); 1382 break; 1383 } 1384 } 1385 S->setLookupEntity(SearchDCAfterScope); 1386 } 1387 } 1388 1389 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1390 // We assume that the caller has already called 1391 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1392 FunctionDecl *FD = D->getAsFunction(); 1393 if (!FD) 1394 return; 1395 1396 // Same implementation as PushDeclContext, but enters the context 1397 // from the lexical parent, rather than the top-level class. 1398 assert(CurContext == FD->getLexicalParent() && 1399 "The next DeclContext should be lexically contained in the current one."); 1400 CurContext = FD; 1401 S->setEntity(CurContext); 1402 1403 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1404 ParmVarDecl *Param = FD->getParamDecl(P); 1405 // If the parameter has an identifier, then add it to the scope 1406 if (Param->getIdentifier()) { 1407 S->AddDecl(Param); 1408 IdResolver.AddDecl(Param); 1409 } 1410 } 1411 } 1412 1413 void Sema::ActOnExitFunctionContext() { 1414 // Same implementation as PopDeclContext, but returns to the lexical parent, 1415 // rather than the top-level class. 1416 assert(CurContext && "DeclContext imbalance!"); 1417 CurContext = CurContext->getLexicalParent(); 1418 assert(CurContext && "Popped translation unit!"); 1419 } 1420 1421 /// Determine whether we allow overloading of the function 1422 /// PrevDecl with another declaration. 1423 /// 1424 /// This routine determines whether overloading is possible, not 1425 /// whether some new function is actually an overload. It will return 1426 /// true in C++ (where we can always provide overloads) or, as an 1427 /// extension, in C when the previous function is already an 1428 /// overloaded function declaration or has the "overloadable" 1429 /// attribute. 1430 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1431 ASTContext &Context, 1432 const FunctionDecl *New) { 1433 if (Context.getLangOpts().CPlusPlus) 1434 return true; 1435 1436 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1437 return true; 1438 1439 return Previous.getResultKind() == LookupResult::Found && 1440 (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() || 1441 New->hasAttr<OverloadableAttr>()); 1442 } 1443 1444 /// Add this decl to the scope shadowed decl chains. 1445 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1446 // Move up the scope chain until we find the nearest enclosing 1447 // non-transparent context. The declaration will be introduced into this 1448 // scope. 1449 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1450 S = S->getParent(); 1451 1452 // Add scoped declarations into their context, so that they can be 1453 // found later. Declarations without a context won't be inserted 1454 // into any context. 1455 if (AddToContext) 1456 CurContext->addDecl(D); 1457 1458 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1459 // are function-local declarations. 1460 if (getLangOpts().CPlusPlus && D->isOutOfLine() && 1461 !D->getDeclContext()->getRedeclContext()->Equals( 1462 D->getLexicalDeclContext()->getRedeclContext()) && 1463 !D->getLexicalDeclContext()->isFunctionOrMethod()) 1464 return; 1465 1466 // Template instantiations should also not be pushed into scope. 1467 if (isa<FunctionDecl>(D) && 1468 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1469 return; 1470 1471 // If this replaces anything in the current scope, 1472 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1473 IEnd = IdResolver.end(); 1474 for (; I != IEnd; ++I) { 1475 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1476 S->RemoveDecl(*I); 1477 IdResolver.RemoveDecl(*I); 1478 1479 // Should only need to replace one decl. 1480 break; 1481 } 1482 } 1483 1484 S->AddDecl(D); 1485 1486 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1487 // Implicitly-generated labels may end up getting generated in an order that 1488 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1489 // the label at the appropriate place in the identifier chain. 1490 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1491 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1492 if (IDC == CurContext) { 1493 if (!S->isDeclScope(*I)) 1494 continue; 1495 } else if (IDC->Encloses(CurContext)) 1496 break; 1497 } 1498 1499 IdResolver.InsertDeclAfter(I, D); 1500 } else { 1501 IdResolver.AddDecl(D); 1502 } 1503 } 1504 1505 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1506 bool AllowInlineNamespace) { 1507 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1508 } 1509 1510 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1511 DeclContext *TargetDC = DC->getPrimaryContext(); 1512 do { 1513 if (DeclContext *ScopeDC = S->getEntity()) 1514 if (ScopeDC->getPrimaryContext() == TargetDC) 1515 return S; 1516 } while ((S = S->getParent())); 1517 1518 return nullptr; 1519 } 1520 1521 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1522 DeclContext*, 1523 ASTContext&); 1524 1525 /// Filters out lookup results that don't fall within the given scope 1526 /// as determined by isDeclInScope. 1527 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1528 bool ConsiderLinkage, 1529 bool AllowInlineNamespace) { 1530 LookupResult::Filter F = R.makeFilter(); 1531 while (F.hasNext()) { 1532 NamedDecl *D = F.next(); 1533 1534 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1535 continue; 1536 1537 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1538 continue; 1539 1540 F.erase(); 1541 } 1542 1543 F.done(); 1544 } 1545 1546 /// We've determined that \p New is a redeclaration of \p Old. Check that they 1547 /// have compatible owning modules. 1548 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) { 1549 // FIXME: The Modules TS is not clear about how friend declarations are 1550 // to be treated. It's not meaningful to have different owning modules for 1551 // linkage in redeclarations of the same entity, so for now allow the 1552 // redeclaration and change the owning modules to match. 1553 if (New->getFriendObjectKind() && 1554 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) { 1555 New->setLocalOwningModule(Old->getOwningModule()); 1556 makeMergedDefinitionVisible(New); 1557 return false; 1558 } 1559 1560 Module *NewM = New->getOwningModule(); 1561 Module *OldM = Old->getOwningModule(); 1562 1563 if (NewM && NewM->Kind == Module::PrivateModuleFragment) 1564 NewM = NewM->Parent; 1565 if (OldM && OldM->Kind == Module::PrivateModuleFragment) 1566 OldM = OldM->Parent; 1567 1568 if (NewM == OldM) 1569 return false; 1570 1571 bool NewIsModuleInterface = NewM && NewM->isModulePurview(); 1572 bool OldIsModuleInterface = OldM && OldM->isModulePurview(); 1573 if (NewIsModuleInterface || OldIsModuleInterface) { 1574 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]: 1575 // if a declaration of D [...] appears in the purview of a module, all 1576 // other such declarations shall appear in the purview of the same module 1577 Diag(New->getLocation(), diag::err_mismatched_owning_module) 1578 << New 1579 << NewIsModuleInterface 1580 << (NewIsModuleInterface ? NewM->getFullModuleName() : "") 1581 << OldIsModuleInterface 1582 << (OldIsModuleInterface ? OldM->getFullModuleName() : ""); 1583 Diag(Old->getLocation(), diag::note_previous_declaration); 1584 New->setInvalidDecl(); 1585 return true; 1586 } 1587 1588 return false; 1589 } 1590 1591 static bool isUsingDecl(NamedDecl *D) { 1592 return isa<UsingShadowDecl>(D) || 1593 isa<UnresolvedUsingTypenameDecl>(D) || 1594 isa<UnresolvedUsingValueDecl>(D); 1595 } 1596 1597 /// Removes using shadow declarations from the lookup results. 1598 static void RemoveUsingDecls(LookupResult &R) { 1599 LookupResult::Filter F = R.makeFilter(); 1600 while (F.hasNext()) 1601 if (isUsingDecl(F.next())) 1602 F.erase(); 1603 1604 F.done(); 1605 } 1606 1607 /// Check for this common pattern: 1608 /// @code 1609 /// class S { 1610 /// S(const S&); // DO NOT IMPLEMENT 1611 /// void operator=(const S&); // DO NOT IMPLEMENT 1612 /// }; 1613 /// @endcode 1614 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1615 // FIXME: Should check for private access too but access is set after we get 1616 // the decl here. 1617 if (D->doesThisDeclarationHaveABody()) 1618 return false; 1619 1620 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1621 return CD->isCopyConstructor(); 1622 return D->isCopyAssignmentOperator(); 1623 } 1624 1625 // We need this to handle 1626 // 1627 // typedef struct { 1628 // void *foo() { return 0; } 1629 // } A; 1630 // 1631 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1632 // for example. If 'A', foo will have external linkage. If we have '*A', 1633 // foo will have no linkage. Since we can't know until we get to the end 1634 // of the typedef, this function finds out if D might have non-external linkage. 1635 // Callers should verify at the end of the TU if it D has external linkage or 1636 // not. 1637 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1638 const DeclContext *DC = D->getDeclContext(); 1639 while (!DC->isTranslationUnit()) { 1640 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1641 if (!RD->hasNameForLinkage()) 1642 return true; 1643 } 1644 DC = DC->getParent(); 1645 } 1646 1647 return !D->isExternallyVisible(); 1648 } 1649 1650 // FIXME: This needs to be refactored; some other isInMainFile users want 1651 // these semantics. 1652 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1653 if (S.TUKind != TU_Complete) 1654 return false; 1655 return S.SourceMgr.isInMainFile(Loc); 1656 } 1657 1658 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1659 assert(D); 1660 1661 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1662 return false; 1663 1664 // Ignore all entities declared within templates, and out-of-line definitions 1665 // of members of class templates. 1666 if (D->getDeclContext()->isDependentContext() || 1667 D->getLexicalDeclContext()->isDependentContext()) 1668 return false; 1669 1670 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1671 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1672 return false; 1673 // A non-out-of-line declaration of a member specialization was implicitly 1674 // instantiated; it's the out-of-line declaration that we're interested in. 1675 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1676 FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) 1677 return false; 1678 1679 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1680 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1681 return false; 1682 } else { 1683 // 'static inline' functions are defined in headers; don't warn. 1684 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1685 return false; 1686 } 1687 1688 if (FD->doesThisDeclarationHaveABody() && 1689 Context.DeclMustBeEmitted(FD)) 1690 return false; 1691 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1692 // Constants and utility variables are defined in headers with internal 1693 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1694 // like "inline".) 1695 if (!isMainFileLoc(*this, VD->getLocation())) 1696 return false; 1697 1698 if (Context.DeclMustBeEmitted(VD)) 1699 return false; 1700 1701 if (VD->isStaticDataMember() && 1702 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1703 return false; 1704 if (VD->isStaticDataMember() && 1705 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1706 VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) 1707 return false; 1708 1709 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) 1710 return false; 1711 } else { 1712 return false; 1713 } 1714 1715 // Only warn for unused decls internal to the translation unit. 1716 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1717 // for inline functions defined in the main source file, for instance. 1718 return mightHaveNonExternalLinkage(D); 1719 } 1720 1721 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1722 if (!D) 1723 return; 1724 1725 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1726 const FunctionDecl *First = FD->getFirstDecl(); 1727 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1728 return; // First should already be in the vector. 1729 } 1730 1731 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1732 const VarDecl *First = VD->getFirstDecl(); 1733 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1734 return; // First should already be in the vector. 1735 } 1736 1737 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1738 UnusedFileScopedDecls.push_back(D); 1739 } 1740 1741 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1742 if (D->isInvalidDecl()) 1743 return false; 1744 1745 bool Referenced = false; 1746 if (auto *DD = dyn_cast<DecompositionDecl>(D)) { 1747 // For a decomposition declaration, warn if none of the bindings are 1748 // referenced, instead of if the variable itself is referenced (which 1749 // it is, by the bindings' expressions). 1750 for (auto *BD : DD->bindings()) { 1751 if (BD->isReferenced()) { 1752 Referenced = true; 1753 break; 1754 } 1755 } 1756 } else if (!D->getDeclName()) { 1757 return false; 1758 } else if (D->isReferenced() || D->isUsed()) { 1759 Referenced = true; 1760 } 1761 1762 if (Referenced || D->hasAttr<UnusedAttr>() || 1763 D->hasAttr<ObjCPreciseLifetimeAttr>()) 1764 return false; 1765 1766 if (isa<LabelDecl>(D)) 1767 return true; 1768 1769 // Except for labels, we only care about unused decls that are local to 1770 // functions. 1771 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1772 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1773 // For dependent types, the diagnostic is deferred. 1774 WithinFunction = 1775 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1776 if (!WithinFunction) 1777 return false; 1778 1779 if (isa<TypedefNameDecl>(D)) 1780 return true; 1781 1782 // White-list anything that isn't a local variable. 1783 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1784 return false; 1785 1786 // Types of valid local variables should be complete, so this should succeed. 1787 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1788 1789 // White-list anything with an __attribute__((unused)) type. 1790 const auto *Ty = VD->getType().getTypePtr(); 1791 1792 // Only look at the outermost level of typedef. 1793 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1794 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1795 return false; 1796 } 1797 1798 // If we failed to complete the type for some reason, or if the type is 1799 // dependent, don't diagnose the variable. 1800 if (Ty->isIncompleteType() || Ty->isDependentType()) 1801 return false; 1802 1803 // Look at the element type to ensure that the warning behaviour is 1804 // consistent for both scalars and arrays. 1805 Ty = Ty->getBaseElementTypeUnsafe(); 1806 1807 if (const TagType *TT = Ty->getAs<TagType>()) { 1808 const TagDecl *Tag = TT->getDecl(); 1809 if (Tag->hasAttr<UnusedAttr>()) 1810 return false; 1811 1812 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1813 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1814 return false; 1815 1816 if (const Expr *Init = VD->getInit()) { 1817 if (const ExprWithCleanups *Cleanups = 1818 dyn_cast<ExprWithCleanups>(Init)) 1819 Init = Cleanups->getSubExpr(); 1820 const CXXConstructExpr *Construct = 1821 dyn_cast<CXXConstructExpr>(Init); 1822 if (Construct && !Construct->isElidable()) { 1823 CXXConstructorDecl *CD = Construct->getConstructor(); 1824 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() && 1825 (VD->getInit()->isValueDependent() || !VD->evaluateValue())) 1826 return false; 1827 } 1828 1829 // Suppress the warning if we don't know how this is constructed, and 1830 // it could possibly be non-trivial constructor. 1831 if (Init->isTypeDependent()) 1832 for (const CXXConstructorDecl *Ctor : RD->ctors()) 1833 if (!Ctor->isTrivial()) 1834 return false; 1835 } 1836 } 1837 } 1838 1839 // TODO: __attribute__((unused)) templates? 1840 } 1841 1842 return true; 1843 } 1844 1845 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1846 FixItHint &Hint) { 1847 if (isa<LabelDecl>(D)) { 1848 SourceLocation AfterColon = Lexer::findLocationAfterToken( 1849 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), 1850 true); 1851 if (AfterColon.isInvalid()) 1852 return; 1853 Hint = FixItHint::CreateRemoval( 1854 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon)); 1855 } 1856 } 1857 1858 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1859 if (D->getTypeForDecl()->isDependentType()) 1860 return; 1861 1862 for (auto *TmpD : D->decls()) { 1863 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1864 DiagnoseUnusedDecl(T); 1865 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1866 DiagnoseUnusedNestedTypedefs(R); 1867 } 1868 } 1869 1870 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1871 /// unless they are marked attr(unused). 1872 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1873 if (!ShouldDiagnoseUnusedDecl(D)) 1874 return; 1875 1876 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1877 // typedefs can be referenced later on, so the diagnostics are emitted 1878 // at end-of-translation-unit. 1879 UnusedLocalTypedefNameCandidates.insert(TD); 1880 return; 1881 } 1882 1883 FixItHint Hint; 1884 GenerateFixForUnusedDecl(D, Context, Hint); 1885 1886 unsigned DiagID; 1887 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1888 DiagID = diag::warn_unused_exception_param; 1889 else if (isa<LabelDecl>(D)) 1890 DiagID = diag::warn_unused_label; 1891 else 1892 DiagID = diag::warn_unused_variable; 1893 1894 Diag(D->getLocation(), DiagID) << D << Hint; 1895 } 1896 1897 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1898 // Verify that we have no forward references left. If so, there was a goto 1899 // or address of a label taken, but no definition of it. Label fwd 1900 // definitions are indicated with a null substmt which is also not a resolved 1901 // MS inline assembly label name. 1902 bool Diagnose = false; 1903 if (L->isMSAsmLabel()) 1904 Diagnose = !L->isResolvedMSAsmLabel(); 1905 else 1906 Diagnose = L->getStmt() == nullptr; 1907 if (Diagnose) 1908 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1909 } 1910 1911 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1912 S->mergeNRVOIntoParent(); 1913 1914 if (S->decl_empty()) return; 1915 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1916 "Scope shouldn't contain decls!"); 1917 1918 for (auto *TmpD : S->decls()) { 1919 assert(TmpD && "This decl didn't get pushed??"); 1920 1921 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1922 NamedDecl *D = cast<NamedDecl>(TmpD); 1923 1924 // Diagnose unused variables in this scope. 1925 if (!S->hasUnrecoverableErrorOccurred()) { 1926 DiagnoseUnusedDecl(D); 1927 if (const auto *RD = dyn_cast<RecordDecl>(D)) 1928 DiagnoseUnusedNestedTypedefs(RD); 1929 } 1930 1931 if (!D->getDeclName()) continue; 1932 1933 // If this was a forward reference to a label, verify it was defined. 1934 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1935 CheckPoppedLabel(LD, *this); 1936 1937 // Remove this name from our lexical scope, and warn on it if we haven't 1938 // already. 1939 IdResolver.RemoveDecl(D); 1940 auto ShadowI = ShadowingDecls.find(D); 1941 if (ShadowI != ShadowingDecls.end()) { 1942 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { 1943 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) 1944 << D << FD << FD->getParent(); 1945 Diag(FD->getLocation(), diag::note_previous_declaration); 1946 } 1947 ShadowingDecls.erase(ShadowI); 1948 } 1949 } 1950 } 1951 1952 /// Look for an Objective-C class in the translation unit. 1953 /// 1954 /// \param Id The name of the Objective-C class we're looking for. If 1955 /// typo-correction fixes this name, the Id will be updated 1956 /// to the fixed name. 1957 /// 1958 /// \param IdLoc The location of the name in the translation unit. 1959 /// 1960 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1961 /// if there is no class with the given name. 1962 /// 1963 /// \returns The declaration of the named Objective-C class, or NULL if the 1964 /// class could not be found. 1965 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1966 SourceLocation IdLoc, 1967 bool DoTypoCorrection) { 1968 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1969 // creation from this context. 1970 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1971 1972 if (!IDecl && DoTypoCorrection) { 1973 // Perform typo correction at the given location, but only if we 1974 // find an Objective-C class name. 1975 DeclFilterCCC<ObjCInterfaceDecl> CCC{}; 1976 if (TypoCorrection C = 1977 CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, 1978 TUScope, nullptr, CCC, CTK_ErrorRecovery)) { 1979 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1980 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1981 Id = IDecl->getIdentifier(); 1982 } 1983 } 1984 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1985 // This routine must always return a class definition, if any. 1986 if (Def && Def->getDefinition()) 1987 Def = Def->getDefinition(); 1988 return Def; 1989 } 1990 1991 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 1992 /// from S, where a non-field would be declared. This routine copes 1993 /// with the difference between C and C++ scoping rules in structs and 1994 /// unions. For example, the following code is well-formed in C but 1995 /// ill-formed in C++: 1996 /// @code 1997 /// struct S6 { 1998 /// enum { BAR } e; 1999 /// }; 2000 /// 2001 /// void test_S6() { 2002 /// struct S6 a; 2003 /// a.e = BAR; 2004 /// } 2005 /// @endcode 2006 /// For the declaration of BAR, this routine will return a different 2007 /// scope. The scope S will be the scope of the unnamed enumeration 2008 /// within S6. In C++, this routine will return the scope associated 2009 /// with S6, because the enumeration's scope is a transparent 2010 /// context but structures can contain non-field names. In C, this 2011 /// routine will return the translation unit scope, since the 2012 /// enumeration's scope is a transparent context and structures cannot 2013 /// contain non-field names. 2014 Scope *Sema::getNonFieldDeclScope(Scope *S) { 2015 while (((S->getFlags() & Scope::DeclScope) == 0) || 2016 (S->getEntity() && S->getEntity()->isTransparentContext()) || 2017 (S->isClassScope() && !getLangOpts().CPlusPlus)) 2018 S = S->getParent(); 2019 return S; 2020 } 2021 2022 /// Looks up the declaration of "struct objc_super" and 2023 /// saves it for later use in building builtin declaration of 2024 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such 2025 /// pre-existing declaration exists no action takes place. 2026 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, 2027 IdentifierInfo *II) { 2028 if (!II->isStr("objc_msgSendSuper")) 2029 return; 2030 ASTContext &Context = ThisSema.Context; 2031 2032 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), 2033 SourceLocation(), Sema::LookupTagName); 2034 ThisSema.LookupName(Result, S); 2035 if (Result.getResultKind() == LookupResult::Found) 2036 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 2037 Context.setObjCSuperType(Context.getTagDeclType(TD)); 2038 } 2039 2040 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, 2041 ASTContext::GetBuiltinTypeError Error) { 2042 switch (Error) { 2043 case ASTContext::GE_None: 2044 return ""; 2045 case ASTContext::GE_Missing_type: 2046 return BuiltinInfo.getHeaderName(ID); 2047 case ASTContext::GE_Missing_stdio: 2048 return "stdio.h"; 2049 case ASTContext::GE_Missing_setjmp: 2050 return "setjmp.h"; 2051 case ASTContext::GE_Missing_ucontext: 2052 return "ucontext.h"; 2053 } 2054 llvm_unreachable("unhandled error kind"); 2055 } 2056 2057 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 2058 /// file scope. lazily create a decl for it. ForRedeclaration is true 2059 /// if we're creating this built-in in anticipation of redeclaring the 2060 /// built-in. 2061 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 2062 Scope *S, bool ForRedeclaration, 2063 SourceLocation Loc) { 2064 LookupPredefedObjCSuperType(*this, S, II); 2065 2066 ASTContext::GetBuiltinTypeError Error; 2067 QualType R = Context.GetBuiltinType(ID, Error); 2068 if (Error) { 2069 if (!ForRedeclaration) 2070 return nullptr; 2071 2072 // If we have a builtin without an associated type we should not emit a 2073 // warning when we were not able to find a type for it. 2074 if (Error == ASTContext::GE_Missing_type) 2075 return nullptr; 2076 2077 // If we could not find a type for setjmp it is because the jmp_buf type was 2078 // not defined prior to the setjmp declaration. 2079 if (Error == ASTContext::GE_Missing_setjmp) { 2080 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf) 2081 << Context.BuiltinInfo.getName(ID); 2082 return nullptr; 2083 } 2084 2085 // Generally, we emit a warning that the declaration requires the 2086 // appropriate header. 2087 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 2088 << getHeaderName(Context.BuiltinInfo, ID, Error) 2089 << Context.BuiltinInfo.getName(ID); 2090 return nullptr; 2091 } 2092 2093 if (!ForRedeclaration && 2094 (Context.BuiltinInfo.isPredefinedLibFunction(ID) || 2095 Context.BuiltinInfo.isHeaderDependentFunction(ID))) { 2096 Diag(Loc, diag::ext_implicit_lib_function_decl) 2097 << Context.BuiltinInfo.getName(ID) << R; 2098 if (Context.BuiltinInfo.getHeaderName(ID) && 2099 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc)) 2100 Diag(Loc, diag::note_include_header_or_declare) 2101 << Context.BuiltinInfo.getHeaderName(ID) 2102 << Context.BuiltinInfo.getName(ID); 2103 } 2104 2105 if (R.isNull()) 2106 return nullptr; 2107 2108 DeclContext *Parent = Context.getTranslationUnitDecl(); 2109 if (getLangOpts().CPlusPlus) { 2110 LinkageSpecDecl *CLinkageDecl = 2111 LinkageSpecDecl::Create(Context, Parent, Loc, Loc, 2112 LinkageSpecDecl::lang_c, false); 2113 CLinkageDecl->setImplicit(); 2114 Parent->addDecl(CLinkageDecl); 2115 Parent = CLinkageDecl; 2116 } 2117 2118 FunctionDecl *New = FunctionDecl::Create(Context, 2119 Parent, 2120 Loc, Loc, II, R, /*TInfo=*/nullptr, 2121 SC_Extern, 2122 false, 2123 R->isFunctionProtoType()); 2124 New->setImplicit(); 2125 2126 // Create Decl objects for each parameter, adding them to the 2127 // FunctionDecl. 2128 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 2129 SmallVector<ParmVarDecl*, 16> Params; 2130 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 2131 ParmVarDecl *parm = 2132 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(), 2133 nullptr, FT->getParamType(i), /*TInfo=*/nullptr, 2134 SC_None, nullptr); 2135 parm->setScopeInfo(0, i); 2136 Params.push_back(parm); 2137 } 2138 New->setParams(Params); 2139 } 2140 2141 AddKnownFunctionAttributes(New); 2142 RegisterLocallyScopedExternCDecl(New, S); 2143 2144 // TUScope is the translation-unit scope to insert this function into. 2145 // FIXME: This is hideous. We need to teach PushOnScopeChains to 2146 // relate Scopes to DeclContexts, and probably eliminate CurContext 2147 // entirely, but we're not there yet. 2148 DeclContext *SavedContext = CurContext; 2149 CurContext = Parent; 2150 PushOnScopeChains(New, TUScope); 2151 CurContext = SavedContext; 2152 return New; 2153 } 2154 2155 /// Typedef declarations don't have linkage, but they still denote the same 2156 /// entity if their types are the same. 2157 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 2158 /// isSameEntity. 2159 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 2160 TypedefNameDecl *Decl, 2161 LookupResult &Previous) { 2162 // This is only interesting when modules are enabled. 2163 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 2164 return; 2165 2166 // Empty sets are uninteresting. 2167 if (Previous.empty()) 2168 return; 2169 2170 LookupResult::Filter Filter = Previous.makeFilter(); 2171 while (Filter.hasNext()) { 2172 NamedDecl *Old = Filter.next(); 2173 2174 // Non-hidden declarations are never ignored. 2175 if (S.isVisible(Old)) 2176 continue; 2177 2178 // Declarations of the same entity are not ignored, even if they have 2179 // different linkages. 2180 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2181 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 2182 Decl->getUnderlyingType())) 2183 continue; 2184 2185 // If both declarations give a tag declaration a typedef name for linkage 2186 // purposes, then they declare the same entity. 2187 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 2188 Decl->getAnonDeclWithTypedefName()) 2189 continue; 2190 } 2191 2192 Filter.erase(); 2193 } 2194 2195 Filter.done(); 2196 } 2197 2198 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 2199 QualType OldType; 2200 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 2201 OldType = OldTypedef->getUnderlyingType(); 2202 else 2203 OldType = Context.getTypeDeclType(Old); 2204 QualType NewType = New->getUnderlyingType(); 2205 2206 if (NewType->isVariablyModifiedType()) { 2207 // Must not redefine a typedef with a variably-modified type. 2208 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2209 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 2210 << Kind << NewType; 2211 if (Old->getLocation().isValid()) 2212 notePreviousDefinition(Old, New->getLocation()); 2213 New->setInvalidDecl(); 2214 return true; 2215 } 2216 2217 if (OldType != NewType && 2218 !OldType->isDependentType() && 2219 !NewType->isDependentType() && 2220 !Context.hasSameType(OldType, NewType)) { 2221 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2222 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 2223 << Kind << NewType << OldType; 2224 if (Old->getLocation().isValid()) 2225 notePreviousDefinition(Old, New->getLocation()); 2226 New->setInvalidDecl(); 2227 return true; 2228 } 2229 return false; 2230 } 2231 2232 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 2233 /// same name and scope as a previous declaration 'Old'. Figure out 2234 /// how to resolve this situation, merging decls or emitting 2235 /// diagnostics as appropriate. If there was an error, set New to be invalid. 2236 /// 2237 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 2238 LookupResult &OldDecls) { 2239 // If the new decl is known invalid already, don't bother doing any 2240 // merging checks. 2241 if (New->isInvalidDecl()) return; 2242 2243 // Allow multiple definitions for ObjC built-in typedefs. 2244 // FIXME: Verify the underlying types are equivalent! 2245 if (getLangOpts().ObjC) { 2246 const IdentifierInfo *TypeID = New->getIdentifier(); 2247 switch (TypeID->getLength()) { 2248 default: break; 2249 case 2: 2250 { 2251 if (!TypeID->isStr("id")) 2252 break; 2253 QualType T = New->getUnderlyingType(); 2254 if (!T->isPointerType()) 2255 break; 2256 if (!T->isVoidPointerType()) { 2257 QualType PT = T->castAs<PointerType>()->getPointeeType(); 2258 if (!PT->isStructureType()) 2259 break; 2260 } 2261 Context.setObjCIdRedefinitionType(T); 2262 // Install the built-in type for 'id', ignoring the current definition. 2263 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 2264 return; 2265 } 2266 case 5: 2267 if (!TypeID->isStr("Class")) 2268 break; 2269 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 2270 // Install the built-in type for 'Class', ignoring the current definition. 2271 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 2272 return; 2273 case 3: 2274 if (!TypeID->isStr("SEL")) 2275 break; 2276 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 2277 // Install the built-in type for 'SEL', ignoring the current definition. 2278 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 2279 return; 2280 } 2281 // Fall through - the typedef name was not a builtin type. 2282 } 2283 2284 // Verify the old decl was also a type. 2285 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 2286 if (!Old) { 2287 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2288 << New->getDeclName(); 2289 2290 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 2291 if (OldD->getLocation().isValid()) 2292 notePreviousDefinition(OldD, New->getLocation()); 2293 2294 return New->setInvalidDecl(); 2295 } 2296 2297 // If the old declaration is invalid, just give up here. 2298 if (Old->isInvalidDecl()) 2299 return New->setInvalidDecl(); 2300 2301 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2302 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2303 auto *NewTag = New->getAnonDeclWithTypedefName(); 2304 NamedDecl *Hidden = nullptr; 2305 if (OldTag && NewTag && 2306 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 2307 !hasVisibleDefinition(OldTag, &Hidden)) { 2308 // There is a definition of this tag, but it is not visible. Use it 2309 // instead of our tag. 2310 New->setTypeForDecl(OldTD->getTypeForDecl()); 2311 if (OldTD->isModed()) 2312 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 2313 OldTD->getUnderlyingType()); 2314 else 2315 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 2316 2317 // Make the old tag definition visible. 2318 makeMergedDefinitionVisible(Hidden); 2319 2320 // If this was an unscoped enumeration, yank all of its enumerators 2321 // out of the scope. 2322 if (isa<EnumDecl>(NewTag)) { 2323 Scope *EnumScope = getNonFieldDeclScope(S); 2324 for (auto *D : NewTag->decls()) { 2325 auto *ED = cast<EnumConstantDecl>(D); 2326 assert(EnumScope->isDeclScope(ED)); 2327 EnumScope->RemoveDecl(ED); 2328 IdResolver.RemoveDecl(ED); 2329 ED->getLexicalDeclContext()->removeDecl(ED); 2330 } 2331 } 2332 } 2333 } 2334 2335 // If the typedef types are not identical, reject them in all languages and 2336 // with any extensions enabled. 2337 if (isIncompatibleTypedef(Old, New)) 2338 return; 2339 2340 // The types match. Link up the redeclaration chain and merge attributes if 2341 // the old declaration was a typedef. 2342 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2343 New->setPreviousDecl(Typedef); 2344 mergeDeclAttributes(New, Old); 2345 } 2346 2347 if (getLangOpts().MicrosoftExt) 2348 return; 2349 2350 if (getLangOpts().CPlusPlus) { 2351 // C++ [dcl.typedef]p2: 2352 // In a given non-class scope, a typedef specifier can be used to 2353 // redefine the name of any type declared in that scope to refer 2354 // to the type to which it already refers. 2355 if (!isa<CXXRecordDecl>(CurContext)) 2356 return; 2357 2358 // C++0x [dcl.typedef]p4: 2359 // In a given class scope, a typedef specifier can be used to redefine 2360 // any class-name declared in that scope that is not also a typedef-name 2361 // to refer to the type to which it already refers. 2362 // 2363 // This wording came in via DR424, which was a correction to the 2364 // wording in DR56, which accidentally banned code like: 2365 // 2366 // struct S { 2367 // typedef struct A { } A; 2368 // }; 2369 // 2370 // in the C++03 standard. We implement the C++0x semantics, which 2371 // allow the above but disallow 2372 // 2373 // struct S { 2374 // typedef int I; 2375 // typedef int I; 2376 // }; 2377 // 2378 // since that was the intent of DR56. 2379 if (!isa<TypedefNameDecl>(Old)) 2380 return; 2381 2382 Diag(New->getLocation(), diag::err_redefinition) 2383 << New->getDeclName(); 2384 notePreviousDefinition(Old, New->getLocation()); 2385 return New->setInvalidDecl(); 2386 } 2387 2388 // Modules always permit redefinition of typedefs, as does C11. 2389 if (getLangOpts().Modules || getLangOpts().C11) 2390 return; 2391 2392 // If we have a redefinition of a typedef in C, emit a warning. This warning 2393 // is normally mapped to an error, but can be controlled with 2394 // -Wtypedef-redefinition. If either the original or the redefinition is 2395 // in a system header, don't emit this for compatibility with GCC. 2396 if (getDiagnostics().getSuppressSystemWarnings() && 2397 // Some standard types are defined implicitly in Clang (e.g. OpenCL). 2398 (Old->isImplicit() || 2399 Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2400 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2401 return; 2402 2403 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2404 << New->getDeclName(); 2405 notePreviousDefinition(Old, New->getLocation()); 2406 } 2407 2408 /// DeclhasAttr - returns true if decl Declaration already has the target 2409 /// attribute. 2410 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2411 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2412 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2413 for (const auto *i : D->attrs()) 2414 if (i->getKind() == A->getKind()) { 2415 if (Ann) { 2416 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2417 return true; 2418 continue; 2419 } 2420 // FIXME: Don't hardcode this check 2421 if (OA && isa<OwnershipAttr>(i)) 2422 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2423 return true; 2424 } 2425 2426 return false; 2427 } 2428 2429 static bool isAttributeTargetADefinition(Decl *D) { 2430 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2431 return VD->isThisDeclarationADefinition(); 2432 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2433 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2434 return true; 2435 } 2436 2437 /// Merge alignment attributes from \p Old to \p New, taking into account the 2438 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2439 /// 2440 /// \return \c true if any attributes were added to \p New. 2441 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2442 // Look for alignas attributes on Old, and pick out whichever attribute 2443 // specifies the strictest alignment requirement. 2444 AlignedAttr *OldAlignasAttr = nullptr; 2445 AlignedAttr *OldStrictestAlignAttr = nullptr; 2446 unsigned OldAlign = 0; 2447 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2448 // FIXME: We have no way of representing inherited dependent alignments 2449 // in a case like: 2450 // template<int A, int B> struct alignas(A) X; 2451 // template<int A, int B> struct alignas(B) X {}; 2452 // For now, we just ignore any alignas attributes which are not on the 2453 // definition in such a case. 2454 if (I->isAlignmentDependent()) 2455 return false; 2456 2457 if (I->isAlignas()) 2458 OldAlignasAttr = I; 2459 2460 unsigned Align = I->getAlignment(S.Context); 2461 if (Align > OldAlign) { 2462 OldAlign = Align; 2463 OldStrictestAlignAttr = I; 2464 } 2465 } 2466 2467 // Look for alignas attributes on New. 2468 AlignedAttr *NewAlignasAttr = nullptr; 2469 unsigned NewAlign = 0; 2470 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2471 if (I->isAlignmentDependent()) 2472 return false; 2473 2474 if (I->isAlignas()) 2475 NewAlignasAttr = I; 2476 2477 unsigned Align = I->getAlignment(S.Context); 2478 if (Align > NewAlign) 2479 NewAlign = Align; 2480 } 2481 2482 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2483 // Both declarations have 'alignas' attributes. We require them to match. 2484 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2485 // fall short. (If two declarations both have alignas, they must both match 2486 // every definition, and so must match each other if there is a definition.) 2487 2488 // If either declaration only contains 'alignas(0)' specifiers, then it 2489 // specifies the natural alignment for the type. 2490 if (OldAlign == 0 || NewAlign == 0) { 2491 QualType Ty; 2492 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2493 Ty = VD->getType(); 2494 else 2495 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2496 2497 if (OldAlign == 0) 2498 OldAlign = S.Context.getTypeAlign(Ty); 2499 if (NewAlign == 0) 2500 NewAlign = S.Context.getTypeAlign(Ty); 2501 } 2502 2503 if (OldAlign != NewAlign) { 2504 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2505 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2506 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2507 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2508 } 2509 } 2510 2511 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2512 // C++11 [dcl.align]p6: 2513 // if any declaration of an entity has an alignment-specifier, 2514 // every defining declaration of that entity shall specify an 2515 // equivalent alignment. 2516 // C11 6.7.5/7: 2517 // If the definition of an object does not have an alignment 2518 // specifier, any other declaration of that object shall also 2519 // have no alignment specifier. 2520 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2521 << OldAlignasAttr; 2522 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2523 << OldAlignasAttr; 2524 } 2525 2526 bool AnyAdded = false; 2527 2528 // Ensure we have an attribute representing the strictest alignment. 2529 if (OldAlign > NewAlign) { 2530 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2531 Clone->setInherited(true); 2532 New->addAttr(Clone); 2533 AnyAdded = true; 2534 } 2535 2536 // Ensure we have an alignas attribute if the old declaration had one. 2537 if (OldAlignasAttr && !NewAlignasAttr && 2538 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2539 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2540 Clone->setInherited(true); 2541 New->addAttr(Clone); 2542 AnyAdded = true; 2543 } 2544 2545 return AnyAdded; 2546 } 2547 2548 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2549 const InheritableAttr *Attr, 2550 Sema::AvailabilityMergeKind AMK) { 2551 // This function copies an attribute Attr from a previous declaration to the 2552 // new declaration D if the new declaration doesn't itself have that attribute 2553 // yet or if that attribute allows duplicates. 2554 // If you're adding a new attribute that requires logic different from 2555 // "use explicit attribute on decl if present, else use attribute from 2556 // previous decl", for example if the attribute needs to be consistent 2557 // between redeclarations, you need to call a custom merge function here. 2558 InheritableAttr *NewAttr = nullptr; 2559 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2560 NewAttr = S.mergeAvailabilityAttr( 2561 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(), 2562 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(), 2563 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK, 2564 AA->getPriority()); 2565 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2566 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility()); 2567 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2568 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility()); 2569 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2570 NewAttr = S.mergeDLLImportAttr(D, *ImportA); 2571 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2572 NewAttr = S.mergeDLLExportAttr(D, *ExportA); 2573 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2574 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(), 2575 FA->getFirstArg()); 2576 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2577 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName()); 2578 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr)) 2579 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName()); 2580 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2581 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(), 2582 IA->getInheritanceModel()); 2583 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2584 NewAttr = S.mergeAlwaysInlineAttr(D, *AA, 2585 &S.Context.Idents.get(AA->getSpelling())); 2586 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2587 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2588 isa<CUDAGlobalAttr>(Attr))) { 2589 // CUDA target attributes are part of function signature for 2590 // overloading purposes and must not be merged. 2591 return false; 2592 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2593 NewAttr = S.mergeMinSizeAttr(D, *MA); 2594 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2595 NewAttr = S.mergeOptimizeNoneAttr(D, *OA); 2596 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2597 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA); 2598 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr)) 2599 NewAttr = S.mergeCommonAttr(D, *CommonA); 2600 else if (isa<AlignedAttr>(Attr)) 2601 // AlignedAttrs are handled separately, because we need to handle all 2602 // such attributes on a declaration at the same time. 2603 NewAttr = nullptr; 2604 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2605 (AMK == Sema::AMK_Override || 2606 AMK == Sema::AMK_ProtocolImplementation)) 2607 NewAttr = nullptr; 2608 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2609 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl()); 2610 else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr)) 2611 NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA); 2612 else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr)) 2613 NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA); 2614 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr)) 2615 NewAttr = S.mergeImportModuleAttr(D, *IMA); 2616 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr)) 2617 NewAttr = S.mergeImportNameAttr(D, *INA); 2618 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr)) 2619 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2620 2621 if (NewAttr) { 2622 NewAttr->setInherited(true); 2623 D->addAttr(NewAttr); 2624 if (isa<MSInheritanceAttr>(NewAttr)) 2625 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2626 return true; 2627 } 2628 2629 return false; 2630 } 2631 2632 static const NamedDecl *getDefinition(const Decl *D) { 2633 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2634 return TD->getDefinition(); 2635 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2636 const VarDecl *Def = VD->getDefinition(); 2637 if (Def) 2638 return Def; 2639 return VD->getActingDefinition(); 2640 } 2641 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 2642 return FD->getDefinition(); 2643 return nullptr; 2644 } 2645 2646 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2647 for (const auto *Attribute : D->attrs()) 2648 if (Attribute->getKind() == Kind) 2649 return true; 2650 return false; 2651 } 2652 2653 /// checkNewAttributesAfterDef - If we already have a definition, check that 2654 /// there are no new attributes in this declaration. 2655 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2656 if (!New->hasAttrs()) 2657 return; 2658 2659 const NamedDecl *Def = getDefinition(Old); 2660 if (!Def || Def == New) 2661 return; 2662 2663 AttrVec &NewAttributes = New->getAttrs(); 2664 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2665 const Attr *NewAttribute = NewAttributes[I]; 2666 2667 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 2668 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2669 Sema::SkipBodyInfo SkipBody; 2670 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2671 2672 // If we're skipping this definition, drop the "alias" attribute. 2673 if (SkipBody.ShouldSkip) { 2674 NewAttributes.erase(NewAttributes.begin() + I); 2675 --E; 2676 continue; 2677 } 2678 } else { 2679 VarDecl *VD = cast<VarDecl>(New); 2680 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2681 VarDecl::TentativeDefinition 2682 ? diag::err_alias_after_tentative 2683 : diag::err_redefinition; 2684 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2685 if (Diag == diag::err_redefinition) 2686 S.notePreviousDefinition(Def, VD->getLocation()); 2687 else 2688 S.Diag(Def->getLocation(), diag::note_previous_definition); 2689 VD->setInvalidDecl(); 2690 } 2691 ++I; 2692 continue; 2693 } 2694 2695 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2696 // Tentative definitions are only interesting for the alias check above. 2697 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2698 ++I; 2699 continue; 2700 } 2701 } 2702 2703 if (hasAttribute(Def, NewAttribute->getKind())) { 2704 ++I; 2705 continue; // regular attr merging will take care of validating this. 2706 } 2707 2708 if (isa<C11NoReturnAttr>(NewAttribute)) { 2709 // C's _Noreturn is allowed to be added to a function after it is defined. 2710 ++I; 2711 continue; 2712 } else if (isa<UuidAttr>(NewAttribute)) { 2713 // msvc will allow a subsequent definition to add an uuid to a class 2714 ++I; 2715 continue; 2716 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2717 if (AA->isAlignas()) { 2718 // C++11 [dcl.align]p6: 2719 // if any declaration of an entity has an alignment-specifier, 2720 // every defining declaration of that entity shall specify an 2721 // equivalent alignment. 2722 // C11 6.7.5/7: 2723 // If the definition of an object does not have an alignment 2724 // specifier, any other declaration of that object shall also 2725 // have no alignment specifier. 2726 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2727 << AA; 2728 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2729 << AA; 2730 NewAttributes.erase(NewAttributes.begin() + I); 2731 --E; 2732 continue; 2733 } 2734 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) { 2735 // If there is a C definition followed by a redeclaration with this 2736 // attribute then there are two different definitions. In C++, prefer the 2737 // standard diagnostics. 2738 if (!S.getLangOpts().CPlusPlus) { 2739 S.Diag(NewAttribute->getLocation(), 2740 diag::err_loader_uninitialized_redeclaration); 2741 S.Diag(Def->getLocation(), diag::note_previous_definition); 2742 NewAttributes.erase(NewAttributes.begin() + I); 2743 --E; 2744 continue; 2745 } 2746 } else if (isa<SelectAnyAttr>(NewAttribute) && 2747 cast<VarDecl>(New)->isInline() && 2748 !cast<VarDecl>(New)->isInlineSpecified()) { 2749 // Don't warn about applying selectany to implicitly inline variables. 2750 // Older compilers and language modes would require the use of selectany 2751 // to make such variables inline, and it would have no effect if we 2752 // honored it. 2753 ++I; 2754 continue; 2755 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) { 2756 // We allow to add OMP[Begin]DeclareVariantAttr to be added to 2757 // declarations after defintions. 2758 ++I; 2759 continue; 2760 } 2761 2762 S.Diag(NewAttribute->getLocation(), 2763 diag::warn_attribute_precede_definition); 2764 S.Diag(Def->getLocation(), diag::note_previous_definition); 2765 NewAttributes.erase(NewAttributes.begin() + I); 2766 --E; 2767 } 2768 } 2769 2770 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, 2771 const ConstInitAttr *CIAttr, 2772 bool AttrBeforeInit) { 2773 SourceLocation InsertLoc = InitDecl->getInnerLocStart(); 2774 2775 // Figure out a good way to write this specifier on the old declaration. 2776 // FIXME: We should just use the spelling of CIAttr, but we don't preserve 2777 // enough of the attribute list spelling information to extract that without 2778 // heroics. 2779 std::string SuitableSpelling; 2780 if (S.getLangOpts().CPlusPlus20) 2781 SuitableSpelling = std::string( 2782 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit})); 2783 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2784 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2785 InsertLoc, {tok::l_square, tok::l_square, 2786 S.PP.getIdentifierInfo("clang"), tok::coloncolon, 2787 S.PP.getIdentifierInfo("require_constant_initialization"), 2788 tok::r_square, tok::r_square})); 2789 if (SuitableSpelling.empty()) 2790 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2791 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren, 2792 S.PP.getIdentifierInfo("require_constant_initialization"), 2793 tok::r_paren, tok::r_paren})); 2794 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20) 2795 SuitableSpelling = "constinit"; 2796 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2797 SuitableSpelling = "[[clang::require_constant_initialization]]"; 2798 if (SuitableSpelling.empty()) 2799 SuitableSpelling = "__attribute__((require_constant_initialization))"; 2800 SuitableSpelling += " "; 2801 2802 if (AttrBeforeInit) { 2803 // extern constinit int a; 2804 // int a = 0; // error (missing 'constinit'), accepted as extension 2805 assert(CIAttr->isConstinit() && "should not diagnose this for attribute"); 2806 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing) 2807 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 2808 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here); 2809 } else { 2810 // int a = 0; 2811 // constinit extern int a; // error (missing 'constinit') 2812 S.Diag(CIAttr->getLocation(), 2813 CIAttr->isConstinit() ? diag::err_constinit_added_too_late 2814 : diag::warn_require_const_init_added_too_late) 2815 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation())); 2816 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here) 2817 << CIAttr->isConstinit() 2818 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 2819 } 2820 } 2821 2822 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2823 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2824 AvailabilityMergeKind AMK) { 2825 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2826 UsedAttr *NewAttr = OldAttr->clone(Context); 2827 NewAttr->setInherited(true); 2828 New->addAttr(NewAttr); 2829 } 2830 2831 if (!Old->hasAttrs() && !New->hasAttrs()) 2832 return; 2833 2834 // [dcl.constinit]p1: 2835 // If the [constinit] specifier is applied to any declaration of a 2836 // variable, it shall be applied to the initializing declaration. 2837 const auto *OldConstInit = Old->getAttr<ConstInitAttr>(); 2838 const auto *NewConstInit = New->getAttr<ConstInitAttr>(); 2839 if (bool(OldConstInit) != bool(NewConstInit)) { 2840 const auto *OldVD = cast<VarDecl>(Old); 2841 auto *NewVD = cast<VarDecl>(New); 2842 2843 // Find the initializing declaration. Note that we might not have linked 2844 // the new declaration into the redeclaration chain yet. 2845 const VarDecl *InitDecl = OldVD->getInitializingDeclaration(); 2846 if (!InitDecl && 2847 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition())) 2848 InitDecl = NewVD; 2849 2850 if (InitDecl == NewVD) { 2851 // This is the initializing declaration. If it would inherit 'constinit', 2852 // that's ill-formed. (Note that we do not apply this to the attribute 2853 // form). 2854 if (OldConstInit && OldConstInit->isConstinit()) 2855 diagnoseMissingConstinit(*this, NewVD, OldConstInit, 2856 /*AttrBeforeInit=*/true); 2857 } else if (NewConstInit) { 2858 // This is the first time we've been told that this declaration should 2859 // have a constant initializer. If we already saw the initializing 2860 // declaration, this is too late. 2861 if (InitDecl && InitDecl != NewVD) { 2862 diagnoseMissingConstinit(*this, InitDecl, NewConstInit, 2863 /*AttrBeforeInit=*/false); 2864 NewVD->dropAttr<ConstInitAttr>(); 2865 } 2866 } 2867 } 2868 2869 // Attributes declared post-definition are currently ignored. 2870 checkNewAttributesAfterDef(*this, New, Old); 2871 2872 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 2873 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 2874 if (!OldA->isEquivalent(NewA)) { 2875 // This redeclaration changes __asm__ label. 2876 Diag(New->getLocation(), diag::err_different_asm_label); 2877 Diag(OldA->getLocation(), diag::note_previous_declaration); 2878 } 2879 } else if (Old->isUsed()) { 2880 // This redeclaration adds an __asm__ label to a declaration that has 2881 // already been ODR-used. 2882 Diag(New->getLocation(), diag::err_late_asm_label_name) 2883 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 2884 } 2885 } 2886 2887 // Re-declaration cannot add abi_tag's. 2888 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 2889 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 2890 for (const auto &NewTag : NewAbiTagAttr->tags()) { 2891 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(), 2892 NewTag) == OldAbiTagAttr->tags_end()) { 2893 Diag(NewAbiTagAttr->getLocation(), 2894 diag::err_new_abi_tag_on_redeclaration) 2895 << NewTag; 2896 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 2897 } 2898 } 2899 } else { 2900 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 2901 Diag(Old->getLocation(), diag::note_previous_declaration); 2902 } 2903 } 2904 2905 // This redeclaration adds a section attribute. 2906 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { 2907 if (auto *VD = dyn_cast<VarDecl>(New)) { 2908 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) { 2909 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration); 2910 Diag(Old->getLocation(), diag::note_previous_declaration); 2911 } 2912 } 2913 } 2914 2915 // Redeclaration adds code-seg attribute. 2916 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 2917 if (NewCSA && !Old->hasAttr<CodeSegAttr>() && 2918 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) { 2919 Diag(New->getLocation(), diag::warn_mismatched_section) 2920 << 0 /*codeseg*/; 2921 Diag(Old->getLocation(), diag::note_previous_declaration); 2922 } 2923 2924 if (!Old->hasAttrs()) 2925 return; 2926 2927 bool foundAny = New->hasAttrs(); 2928 2929 // Ensure that any moving of objects within the allocated map is done before 2930 // we process them. 2931 if (!foundAny) New->setAttrs(AttrVec()); 2932 2933 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2934 // Ignore deprecated/unavailable/availability attributes if requested. 2935 AvailabilityMergeKind LocalAMK = AMK_None; 2936 if (isa<DeprecatedAttr>(I) || 2937 isa<UnavailableAttr>(I) || 2938 isa<AvailabilityAttr>(I)) { 2939 switch (AMK) { 2940 case AMK_None: 2941 continue; 2942 2943 case AMK_Redeclaration: 2944 case AMK_Override: 2945 case AMK_ProtocolImplementation: 2946 LocalAMK = AMK; 2947 break; 2948 } 2949 } 2950 2951 // Already handled. 2952 if (isa<UsedAttr>(I)) 2953 continue; 2954 2955 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 2956 foundAny = true; 2957 } 2958 2959 if (mergeAlignedAttrs(*this, New, Old)) 2960 foundAny = true; 2961 2962 if (!foundAny) New->dropAttrs(); 2963 } 2964 2965 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2966 /// to the new one. 2967 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2968 const ParmVarDecl *oldDecl, 2969 Sema &S) { 2970 // C++11 [dcl.attr.depend]p2: 2971 // The first declaration of a function shall specify the 2972 // carries_dependency attribute for its declarator-id if any declaration 2973 // of the function specifies the carries_dependency attribute. 2974 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2975 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2976 S.Diag(CDA->getLocation(), 2977 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2978 // Find the first declaration of the parameter. 2979 // FIXME: Should we build redeclaration chains for function parameters? 2980 const FunctionDecl *FirstFD = 2981 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2982 const ParmVarDecl *FirstVD = 2983 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2984 S.Diag(FirstVD->getLocation(), 2985 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2986 } 2987 2988 if (!oldDecl->hasAttrs()) 2989 return; 2990 2991 bool foundAny = newDecl->hasAttrs(); 2992 2993 // Ensure that any moving of objects within the allocated map is 2994 // done before we process them. 2995 if (!foundAny) newDecl->setAttrs(AttrVec()); 2996 2997 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 2998 if (!DeclHasAttr(newDecl, I)) { 2999 InheritableAttr *newAttr = 3000 cast<InheritableParamAttr>(I->clone(S.Context)); 3001 newAttr->setInherited(true); 3002 newDecl->addAttr(newAttr); 3003 foundAny = true; 3004 } 3005 } 3006 3007 if (!foundAny) newDecl->dropAttrs(); 3008 } 3009 3010 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 3011 const ParmVarDecl *OldParam, 3012 Sema &S) { 3013 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 3014 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 3015 if (*Oldnullability != *Newnullability) { 3016 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 3017 << DiagNullabilityKind( 3018 *Newnullability, 3019 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3020 != 0)) 3021 << DiagNullabilityKind( 3022 *Oldnullability, 3023 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 3024 != 0)); 3025 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 3026 } 3027 } else { 3028 QualType NewT = NewParam->getType(); 3029 NewT = S.Context.getAttributedType( 3030 AttributedType::getNullabilityAttrKind(*Oldnullability), 3031 NewT, NewT); 3032 NewParam->setType(NewT); 3033 } 3034 } 3035 } 3036 3037 namespace { 3038 3039 /// Used in MergeFunctionDecl to keep track of function parameters in 3040 /// C. 3041 struct GNUCompatibleParamWarning { 3042 ParmVarDecl *OldParm; 3043 ParmVarDecl *NewParm; 3044 QualType PromotedType; 3045 }; 3046 3047 } // end anonymous namespace 3048 3049 // Determine whether the previous declaration was a definition, implicit 3050 // declaration, or a declaration. 3051 template <typename T> 3052 static std::pair<diag::kind, SourceLocation> 3053 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 3054 diag::kind PrevDiag; 3055 SourceLocation OldLocation = Old->getLocation(); 3056 if (Old->isThisDeclarationADefinition()) 3057 PrevDiag = diag::note_previous_definition; 3058 else if (Old->isImplicit()) { 3059 PrevDiag = diag::note_previous_implicit_declaration; 3060 if (OldLocation.isInvalid()) 3061 OldLocation = New->getLocation(); 3062 } else 3063 PrevDiag = diag::note_previous_declaration; 3064 return std::make_pair(PrevDiag, OldLocation); 3065 } 3066 3067 /// canRedefineFunction - checks if a function can be redefined. Currently, 3068 /// only extern inline functions can be redefined, and even then only in 3069 /// GNU89 mode. 3070 static bool canRedefineFunction(const FunctionDecl *FD, 3071 const LangOptions& LangOpts) { 3072 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 3073 !LangOpts.CPlusPlus && 3074 FD->isInlineSpecified() && 3075 FD->getStorageClass() == SC_Extern); 3076 } 3077 3078 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 3079 const AttributedType *AT = T->getAs<AttributedType>(); 3080 while (AT && !AT->isCallingConv()) 3081 AT = AT->getModifiedType()->getAs<AttributedType>(); 3082 return AT; 3083 } 3084 3085 template <typename T> 3086 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 3087 const DeclContext *DC = Old->getDeclContext(); 3088 if (DC->isRecord()) 3089 return false; 3090 3091 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 3092 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 3093 return true; 3094 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 3095 return true; 3096 return false; 3097 } 3098 3099 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 3100 static bool isExternC(VarTemplateDecl *) { return false; } 3101 3102 /// Check whether a redeclaration of an entity introduced by a 3103 /// using-declaration is valid, given that we know it's not an overload 3104 /// (nor a hidden tag declaration). 3105 template<typename ExpectedDecl> 3106 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 3107 ExpectedDecl *New) { 3108 // C++11 [basic.scope.declarative]p4: 3109 // Given a set of declarations in a single declarative region, each of 3110 // which specifies the same unqualified name, 3111 // -- they shall all refer to the same entity, or all refer to functions 3112 // and function templates; or 3113 // -- exactly one declaration shall declare a class name or enumeration 3114 // name that is not a typedef name and the other declarations shall all 3115 // refer to the same variable or enumerator, or all refer to functions 3116 // and function templates; in this case the class name or enumeration 3117 // name is hidden (3.3.10). 3118 3119 // C++11 [namespace.udecl]p14: 3120 // If a function declaration in namespace scope or block scope has the 3121 // same name and the same parameter-type-list as a function introduced 3122 // by a using-declaration, and the declarations do not declare the same 3123 // function, the program is ill-formed. 3124 3125 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 3126 if (Old && 3127 !Old->getDeclContext()->getRedeclContext()->Equals( 3128 New->getDeclContext()->getRedeclContext()) && 3129 !(isExternC(Old) && isExternC(New))) 3130 Old = nullptr; 3131 3132 if (!Old) { 3133 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 3134 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 3135 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 3136 return true; 3137 } 3138 return false; 3139 } 3140 3141 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 3142 const FunctionDecl *B) { 3143 assert(A->getNumParams() == B->getNumParams()); 3144 3145 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 3146 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 3147 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 3148 if (AttrA == AttrB) 3149 return true; 3150 return AttrA && AttrB && AttrA->getType() == AttrB->getType() && 3151 AttrA->isDynamic() == AttrB->isDynamic(); 3152 }; 3153 3154 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 3155 } 3156 3157 /// If necessary, adjust the semantic declaration context for a qualified 3158 /// declaration to name the correct inline namespace within the qualifier. 3159 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, 3160 DeclaratorDecl *OldD) { 3161 // The only case where we need to update the DeclContext is when 3162 // redeclaration lookup for a qualified name finds a declaration 3163 // in an inline namespace within the context named by the qualifier: 3164 // 3165 // inline namespace N { int f(); } 3166 // int ::f(); // Sema DC needs adjusting from :: to N::. 3167 // 3168 // For unqualified declarations, the semantic context *can* change 3169 // along the redeclaration chain (for local extern declarations, 3170 // extern "C" declarations, and friend declarations in particular). 3171 if (!NewD->getQualifier()) 3172 return; 3173 3174 // NewD is probably already in the right context. 3175 auto *NamedDC = NewD->getDeclContext()->getRedeclContext(); 3176 auto *SemaDC = OldD->getDeclContext()->getRedeclContext(); 3177 if (NamedDC->Equals(SemaDC)) 3178 return; 3179 3180 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || 3181 NewD->isInvalidDecl() || OldD->isInvalidDecl()) && 3182 "unexpected context for redeclaration"); 3183 3184 auto *LexDC = NewD->getLexicalDeclContext(); 3185 auto FixSemaDC = [=](NamedDecl *D) { 3186 if (!D) 3187 return; 3188 D->setDeclContext(SemaDC); 3189 D->setLexicalDeclContext(LexDC); 3190 }; 3191 3192 FixSemaDC(NewD); 3193 if (auto *FD = dyn_cast<FunctionDecl>(NewD)) 3194 FixSemaDC(FD->getDescribedFunctionTemplate()); 3195 else if (auto *VD = dyn_cast<VarDecl>(NewD)) 3196 FixSemaDC(VD->getDescribedVarTemplate()); 3197 } 3198 3199 /// MergeFunctionDecl - We just parsed a function 'New' from 3200 /// declarator D which has the same name and scope as a previous 3201 /// declaration 'Old'. Figure out how to resolve this situation, 3202 /// merging decls or emitting diagnostics as appropriate. 3203 /// 3204 /// In C++, New and Old must be declarations that are not 3205 /// overloaded. Use IsOverload to determine whether New and Old are 3206 /// overloaded, and to select the Old declaration that New should be 3207 /// merged with. 3208 /// 3209 /// Returns true if there was an error, false otherwise. 3210 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 3211 Scope *S, bool MergeTypeWithOld) { 3212 // Verify the old decl was also a function. 3213 FunctionDecl *Old = OldD->getAsFunction(); 3214 if (!Old) { 3215 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 3216 if (New->getFriendObjectKind()) { 3217 Diag(New->getLocation(), diag::err_using_decl_friend); 3218 Diag(Shadow->getTargetDecl()->getLocation(), 3219 diag::note_using_decl_target); 3220 Diag(Shadow->getUsingDecl()->getLocation(), 3221 diag::note_using_decl) << 0; 3222 return true; 3223 } 3224 3225 // Check whether the two declarations might declare the same function. 3226 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 3227 return true; 3228 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 3229 } else { 3230 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3231 << New->getDeclName(); 3232 notePreviousDefinition(OldD, New->getLocation()); 3233 return true; 3234 } 3235 } 3236 3237 // If the old declaration is invalid, just give up here. 3238 if (Old->isInvalidDecl()) 3239 return true; 3240 3241 // Disallow redeclaration of some builtins. 3242 if (!getASTContext().canBuiltinBeRedeclared(Old)) { 3243 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName(); 3244 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 3245 << Old << Old->getType(); 3246 return true; 3247 } 3248 3249 diag::kind PrevDiag; 3250 SourceLocation OldLocation; 3251 std::tie(PrevDiag, OldLocation) = 3252 getNoteDiagForInvalidRedeclaration(Old, New); 3253 3254 // Don't complain about this if we're in GNU89 mode and the old function 3255 // is an extern inline function. 3256 // Don't complain about specializations. They are not supposed to have 3257 // storage classes. 3258 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 3259 New->getStorageClass() == SC_Static && 3260 Old->hasExternalFormalLinkage() && 3261 !New->getTemplateSpecializationInfo() && 3262 !canRedefineFunction(Old, getLangOpts())) { 3263 if (getLangOpts().MicrosoftExt) { 3264 Diag(New->getLocation(), diag::ext_static_non_static) << New; 3265 Diag(OldLocation, PrevDiag); 3266 } else { 3267 Diag(New->getLocation(), diag::err_static_non_static) << New; 3268 Diag(OldLocation, PrevDiag); 3269 return true; 3270 } 3271 } 3272 3273 if (New->hasAttr<InternalLinkageAttr>() && 3274 !Old->hasAttr<InternalLinkageAttr>()) { 3275 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3276 << New->getDeclName(); 3277 notePreviousDefinition(Old, New->getLocation()); 3278 New->dropAttr<InternalLinkageAttr>(); 3279 } 3280 3281 if (CheckRedeclarationModuleOwnership(New, Old)) 3282 return true; 3283 3284 if (!getLangOpts().CPlusPlus) { 3285 bool OldOvl = Old->hasAttr<OverloadableAttr>(); 3286 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { 3287 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) 3288 << New << OldOvl; 3289 3290 // Try our best to find a decl that actually has the overloadable 3291 // attribute for the note. In most cases (e.g. programs with only one 3292 // broken declaration/definition), this won't matter. 3293 // 3294 // FIXME: We could do this if we juggled some extra state in 3295 // OverloadableAttr, rather than just removing it. 3296 const Decl *DiagOld = Old; 3297 if (OldOvl) { 3298 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { 3299 const auto *A = D->getAttr<OverloadableAttr>(); 3300 return A && !A->isImplicit(); 3301 }); 3302 // If we've implicitly added *all* of the overloadable attrs to this 3303 // chain, emitting a "previous redecl" note is pointless. 3304 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; 3305 } 3306 3307 if (DiagOld) 3308 Diag(DiagOld->getLocation(), 3309 diag::note_attribute_overloadable_prev_overload) 3310 << OldOvl; 3311 3312 if (OldOvl) 3313 New->addAttr(OverloadableAttr::CreateImplicit(Context)); 3314 else 3315 New->dropAttr<OverloadableAttr>(); 3316 } 3317 } 3318 3319 // If a function is first declared with a calling convention, but is later 3320 // declared or defined without one, all following decls assume the calling 3321 // convention of the first. 3322 // 3323 // It's OK if a function is first declared without a calling convention, 3324 // but is later declared or defined with the default calling convention. 3325 // 3326 // To test if either decl has an explicit calling convention, we look for 3327 // AttributedType sugar nodes on the type as written. If they are missing or 3328 // were canonicalized away, we assume the calling convention was implicit. 3329 // 3330 // Note also that we DO NOT return at this point, because we still have 3331 // other tests to run. 3332 QualType OldQType = Context.getCanonicalType(Old->getType()); 3333 QualType NewQType = Context.getCanonicalType(New->getType()); 3334 const FunctionType *OldType = cast<FunctionType>(OldQType); 3335 const FunctionType *NewType = cast<FunctionType>(NewQType); 3336 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 3337 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 3338 bool RequiresAdjustment = false; 3339 3340 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 3341 FunctionDecl *First = Old->getFirstDecl(); 3342 const FunctionType *FT = 3343 First->getType().getCanonicalType()->castAs<FunctionType>(); 3344 FunctionType::ExtInfo FI = FT->getExtInfo(); 3345 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 3346 if (!NewCCExplicit) { 3347 // Inherit the CC from the previous declaration if it was specified 3348 // there but not here. 3349 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3350 RequiresAdjustment = true; 3351 } else if (New->getBuiltinID()) { 3352 // Calling Conventions on a Builtin aren't really useful and setting a 3353 // default calling convention and cdecl'ing some builtin redeclarations is 3354 // common, so warn and ignore the calling convention on the redeclaration. 3355 Diag(New->getLocation(), diag::warn_cconv_unsupported) 3356 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3357 << (int)CallingConventionIgnoredReason::BuiltinFunction; 3358 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3359 RequiresAdjustment = true; 3360 } else { 3361 // Calling conventions aren't compatible, so complain. 3362 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 3363 Diag(New->getLocation(), diag::err_cconv_change) 3364 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3365 << !FirstCCExplicit 3366 << (!FirstCCExplicit ? "" : 3367 FunctionType::getNameForCallConv(FI.getCC())); 3368 3369 // Put the note on the first decl, since it is the one that matters. 3370 Diag(First->getLocation(), diag::note_previous_declaration); 3371 return true; 3372 } 3373 } 3374 3375 // FIXME: diagnose the other way around? 3376 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 3377 NewTypeInfo = NewTypeInfo.withNoReturn(true); 3378 RequiresAdjustment = true; 3379 } 3380 3381 // Merge regparm attribute. 3382 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 3383 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 3384 if (NewTypeInfo.getHasRegParm()) { 3385 Diag(New->getLocation(), diag::err_regparm_mismatch) 3386 << NewType->getRegParmType() 3387 << OldType->getRegParmType(); 3388 Diag(OldLocation, diag::note_previous_declaration); 3389 return true; 3390 } 3391 3392 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 3393 RequiresAdjustment = true; 3394 } 3395 3396 // Merge ns_returns_retained attribute. 3397 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 3398 if (NewTypeInfo.getProducesResult()) { 3399 Diag(New->getLocation(), diag::err_function_attribute_mismatch) 3400 << "'ns_returns_retained'"; 3401 Diag(OldLocation, diag::note_previous_declaration); 3402 return true; 3403 } 3404 3405 NewTypeInfo = NewTypeInfo.withProducesResult(true); 3406 RequiresAdjustment = true; 3407 } 3408 3409 if (OldTypeInfo.getNoCallerSavedRegs() != 3410 NewTypeInfo.getNoCallerSavedRegs()) { 3411 if (NewTypeInfo.getNoCallerSavedRegs()) { 3412 AnyX86NoCallerSavedRegistersAttr *Attr = 3413 New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); 3414 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; 3415 Diag(OldLocation, diag::note_previous_declaration); 3416 return true; 3417 } 3418 3419 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); 3420 RequiresAdjustment = true; 3421 } 3422 3423 if (RequiresAdjustment) { 3424 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 3425 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 3426 New->setType(QualType(AdjustedType, 0)); 3427 NewQType = Context.getCanonicalType(New->getType()); 3428 } 3429 3430 // If this redeclaration makes the function inline, we may need to add it to 3431 // UndefinedButUsed. 3432 if (!Old->isInlined() && New->isInlined() && 3433 !New->hasAttr<GNUInlineAttr>() && 3434 !getLangOpts().GNUInline && 3435 Old->isUsed(false) && 3436 !Old->isDefined() && !New->isThisDeclarationADefinition()) 3437 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3438 SourceLocation())); 3439 3440 // If this redeclaration makes it newly gnu_inline, we don't want to warn 3441 // about it. 3442 if (New->hasAttr<GNUInlineAttr>() && 3443 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 3444 UndefinedButUsed.erase(Old->getCanonicalDecl()); 3445 } 3446 3447 // If pass_object_size params don't match up perfectly, this isn't a valid 3448 // redeclaration. 3449 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 3450 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 3451 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 3452 << New->getDeclName(); 3453 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3454 return true; 3455 } 3456 3457 if (getLangOpts().CPlusPlus) { 3458 // C++1z [over.load]p2 3459 // Certain function declarations cannot be overloaded: 3460 // -- Function declarations that differ only in the return type, 3461 // the exception specification, or both cannot be overloaded. 3462 3463 // Check the exception specifications match. This may recompute the type of 3464 // both Old and New if it resolved exception specifications, so grab the 3465 // types again after this. Because this updates the type, we do this before 3466 // any of the other checks below, which may update the "de facto" NewQType 3467 // but do not necessarily update the type of New. 3468 if (CheckEquivalentExceptionSpec(Old, New)) 3469 return true; 3470 OldQType = Context.getCanonicalType(Old->getType()); 3471 NewQType = Context.getCanonicalType(New->getType()); 3472 3473 // Go back to the type source info to compare the declared return types, 3474 // per C++1y [dcl.type.auto]p13: 3475 // Redeclarations or specializations of a function or function template 3476 // with a declared return type that uses a placeholder type shall also 3477 // use that placeholder, not a deduced type. 3478 QualType OldDeclaredReturnType = Old->getDeclaredReturnType(); 3479 QualType NewDeclaredReturnType = New->getDeclaredReturnType(); 3480 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 3481 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType, 3482 OldDeclaredReturnType)) { 3483 QualType ResQT; 3484 if (NewDeclaredReturnType->isObjCObjectPointerType() && 3485 OldDeclaredReturnType->isObjCObjectPointerType()) 3486 // FIXME: This does the wrong thing for a deduced return type. 3487 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 3488 if (ResQT.isNull()) { 3489 if (New->isCXXClassMember() && New->isOutOfLine()) 3490 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 3491 << New << New->getReturnTypeSourceRange(); 3492 else 3493 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 3494 << New->getReturnTypeSourceRange(); 3495 Diag(OldLocation, PrevDiag) << Old << Old->getType() 3496 << Old->getReturnTypeSourceRange(); 3497 return true; 3498 } 3499 else 3500 NewQType = ResQT; 3501 } 3502 3503 QualType OldReturnType = OldType->getReturnType(); 3504 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 3505 if (OldReturnType != NewReturnType) { 3506 // If this function has a deduced return type and has already been 3507 // defined, copy the deduced value from the old declaration. 3508 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 3509 if (OldAT && OldAT->isDeduced()) { 3510 New->setType( 3511 SubstAutoType(New->getType(), 3512 OldAT->isDependentType() ? Context.DependentTy 3513 : OldAT->getDeducedType())); 3514 NewQType = Context.getCanonicalType( 3515 SubstAutoType(NewQType, 3516 OldAT->isDependentType() ? Context.DependentTy 3517 : OldAT->getDeducedType())); 3518 } 3519 } 3520 3521 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 3522 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 3523 if (OldMethod && NewMethod) { 3524 // Preserve triviality. 3525 NewMethod->setTrivial(OldMethod->isTrivial()); 3526 3527 // MSVC allows explicit template specialization at class scope: 3528 // 2 CXXMethodDecls referring to the same function will be injected. 3529 // We don't want a redeclaration error. 3530 bool IsClassScopeExplicitSpecialization = 3531 OldMethod->isFunctionTemplateSpecialization() && 3532 NewMethod->isFunctionTemplateSpecialization(); 3533 bool isFriend = NewMethod->getFriendObjectKind(); 3534 3535 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 3536 !IsClassScopeExplicitSpecialization) { 3537 // -- Member function declarations with the same name and the 3538 // same parameter types cannot be overloaded if any of them 3539 // is a static member function declaration. 3540 if (OldMethod->isStatic() != NewMethod->isStatic()) { 3541 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 3542 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3543 return true; 3544 } 3545 3546 // C++ [class.mem]p1: 3547 // [...] A member shall not be declared twice in the 3548 // member-specification, except that a nested class or member 3549 // class template can be declared and then later defined. 3550 if (!inTemplateInstantiation()) { 3551 unsigned NewDiag; 3552 if (isa<CXXConstructorDecl>(OldMethod)) 3553 NewDiag = diag::err_constructor_redeclared; 3554 else if (isa<CXXDestructorDecl>(NewMethod)) 3555 NewDiag = diag::err_destructor_redeclared; 3556 else if (isa<CXXConversionDecl>(NewMethod)) 3557 NewDiag = diag::err_conv_function_redeclared; 3558 else 3559 NewDiag = diag::err_member_redeclared; 3560 3561 Diag(New->getLocation(), NewDiag); 3562 } else { 3563 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 3564 << New << New->getType(); 3565 } 3566 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3567 return true; 3568 3569 // Complain if this is an explicit declaration of a special 3570 // member that was initially declared implicitly. 3571 // 3572 // As an exception, it's okay to befriend such methods in order 3573 // to permit the implicit constructor/destructor/operator calls. 3574 } else if (OldMethod->isImplicit()) { 3575 if (isFriend) { 3576 NewMethod->setImplicit(); 3577 } else { 3578 Diag(NewMethod->getLocation(), 3579 diag::err_definition_of_implicitly_declared_member) 3580 << New << getSpecialMember(OldMethod); 3581 return true; 3582 } 3583 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 3584 Diag(NewMethod->getLocation(), 3585 diag::err_definition_of_explicitly_defaulted_member) 3586 << getSpecialMember(OldMethod); 3587 return true; 3588 } 3589 } 3590 3591 // C++11 [dcl.attr.noreturn]p1: 3592 // The first declaration of a function shall specify the noreturn 3593 // attribute if any declaration of that function specifies the noreturn 3594 // attribute. 3595 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 3596 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 3597 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 3598 Diag(Old->getFirstDecl()->getLocation(), 3599 diag::note_noreturn_missing_first_decl); 3600 } 3601 3602 // C++11 [dcl.attr.depend]p2: 3603 // The first declaration of a function shall specify the 3604 // carries_dependency attribute for its declarator-id if any declaration 3605 // of the function specifies the carries_dependency attribute. 3606 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 3607 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 3608 Diag(CDA->getLocation(), 3609 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 3610 Diag(Old->getFirstDecl()->getLocation(), 3611 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 3612 } 3613 3614 // (C++98 8.3.5p3): 3615 // All declarations for a function shall agree exactly in both the 3616 // return type and the parameter-type-list. 3617 // We also want to respect all the extended bits except noreturn. 3618 3619 // noreturn should now match unless the old type info didn't have it. 3620 QualType OldQTypeForComparison = OldQType; 3621 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3622 auto *OldType = OldQType->castAs<FunctionProtoType>(); 3623 const FunctionType *OldTypeForComparison 3624 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3625 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3626 assert(OldQTypeForComparison.isCanonical()); 3627 } 3628 3629 if (haveIncompatibleLanguageLinkages(Old, New)) { 3630 // As a special case, retain the language linkage from previous 3631 // declarations of a friend function as an extension. 3632 // 3633 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3634 // and is useful because there's otherwise no way to specify language 3635 // linkage within class scope. 3636 // 3637 // Check cautiously as the friend object kind isn't yet complete. 3638 if (New->getFriendObjectKind() != Decl::FOK_None) { 3639 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3640 Diag(OldLocation, PrevDiag); 3641 } else { 3642 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3643 Diag(OldLocation, PrevDiag); 3644 return true; 3645 } 3646 } 3647 3648 // If the function types are compatible, merge the declarations. Ignore the 3649 // exception specifier because it was already checked above in 3650 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics 3651 // about incompatible types under -fms-compatibility. 3652 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison, 3653 NewQType)) 3654 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3655 3656 // If the types are imprecise (due to dependent constructs in friends or 3657 // local extern declarations), it's OK if they differ. We'll check again 3658 // during instantiation. 3659 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType)) 3660 return false; 3661 3662 // Fall through for conflicting redeclarations and redefinitions. 3663 } 3664 3665 // C: Function types need to be compatible, not identical. This handles 3666 // duplicate function decls like "void f(int); void f(enum X);" properly. 3667 if (!getLangOpts().CPlusPlus && 3668 Context.typesAreCompatible(OldQType, NewQType)) { 3669 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 3670 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 3671 const FunctionProtoType *OldProto = nullptr; 3672 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 3673 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 3674 // The old declaration provided a function prototype, but the 3675 // new declaration does not. Merge in the prototype. 3676 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 3677 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 3678 NewQType = 3679 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 3680 OldProto->getExtProtoInfo()); 3681 New->setType(NewQType); 3682 New->setHasInheritedPrototype(); 3683 3684 // Synthesize parameters with the same types. 3685 SmallVector<ParmVarDecl*, 16> Params; 3686 for (const auto &ParamType : OldProto->param_types()) { 3687 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 3688 SourceLocation(), nullptr, 3689 ParamType, /*TInfo=*/nullptr, 3690 SC_None, nullptr); 3691 Param->setScopeInfo(0, Params.size()); 3692 Param->setImplicit(); 3693 Params.push_back(Param); 3694 } 3695 3696 New->setParams(Params); 3697 } 3698 3699 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3700 } 3701 3702 // Check if the function types are compatible when pointer size address 3703 // spaces are ignored. 3704 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType)) 3705 return false; 3706 3707 // GNU C permits a K&R definition to follow a prototype declaration 3708 // if the declared types of the parameters in the K&R definition 3709 // match the types in the prototype declaration, even when the 3710 // promoted types of the parameters from the K&R definition differ 3711 // from the types in the prototype. GCC then keeps the types from 3712 // the prototype. 3713 // 3714 // If a variadic prototype is followed by a non-variadic K&R definition, 3715 // the K&R definition becomes variadic. This is sort of an edge case, but 3716 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 3717 // C99 6.9.1p8. 3718 if (!getLangOpts().CPlusPlus && 3719 Old->hasPrototype() && !New->hasPrototype() && 3720 New->getType()->getAs<FunctionProtoType>() && 3721 Old->getNumParams() == New->getNumParams()) { 3722 SmallVector<QualType, 16> ArgTypes; 3723 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 3724 const FunctionProtoType *OldProto 3725 = Old->getType()->getAs<FunctionProtoType>(); 3726 const FunctionProtoType *NewProto 3727 = New->getType()->getAs<FunctionProtoType>(); 3728 3729 // Determine whether this is the GNU C extension. 3730 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 3731 NewProto->getReturnType()); 3732 bool LooseCompatible = !MergedReturn.isNull(); 3733 for (unsigned Idx = 0, End = Old->getNumParams(); 3734 LooseCompatible && Idx != End; ++Idx) { 3735 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 3736 ParmVarDecl *NewParm = New->getParamDecl(Idx); 3737 if (Context.typesAreCompatible(OldParm->getType(), 3738 NewProto->getParamType(Idx))) { 3739 ArgTypes.push_back(NewParm->getType()); 3740 } else if (Context.typesAreCompatible(OldParm->getType(), 3741 NewParm->getType(), 3742 /*CompareUnqualified=*/true)) { 3743 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 3744 NewProto->getParamType(Idx) }; 3745 Warnings.push_back(Warn); 3746 ArgTypes.push_back(NewParm->getType()); 3747 } else 3748 LooseCompatible = false; 3749 } 3750 3751 if (LooseCompatible) { 3752 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 3753 Diag(Warnings[Warn].NewParm->getLocation(), 3754 diag::ext_param_promoted_not_compatible_with_prototype) 3755 << Warnings[Warn].PromotedType 3756 << Warnings[Warn].OldParm->getType(); 3757 if (Warnings[Warn].OldParm->getLocation().isValid()) 3758 Diag(Warnings[Warn].OldParm->getLocation(), 3759 diag::note_previous_declaration); 3760 } 3761 3762 if (MergeTypeWithOld) 3763 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 3764 OldProto->getExtProtoInfo())); 3765 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3766 } 3767 3768 // Fall through to diagnose conflicting types. 3769 } 3770 3771 // A function that has already been declared has been redeclared or 3772 // defined with a different type; show an appropriate diagnostic. 3773 3774 // If the previous declaration was an implicitly-generated builtin 3775 // declaration, then at the very least we should use a specialized note. 3776 unsigned BuiltinID; 3777 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3778 // If it's actually a library-defined builtin function like 'malloc' 3779 // or 'printf', just warn about the incompatible redeclaration. 3780 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3781 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3782 Diag(OldLocation, diag::note_previous_builtin_declaration) 3783 << Old << Old->getType(); 3784 3785 // If this is a global redeclaration, just forget hereafter 3786 // about the "builtin-ness" of the function. 3787 // 3788 // Doing this for local extern declarations is problematic. If 3789 // the builtin declaration remains visible, a second invalid 3790 // local declaration will produce a hard error; if it doesn't 3791 // remain visible, a single bogus local redeclaration (which is 3792 // actually only a warning) could break all the downstream code. 3793 if (!New->getLexicalDeclContext()->isFunctionOrMethod()) 3794 New->getIdentifier()->revertBuiltin(); 3795 3796 return false; 3797 } 3798 3799 PrevDiag = diag::note_previous_builtin_declaration; 3800 } 3801 3802 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3803 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3804 return true; 3805 } 3806 3807 /// Completes the merge of two function declarations that are 3808 /// known to be compatible. 3809 /// 3810 /// This routine handles the merging of attributes and other 3811 /// properties of function declarations from the old declaration to 3812 /// the new declaration, once we know that New is in fact a 3813 /// redeclaration of Old. 3814 /// 3815 /// \returns false 3816 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3817 Scope *S, bool MergeTypeWithOld) { 3818 // Merge the attributes 3819 mergeDeclAttributes(New, Old); 3820 3821 // Merge "pure" flag. 3822 if (Old->isPure()) 3823 New->setPure(); 3824 3825 // Merge "used" flag. 3826 if (Old->getMostRecentDecl()->isUsed(false)) 3827 New->setIsUsed(); 3828 3829 // Merge attributes from the parameters. These can mismatch with K&R 3830 // declarations. 3831 if (New->getNumParams() == Old->getNumParams()) 3832 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 3833 ParmVarDecl *NewParam = New->getParamDecl(i); 3834 ParmVarDecl *OldParam = Old->getParamDecl(i); 3835 mergeParamDeclAttributes(NewParam, OldParam, *this); 3836 mergeParamDeclTypes(NewParam, OldParam, *this); 3837 } 3838 3839 if (getLangOpts().CPlusPlus) 3840 return MergeCXXFunctionDecl(New, Old, S); 3841 3842 // Merge the function types so the we get the composite types for the return 3843 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3844 // was visible. 3845 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3846 if (!Merged.isNull() && MergeTypeWithOld) 3847 New->setType(Merged); 3848 3849 return false; 3850 } 3851 3852 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3853 ObjCMethodDecl *oldMethod) { 3854 // Merge the attributes, including deprecated/unavailable 3855 AvailabilityMergeKind MergeKind = 3856 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 3857 ? AMK_ProtocolImplementation 3858 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3859 : AMK_Override; 3860 3861 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3862 3863 // Merge attributes from the parameters. 3864 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3865 oe = oldMethod->param_end(); 3866 for (ObjCMethodDecl::param_iterator 3867 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3868 ni != ne && oi != oe; ++ni, ++oi) 3869 mergeParamDeclAttributes(*ni, *oi, *this); 3870 3871 CheckObjCMethodOverride(newMethod, oldMethod); 3872 } 3873 3874 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 3875 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 3876 3877 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 3878 ? diag::err_redefinition_different_type 3879 : diag::err_redeclaration_different_type) 3880 << New->getDeclName() << New->getType() << Old->getType(); 3881 3882 diag::kind PrevDiag; 3883 SourceLocation OldLocation; 3884 std::tie(PrevDiag, OldLocation) 3885 = getNoteDiagForInvalidRedeclaration(Old, New); 3886 S.Diag(OldLocation, PrevDiag); 3887 New->setInvalidDecl(); 3888 } 3889 3890 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3891 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3892 /// emitting diagnostics as appropriate. 3893 /// 3894 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3895 /// to here in AddInitializerToDecl. We can't check them before the initializer 3896 /// is attached. 3897 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3898 bool MergeTypeWithOld) { 3899 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3900 return; 3901 3902 QualType MergedT; 3903 if (getLangOpts().CPlusPlus) { 3904 if (New->getType()->isUndeducedType()) { 3905 // We don't know what the new type is until the initializer is attached. 3906 return; 3907 } else if (Context.hasSameType(New->getType(), Old->getType())) { 3908 // These could still be something that needs exception specs checked. 3909 return MergeVarDeclExceptionSpecs(New, Old); 3910 } 3911 // C++ [basic.link]p10: 3912 // [...] the types specified by all declarations referring to a given 3913 // object or function shall be identical, except that declarations for an 3914 // array object can specify array types that differ by the presence or 3915 // absence of a major array bound (8.3.4). 3916 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 3917 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3918 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3919 3920 // We are merging a variable declaration New into Old. If it has an array 3921 // bound, and that bound differs from Old's bound, we should diagnose the 3922 // mismatch. 3923 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 3924 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 3925 PrevVD = PrevVD->getPreviousDecl()) { 3926 QualType PrevVDTy = PrevVD->getType(); 3927 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 3928 continue; 3929 3930 if (!Context.hasSameType(New->getType(), PrevVDTy)) 3931 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 3932 } 3933 } 3934 3935 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 3936 if (Context.hasSameType(OldArray->getElementType(), 3937 NewArray->getElementType())) 3938 MergedT = New->getType(); 3939 } 3940 // FIXME: Check visibility. New is hidden but has a complete type. If New 3941 // has no array bound, it should not inherit one from Old, if Old is not 3942 // visible. 3943 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 3944 if (Context.hasSameType(OldArray->getElementType(), 3945 NewArray->getElementType())) 3946 MergedT = Old->getType(); 3947 } 3948 } 3949 else if (New->getType()->isObjCObjectPointerType() && 3950 Old->getType()->isObjCObjectPointerType()) { 3951 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 3952 Old->getType()); 3953 } 3954 } else { 3955 // C 6.2.7p2: 3956 // All declarations that refer to the same object or function shall have 3957 // compatible type. 3958 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 3959 } 3960 if (MergedT.isNull()) { 3961 // It's OK if we couldn't merge types if either type is dependent, for a 3962 // block-scope variable. In other cases (static data members of class 3963 // templates, variable templates, ...), we require the types to be 3964 // equivalent. 3965 // FIXME: The C++ standard doesn't say anything about this. 3966 if ((New->getType()->isDependentType() || 3967 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 3968 // If the old type was dependent, we can't merge with it, so the new type 3969 // becomes dependent for now. We'll reproduce the original type when we 3970 // instantiate the TypeSourceInfo for the variable. 3971 if (!New->getType()->isDependentType() && MergeTypeWithOld) 3972 New->setType(Context.DependentTy); 3973 return; 3974 } 3975 return diagnoseVarDeclTypeMismatch(*this, New, Old); 3976 } 3977 3978 // Don't actually update the type on the new declaration if the old 3979 // declaration was an extern declaration in a different scope. 3980 if (MergeTypeWithOld) 3981 New->setType(MergedT); 3982 } 3983 3984 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 3985 LookupResult &Previous) { 3986 // C11 6.2.7p4: 3987 // For an identifier with internal or external linkage declared 3988 // in a scope in which a prior declaration of that identifier is 3989 // visible, if the prior declaration specifies internal or 3990 // external linkage, the type of the identifier at the later 3991 // declaration becomes the composite type. 3992 // 3993 // If the variable isn't visible, we do not merge with its type. 3994 if (Previous.isShadowed()) 3995 return false; 3996 3997 if (S.getLangOpts().CPlusPlus) { 3998 // C++11 [dcl.array]p3: 3999 // If there is a preceding declaration of the entity in the same 4000 // scope in which the bound was specified, an omitted array bound 4001 // is taken to be the same as in that earlier declaration. 4002 return NewVD->isPreviousDeclInSameBlockScope() || 4003 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 4004 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 4005 } else { 4006 // If the old declaration was function-local, don't merge with its 4007 // type unless we're in the same function. 4008 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 4009 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 4010 } 4011 } 4012 4013 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 4014 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 4015 /// situation, merging decls or emitting diagnostics as appropriate. 4016 /// 4017 /// Tentative definition rules (C99 6.9.2p2) are checked by 4018 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 4019 /// definitions here, since the initializer hasn't been attached. 4020 /// 4021 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 4022 // If the new decl is already invalid, don't do any other checking. 4023 if (New->isInvalidDecl()) 4024 return; 4025 4026 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 4027 return; 4028 4029 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 4030 4031 // Verify the old decl was also a variable or variable template. 4032 VarDecl *Old = nullptr; 4033 VarTemplateDecl *OldTemplate = nullptr; 4034 if (Previous.isSingleResult()) { 4035 if (NewTemplate) { 4036 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 4037 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 4038 4039 if (auto *Shadow = 4040 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4041 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 4042 return New->setInvalidDecl(); 4043 } else { 4044 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 4045 4046 if (auto *Shadow = 4047 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4048 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 4049 return New->setInvalidDecl(); 4050 } 4051 } 4052 if (!Old) { 4053 Diag(New->getLocation(), diag::err_redefinition_different_kind) 4054 << New->getDeclName(); 4055 notePreviousDefinition(Previous.getRepresentativeDecl(), 4056 New->getLocation()); 4057 return New->setInvalidDecl(); 4058 } 4059 4060 // Ensure the template parameters are compatible. 4061 if (NewTemplate && 4062 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 4063 OldTemplate->getTemplateParameters(), 4064 /*Complain=*/true, TPL_TemplateMatch)) 4065 return New->setInvalidDecl(); 4066 4067 // C++ [class.mem]p1: 4068 // A member shall not be declared twice in the member-specification [...] 4069 // 4070 // Here, we need only consider static data members. 4071 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 4072 Diag(New->getLocation(), diag::err_duplicate_member) 4073 << New->getIdentifier(); 4074 Diag(Old->getLocation(), diag::note_previous_declaration); 4075 New->setInvalidDecl(); 4076 } 4077 4078 mergeDeclAttributes(New, Old); 4079 // Warn if an already-declared variable is made a weak_import in a subsequent 4080 // declaration 4081 if (New->hasAttr<WeakImportAttr>() && 4082 Old->getStorageClass() == SC_None && 4083 !Old->hasAttr<WeakImportAttr>()) { 4084 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 4085 notePreviousDefinition(Old, New->getLocation()); 4086 // Remove weak_import attribute on new declaration. 4087 New->dropAttr<WeakImportAttr>(); 4088 } 4089 4090 if (New->hasAttr<InternalLinkageAttr>() && 4091 !Old->hasAttr<InternalLinkageAttr>()) { 4092 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 4093 << New->getDeclName(); 4094 notePreviousDefinition(Old, New->getLocation()); 4095 New->dropAttr<InternalLinkageAttr>(); 4096 } 4097 4098 // Merge the types. 4099 VarDecl *MostRecent = Old->getMostRecentDecl(); 4100 if (MostRecent != Old) { 4101 MergeVarDeclTypes(New, MostRecent, 4102 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 4103 if (New->isInvalidDecl()) 4104 return; 4105 } 4106 4107 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 4108 if (New->isInvalidDecl()) 4109 return; 4110 4111 diag::kind PrevDiag; 4112 SourceLocation OldLocation; 4113 std::tie(PrevDiag, OldLocation) = 4114 getNoteDiagForInvalidRedeclaration(Old, New); 4115 4116 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 4117 if (New->getStorageClass() == SC_Static && 4118 !New->isStaticDataMember() && 4119 Old->hasExternalFormalLinkage()) { 4120 if (getLangOpts().MicrosoftExt) { 4121 Diag(New->getLocation(), diag::ext_static_non_static) 4122 << New->getDeclName(); 4123 Diag(OldLocation, PrevDiag); 4124 } else { 4125 Diag(New->getLocation(), diag::err_static_non_static) 4126 << New->getDeclName(); 4127 Diag(OldLocation, PrevDiag); 4128 return New->setInvalidDecl(); 4129 } 4130 } 4131 // C99 6.2.2p4: 4132 // For an identifier declared with the storage-class specifier 4133 // extern in a scope in which a prior declaration of that 4134 // identifier is visible,23) if the prior declaration specifies 4135 // internal or external linkage, the linkage of the identifier at 4136 // the later declaration is the same as the linkage specified at 4137 // the prior declaration. If no prior declaration is visible, or 4138 // if the prior declaration specifies no linkage, then the 4139 // identifier has external linkage. 4140 if (New->hasExternalStorage() && Old->hasLinkage()) 4141 /* Okay */; 4142 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 4143 !New->isStaticDataMember() && 4144 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 4145 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 4146 Diag(OldLocation, PrevDiag); 4147 return New->setInvalidDecl(); 4148 } 4149 4150 // Check if extern is followed by non-extern and vice-versa. 4151 if (New->hasExternalStorage() && 4152 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 4153 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 4154 Diag(OldLocation, PrevDiag); 4155 return New->setInvalidDecl(); 4156 } 4157 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 4158 !New->hasExternalStorage()) { 4159 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 4160 Diag(OldLocation, PrevDiag); 4161 return New->setInvalidDecl(); 4162 } 4163 4164 if (CheckRedeclarationModuleOwnership(New, Old)) 4165 return; 4166 4167 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 4168 4169 // FIXME: The test for external storage here seems wrong? We still 4170 // need to check for mismatches. 4171 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 4172 // Don't complain about out-of-line definitions of static members. 4173 !(Old->getLexicalDeclContext()->isRecord() && 4174 !New->getLexicalDeclContext()->isRecord())) { 4175 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 4176 Diag(OldLocation, PrevDiag); 4177 return New->setInvalidDecl(); 4178 } 4179 4180 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 4181 if (VarDecl *Def = Old->getDefinition()) { 4182 // C++1z [dcl.fcn.spec]p4: 4183 // If the definition of a variable appears in a translation unit before 4184 // its first declaration as inline, the program is ill-formed. 4185 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 4186 Diag(Def->getLocation(), diag::note_previous_definition); 4187 } 4188 } 4189 4190 // If this redeclaration makes the variable inline, we may need to add it to 4191 // UndefinedButUsed. 4192 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 4193 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 4194 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 4195 SourceLocation())); 4196 4197 if (New->getTLSKind() != Old->getTLSKind()) { 4198 if (!Old->getTLSKind()) { 4199 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 4200 Diag(OldLocation, PrevDiag); 4201 } else if (!New->getTLSKind()) { 4202 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 4203 Diag(OldLocation, PrevDiag); 4204 } else { 4205 // Do not allow redeclaration to change the variable between requiring 4206 // static and dynamic initialization. 4207 // FIXME: GCC allows this, but uses the TLS keyword on the first 4208 // declaration to determine the kind. Do we need to be compatible here? 4209 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 4210 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 4211 Diag(OldLocation, PrevDiag); 4212 } 4213 } 4214 4215 // C++ doesn't have tentative definitions, so go right ahead and check here. 4216 if (getLangOpts().CPlusPlus && 4217 New->isThisDeclarationADefinition() == VarDecl::Definition) { 4218 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 4219 Old->getCanonicalDecl()->isConstexpr()) { 4220 // This definition won't be a definition any more once it's been merged. 4221 Diag(New->getLocation(), 4222 diag::warn_deprecated_redundant_constexpr_static_def); 4223 } else if (VarDecl *Def = Old->getDefinition()) { 4224 if (checkVarDeclRedefinition(Def, New)) 4225 return; 4226 } 4227 } 4228 4229 if (haveIncompatibleLanguageLinkages(Old, New)) { 4230 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 4231 Diag(OldLocation, PrevDiag); 4232 New->setInvalidDecl(); 4233 return; 4234 } 4235 4236 // Merge "used" flag. 4237 if (Old->getMostRecentDecl()->isUsed(false)) 4238 New->setIsUsed(); 4239 4240 // Keep a chain of previous declarations. 4241 New->setPreviousDecl(Old); 4242 if (NewTemplate) 4243 NewTemplate->setPreviousDecl(OldTemplate); 4244 adjustDeclContextForDeclaratorDecl(New, Old); 4245 4246 // Inherit access appropriately. 4247 New->setAccess(Old->getAccess()); 4248 if (NewTemplate) 4249 NewTemplate->setAccess(New->getAccess()); 4250 4251 if (Old->isInline()) 4252 New->setImplicitlyInline(); 4253 } 4254 4255 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { 4256 SourceManager &SrcMgr = getSourceManager(); 4257 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); 4258 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); 4259 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); 4260 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); 4261 auto &HSI = PP.getHeaderSearchInfo(); 4262 StringRef HdrFilename = 4263 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); 4264 4265 auto noteFromModuleOrInclude = [&](Module *Mod, 4266 SourceLocation IncLoc) -> bool { 4267 // Redefinition errors with modules are common with non modular mapped 4268 // headers, example: a non-modular header H in module A that also gets 4269 // included directly in a TU. Pointing twice to the same header/definition 4270 // is confusing, try to get better diagnostics when modules is on. 4271 if (IncLoc.isValid()) { 4272 if (Mod) { 4273 Diag(IncLoc, diag::note_redefinition_modules_same_file) 4274 << HdrFilename.str() << Mod->getFullModuleName(); 4275 if (!Mod->DefinitionLoc.isInvalid()) 4276 Diag(Mod->DefinitionLoc, diag::note_defined_here) 4277 << Mod->getFullModuleName(); 4278 } else { 4279 Diag(IncLoc, diag::note_redefinition_include_same_file) 4280 << HdrFilename.str(); 4281 } 4282 return true; 4283 } 4284 4285 return false; 4286 }; 4287 4288 // Is it the same file and same offset? Provide more information on why 4289 // this leads to a redefinition error. 4290 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { 4291 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); 4292 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); 4293 bool EmittedDiag = 4294 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); 4295 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); 4296 4297 // If the header has no guards, emit a note suggesting one. 4298 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) 4299 Diag(Old->getLocation(), diag::note_use_ifdef_guards); 4300 4301 if (EmittedDiag) 4302 return; 4303 } 4304 4305 // Redefinition coming from different files or couldn't do better above. 4306 if (Old->getLocation().isValid()) 4307 Diag(Old->getLocation(), diag::note_previous_definition); 4308 } 4309 4310 /// We've just determined that \p Old and \p New both appear to be definitions 4311 /// of the same variable. Either diagnose or fix the problem. 4312 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 4313 if (!hasVisibleDefinition(Old) && 4314 (New->getFormalLinkage() == InternalLinkage || 4315 New->isInline() || 4316 New->getDescribedVarTemplate() || 4317 New->getNumTemplateParameterLists() || 4318 New->getDeclContext()->isDependentContext())) { 4319 // The previous definition is hidden, and multiple definitions are 4320 // permitted (in separate TUs). Demote this to a declaration. 4321 New->demoteThisDefinitionToDeclaration(); 4322 4323 // Make the canonical definition visible. 4324 if (auto *OldTD = Old->getDescribedVarTemplate()) 4325 makeMergedDefinitionVisible(OldTD); 4326 makeMergedDefinitionVisible(Old); 4327 return false; 4328 } else { 4329 Diag(New->getLocation(), diag::err_redefinition) << New; 4330 notePreviousDefinition(Old, New->getLocation()); 4331 New->setInvalidDecl(); 4332 return true; 4333 } 4334 } 4335 4336 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4337 /// no declarator (e.g. "struct foo;") is parsed. 4338 Decl * 4339 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4340 RecordDecl *&AnonRecord) { 4341 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, 4342 AnonRecord); 4343 } 4344 4345 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 4346 // disambiguate entities defined in different scopes. 4347 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 4348 // compatibility. 4349 // We will pick our mangling number depending on which version of MSVC is being 4350 // targeted. 4351 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 4352 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 4353 ? S->getMSCurManglingNumber() 4354 : S->getMSLastManglingNumber(); 4355 } 4356 4357 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 4358 if (!Context.getLangOpts().CPlusPlus) 4359 return; 4360 4361 if (isa<CXXRecordDecl>(Tag->getParent())) { 4362 // If this tag is the direct child of a class, number it if 4363 // it is anonymous. 4364 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 4365 return; 4366 MangleNumberingContext &MCtx = 4367 Context.getManglingNumberContext(Tag->getParent()); 4368 Context.setManglingNumber( 4369 Tag, MCtx.getManglingNumber( 4370 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4371 return; 4372 } 4373 4374 // If this tag isn't a direct child of a class, number it if it is local. 4375 MangleNumberingContext *MCtx; 4376 Decl *ManglingContextDecl; 4377 std::tie(MCtx, ManglingContextDecl) = 4378 getCurrentMangleNumberContext(Tag->getDeclContext()); 4379 if (MCtx) { 4380 Context.setManglingNumber( 4381 Tag, MCtx->getManglingNumber( 4382 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4383 } 4384 } 4385 4386 namespace { 4387 struct NonCLikeKind { 4388 enum { 4389 None, 4390 BaseClass, 4391 DefaultMemberInit, 4392 Lambda, 4393 Friend, 4394 OtherMember, 4395 Invalid, 4396 } Kind = None; 4397 SourceRange Range; 4398 4399 explicit operator bool() { return Kind != None; } 4400 }; 4401 } 4402 4403 /// Determine whether a class is C-like, according to the rules of C++ 4404 /// [dcl.typedef] for anonymous classes with typedef names for linkage. 4405 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) { 4406 if (RD->isInvalidDecl()) 4407 return {NonCLikeKind::Invalid, {}}; 4408 4409 // C++ [dcl.typedef]p9: [P1766R1] 4410 // An unnamed class with a typedef name for linkage purposes shall not 4411 // 4412 // -- have any base classes 4413 if (RD->getNumBases()) 4414 return {NonCLikeKind::BaseClass, 4415 SourceRange(RD->bases_begin()->getBeginLoc(), 4416 RD->bases_end()[-1].getEndLoc())}; 4417 bool Invalid = false; 4418 for (Decl *D : RD->decls()) { 4419 // Don't complain about things we already diagnosed. 4420 if (D->isInvalidDecl()) { 4421 Invalid = true; 4422 continue; 4423 } 4424 4425 // -- have any [...] default member initializers 4426 if (auto *FD = dyn_cast<FieldDecl>(D)) { 4427 if (FD->hasInClassInitializer()) { 4428 auto *Init = FD->getInClassInitializer(); 4429 return {NonCLikeKind::DefaultMemberInit, 4430 Init ? Init->getSourceRange() : D->getSourceRange()}; 4431 } 4432 continue; 4433 } 4434 4435 // FIXME: We don't allow friend declarations. This violates the wording of 4436 // P1766, but not the intent. 4437 if (isa<FriendDecl>(D)) 4438 return {NonCLikeKind::Friend, D->getSourceRange()}; 4439 4440 // -- declare any members other than non-static data members, member 4441 // enumerations, or member classes, 4442 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) || 4443 isa<EnumDecl>(D)) 4444 continue; 4445 auto *MemberRD = dyn_cast<CXXRecordDecl>(D); 4446 if (!MemberRD) { 4447 if (D->isImplicit()) 4448 continue; 4449 return {NonCLikeKind::OtherMember, D->getSourceRange()}; 4450 } 4451 4452 // -- contain a lambda-expression, 4453 if (MemberRD->isLambda()) 4454 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()}; 4455 4456 // and all member classes shall also satisfy these requirements 4457 // (recursively). 4458 if (MemberRD->isThisDeclarationADefinition()) { 4459 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD)) 4460 return Kind; 4461 } 4462 } 4463 4464 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}}; 4465 } 4466 4467 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 4468 TypedefNameDecl *NewTD) { 4469 if (TagFromDeclSpec->isInvalidDecl()) 4470 return; 4471 4472 // Do nothing if the tag already has a name for linkage purposes. 4473 if (TagFromDeclSpec->hasNameForLinkage()) 4474 return; 4475 4476 // A well-formed anonymous tag must always be a TUK_Definition. 4477 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 4478 4479 // The type must match the tag exactly; no qualifiers allowed. 4480 if (!Context.hasSameType(NewTD->getUnderlyingType(), 4481 Context.getTagDeclType(TagFromDeclSpec))) { 4482 if (getLangOpts().CPlusPlus) 4483 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 4484 return; 4485 } 4486 4487 // C++ [dcl.typedef]p9: [P1766R1, applied as DR] 4488 // An unnamed class with a typedef name for linkage purposes shall [be 4489 // C-like]. 4490 // 4491 // FIXME: Also diagnose if we've already computed the linkage. That ideally 4492 // shouldn't happen, but there are constructs that the language rule doesn't 4493 // disallow for which we can't reasonably avoid computing linkage early. 4494 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec); 4495 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD) 4496 : NonCLikeKind(); 4497 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed(); 4498 if (NonCLike || ChangesLinkage) { 4499 if (NonCLike.Kind == NonCLikeKind::Invalid) 4500 return; 4501 4502 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef; 4503 if (ChangesLinkage) { 4504 // If the linkage changes, we can't accept this as an extension. 4505 if (NonCLike.Kind == NonCLikeKind::None) 4506 DiagID = diag::err_typedef_changes_linkage; 4507 else 4508 DiagID = diag::err_non_c_like_anon_struct_in_typedef; 4509 } 4510 4511 SourceLocation FixitLoc = 4512 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart()); 4513 llvm::SmallString<40> TextToInsert; 4514 TextToInsert += ' '; 4515 TextToInsert += NewTD->getIdentifier()->getName(); 4516 4517 Diag(FixitLoc, DiagID) 4518 << isa<TypeAliasDecl>(NewTD) 4519 << FixItHint::CreateInsertion(FixitLoc, TextToInsert); 4520 if (NonCLike.Kind != NonCLikeKind::None) { 4521 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct) 4522 << NonCLike.Kind - 1 << NonCLike.Range; 4523 } 4524 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here) 4525 << NewTD << isa<TypeAliasDecl>(NewTD); 4526 4527 if (ChangesLinkage) 4528 return; 4529 } 4530 4531 // Otherwise, set this as the anon-decl typedef for the tag. 4532 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 4533 } 4534 4535 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 4536 switch (T) { 4537 case DeclSpec::TST_class: 4538 return 0; 4539 case DeclSpec::TST_struct: 4540 return 1; 4541 case DeclSpec::TST_interface: 4542 return 2; 4543 case DeclSpec::TST_union: 4544 return 3; 4545 case DeclSpec::TST_enum: 4546 return 4; 4547 default: 4548 llvm_unreachable("unexpected type specifier"); 4549 } 4550 } 4551 4552 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4553 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 4554 /// parameters to cope with template friend declarations. 4555 Decl * 4556 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4557 MultiTemplateParamsArg TemplateParams, 4558 bool IsExplicitInstantiation, 4559 RecordDecl *&AnonRecord) { 4560 Decl *TagD = nullptr; 4561 TagDecl *Tag = nullptr; 4562 if (DS.getTypeSpecType() == DeclSpec::TST_class || 4563 DS.getTypeSpecType() == DeclSpec::TST_struct || 4564 DS.getTypeSpecType() == DeclSpec::TST_interface || 4565 DS.getTypeSpecType() == DeclSpec::TST_union || 4566 DS.getTypeSpecType() == DeclSpec::TST_enum) { 4567 TagD = DS.getRepAsDecl(); 4568 4569 if (!TagD) // We probably had an error 4570 return nullptr; 4571 4572 // Note that the above type specs guarantee that the 4573 // type rep is a Decl, whereas in many of the others 4574 // it's a Type. 4575 if (isa<TagDecl>(TagD)) 4576 Tag = cast<TagDecl>(TagD); 4577 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 4578 Tag = CTD->getTemplatedDecl(); 4579 } 4580 4581 if (Tag) { 4582 handleTagNumbering(Tag, S); 4583 Tag->setFreeStanding(); 4584 if (Tag->isInvalidDecl()) 4585 return Tag; 4586 } 4587 4588 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 4589 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 4590 // or incomplete types shall not be restrict-qualified." 4591 if (TypeQuals & DeclSpec::TQ_restrict) 4592 Diag(DS.getRestrictSpecLoc(), 4593 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 4594 << DS.getSourceRange(); 4595 } 4596 4597 if (DS.isInlineSpecified()) 4598 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 4599 << getLangOpts().CPlusPlus17; 4600 4601 if (DS.hasConstexprSpecifier()) { 4602 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 4603 // and definitions of functions and variables. 4604 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to 4605 // the declaration of a function or function template 4606 if (Tag) 4607 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 4608 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) 4609 << DS.getConstexprSpecifier(); 4610 else 4611 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind) 4612 << DS.getConstexprSpecifier(); 4613 // Don't emit warnings after this error. 4614 return TagD; 4615 } 4616 4617 DiagnoseFunctionSpecifiers(DS); 4618 4619 if (DS.isFriendSpecified()) { 4620 // If we're dealing with a decl but not a TagDecl, assume that 4621 // whatever routines created it handled the friendship aspect. 4622 if (TagD && !Tag) 4623 return nullptr; 4624 return ActOnFriendTypeDecl(S, DS, TemplateParams); 4625 } 4626 4627 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 4628 bool IsExplicitSpecialization = 4629 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 4630 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 4631 !IsExplicitInstantiation && !IsExplicitSpecialization && 4632 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 4633 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 4634 // nested-name-specifier unless it is an explicit instantiation 4635 // or an explicit specialization. 4636 // 4637 // FIXME: We allow class template partial specializations here too, per the 4638 // obvious intent of DR1819. 4639 // 4640 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 4641 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 4642 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 4643 return nullptr; 4644 } 4645 4646 // Track whether this decl-specifier declares anything. 4647 bool DeclaresAnything = true; 4648 4649 // Handle anonymous struct definitions. 4650 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 4651 if (!Record->getDeclName() && Record->isCompleteDefinition() && 4652 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 4653 if (getLangOpts().CPlusPlus || 4654 Record->getDeclContext()->isRecord()) { 4655 // If CurContext is a DeclContext that can contain statements, 4656 // RecursiveASTVisitor won't visit the decls that 4657 // BuildAnonymousStructOrUnion() will put into CurContext. 4658 // Also store them here so that they can be part of the 4659 // DeclStmt that gets created in this case. 4660 // FIXME: Also return the IndirectFieldDecls created by 4661 // BuildAnonymousStructOr union, for the same reason? 4662 if (CurContext->isFunctionOrMethod()) 4663 AnonRecord = Record; 4664 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 4665 Context.getPrintingPolicy()); 4666 } 4667 4668 DeclaresAnything = false; 4669 } 4670 } 4671 4672 // C11 6.7.2.1p2: 4673 // A struct-declaration that does not declare an anonymous structure or 4674 // anonymous union shall contain a struct-declarator-list. 4675 // 4676 // This rule also existed in C89 and C99; the grammar for struct-declaration 4677 // did not permit a struct-declaration without a struct-declarator-list. 4678 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 4679 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 4680 // Check for Microsoft C extension: anonymous struct/union member. 4681 // Handle 2 kinds of anonymous struct/union: 4682 // struct STRUCT; 4683 // union UNION; 4684 // and 4685 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 4686 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 4687 if ((Tag && Tag->getDeclName()) || 4688 DS.getTypeSpecType() == DeclSpec::TST_typename) { 4689 RecordDecl *Record = nullptr; 4690 if (Tag) 4691 Record = dyn_cast<RecordDecl>(Tag); 4692 else if (const RecordType *RT = 4693 DS.getRepAsType().get()->getAsStructureType()) 4694 Record = RT->getDecl(); 4695 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 4696 Record = UT->getDecl(); 4697 4698 if (Record && getLangOpts().MicrosoftExt) { 4699 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record) 4700 << Record->isUnion() << DS.getSourceRange(); 4701 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 4702 } 4703 4704 DeclaresAnything = false; 4705 } 4706 } 4707 4708 // Skip all the checks below if we have a type error. 4709 if (DS.getTypeSpecType() == DeclSpec::TST_error || 4710 (TagD && TagD->isInvalidDecl())) 4711 return TagD; 4712 4713 if (getLangOpts().CPlusPlus && 4714 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 4715 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 4716 if (Enum->enumerator_begin() == Enum->enumerator_end() && 4717 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 4718 DeclaresAnything = false; 4719 4720 if (!DS.isMissingDeclaratorOk()) { 4721 // Customize diagnostic for a typedef missing a name. 4722 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 4723 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name) 4724 << DS.getSourceRange(); 4725 else 4726 DeclaresAnything = false; 4727 } 4728 4729 if (DS.isModulePrivateSpecified() && 4730 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 4731 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 4732 << Tag->getTagKind() 4733 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 4734 4735 ActOnDocumentableDecl(TagD); 4736 4737 // C 6.7/2: 4738 // A declaration [...] shall declare at least a declarator [...], a tag, 4739 // or the members of an enumeration. 4740 // C++ [dcl.dcl]p3: 4741 // [If there are no declarators], and except for the declaration of an 4742 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 4743 // names into the program, or shall redeclare a name introduced by a 4744 // previous declaration. 4745 if (!DeclaresAnything) { 4746 // In C, we allow this as a (popular) extension / bug. Don't bother 4747 // producing further diagnostics for redundant qualifiers after this. 4748 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); 4749 return TagD; 4750 } 4751 4752 // C++ [dcl.stc]p1: 4753 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 4754 // init-declarator-list of the declaration shall not be empty. 4755 // C++ [dcl.fct.spec]p1: 4756 // If a cv-qualifier appears in a decl-specifier-seq, the 4757 // init-declarator-list of the declaration shall not be empty. 4758 // 4759 // Spurious qualifiers here appear to be valid in C. 4760 unsigned DiagID = diag::warn_standalone_specifier; 4761 if (getLangOpts().CPlusPlus) 4762 DiagID = diag::ext_standalone_specifier; 4763 4764 // Note that a linkage-specification sets a storage class, but 4765 // 'extern "C" struct foo;' is actually valid and not theoretically 4766 // useless. 4767 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 4768 if (SCS == DeclSpec::SCS_mutable) 4769 // Since mutable is not a viable storage class specifier in C, there is 4770 // no reason to treat it as an extension. Instead, diagnose as an error. 4771 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 4772 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 4773 Diag(DS.getStorageClassSpecLoc(), DiagID) 4774 << DeclSpec::getSpecifierName(SCS); 4775 } 4776 4777 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 4778 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 4779 << DeclSpec::getSpecifierName(TSCS); 4780 if (DS.getTypeQualifiers()) { 4781 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4782 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 4783 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4784 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 4785 // Restrict is covered above. 4786 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4787 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 4788 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4789 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 4790 } 4791 4792 // Warn about ignored type attributes, for example: 4793 // __attribute__((aligned)) struct A; 4794 // Attributes should be placed after tag to apply to type declaration. 4795 if (!DS.getAttributes().empty()) { 4796 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 4797 if (TypeSpecType == DeclSpec::TST_class || 4798 TypeSpecType == DeclSpec::TST_struct || 4799 TypeSpecType == DeclSpec::TST_interface || 4800 TypeSpecType == DeclSpec::TST_union || 4801 TypeSpecType == DeclSpec::TST_enum) { 4802 for (const ParsedAttr &AL : DS.getAttributes()) 4803 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored) 4804 << AL << GetDiagnosticTypeSpecifierID(TypeSpecType); 4805 } 4806 } 4807 4808 return TagD; 4809 } 4810 4811 /// We are trying to inject an anonymous member into the given scope; 4812 /// check if there's an existing declaration that can't be overloaded. 4813 /// 4814 /// \return true if this is a forbidden redeclaration 4815 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 4816 Scope *S, 4817 DeclContext *Owner, 4818 DeclarationName Name, 4819 SourceLocation NameLoc, 4820 bool IsUnion) { 4821 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 4822 Sema::ForVisibleRedeclaration); 4823 if (!SemaRef.LookupName(R, S)) return false; 4824 4825 // Pick a representative declaration. 4826 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 4827 assert(PrevDecl && "Expected a non-null Decl"); 4828 4829 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 4830 return false; 4831 4832 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 4833 << IsUnion << Name; 4834 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4835 4836 return true; 4837 } 4838 4839 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 4840 /// anonymous struct or union AnonRecord into the owning context Owner 4841 /// and scope S. This routine will be invoked just after we realize 4842 /// that an unnamed union or struct is actually an anonymous union or 4843 /// struct, e.g., 4844 /// 4845 /// @code 4846 /// union { 4847 /// int i; 4848 /// float f; 4849 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 4850 /// // f into the surrounding scope.x 4851 /// @endcode 4852 /// 4853 /// This routine is recursive, injecting the names of nested anonymous 4854 /// structs/unions into the owning context and scope as well. 4855 static bool 4856 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 4857 RecordDecl *AnonRecord, AccessSpecifier AS, 4858 SmallVectorImpl<NamedDecl *> &Chaining) { 4859 bool Invalid = false; 4860 4861 // Look every FieldDecl and IndirectFieldDecl with a name. 4862 for (auto *D : AnonRecord->decls()) { 4863 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 4864 cast<NamedDecl>(D)->getDeclName()) { 4865 ValueDecl *VD = cast<ValueDecl>(D); 4866 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 4867 VD->getLocation(), 4868 AnonRecord->isUnion())) { 4869 // C++ [class.union]p2: 4870 // The names of the members of an anonymous union shall be 4871 // distinct from the names of any other entity in the 4872 // scope in which the anonymous union is declared. 4873 Invalid = true; 4874 } else { 4875 // C++ [class.union]p2: 4876 // For the purpose of name lookup, after the anonymous union 4877 // definition, the members of the anonymous union are 4878 // considered to have been defined in the scope in which the 4879 // anonymous union is declared. 4880 unsigned OldChainingSize = Chaining.size(); 4881 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 4882 Chaining.append(IF->chain_begin(), IF->chain_end()); 4883 else 4884 Chaining.push_back(VD); 4885 4886 assert(Chaining.size() >= 2); 4887 NamedDecl **NamedChain = 4888 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 4889 for (unsigned i = 0; i < Chaining.size(); i++) 4890 NamedChain[i] = Chaining[i]; 4891 4892 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 4893 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 4894 VD->getType(), {NamedChain, Chaining.size()}); 4895 4896 for (const auto *Attr : VD->attrs()) 4897 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 4898 4899 IndirectField->setAccess(AS); 4900 IndirectField->setImplicit(); 4901 SemaRef.PushOnScopeChains(IndirectField, S); 4902 4903 // That includes picking up the appropriate access specifier. 4904 if (AS != AS_none) IndirectField->setAccess(AS); 4905 4906 Chaining.resize(OldChainingSize); 4907 } 4908 } 4909 } 4910 4911 return Invalid; 4912 } 4913 4914 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 4915 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 4916 /// illegal input values are mapped to SC_None. 4917 static StorageClass 4918 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 4919 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 4920 assert(StorageClassSpec != DeclSpec::SCS_typedef && 4921 "Parser allowed 'typedef' as storage class VarDecl."); 4922 switch (StorageClassSpec) { 4923 case DeclSpec::SCS_unspecified: return SC_None; 4924 case DeclSpec::SCS_extern: 4925 if (DS.isExternInLinkageSpec()) 4926 return SC_None; 4927 return SC_Extern; 4928 case DeclSpec::SCS_static: return SC_Static; 4929 case DeclSpec::SCS_auto: return SC_Auto; 4930 case DeclSpec::SCS_register: return SC_Register; 4931 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 4932 // Illegal SCSs map to None: error reporting is up to the caller. 4933 case DeclSpec::SCS_mutable: // Fall through. 4934 case DeclSpec::SCS_typedef: return SC_None; 4935 } 4936 llvm_unreachable("unknown storage class specifier"); 4937 } 4938 4939 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 4940 assert(Record->hasInClassInitializer()); 4941 4942 for (const auto *I : Record->decls()) { 4943 const auto *FD = dyn_cast<FieldDecl>(I); 4944 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 4945 FD = IFD->getAnonField(); 4946 if (FD && FD->hasInClassInitializer()) 4947 return FD->getLocation(); 4948 } 4949 4950 llvm_unreachable("couldn't find in-class initializer"); 4951 } 4952 4953 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4954 SourceLocation DefaultInitLoc) { 4955 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4956 return; 4957 4958 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 4959 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 4960 } 4961 4962 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4963 CXXRecordDecl *AnonUnion) { 4964 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4965 return; 4966 4967 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 4968 } 4969 4970 /// BuildAnonymousStructOrUnion - Handle the declaration of an 4971 /// anonymous structure or union. Anonymous unions are a C++ feature 4972 /// (C++ [class.union]) and a C11 feature; anonymous structures 4973 /// are a C11 feature and GNU C++ extension. 4974 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 4975 AccessSpecifier AS, 4976 RecordDecl *Record, 4977 const PrintingPolicy &Policy) { 4978 DeclContext *Owner = Record->getDeclContext(); 4979 4980 // Diagnose whether this anonymous struct/union is an extension. 4981 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 4982 Diag(Record->getLocation(), diag::ext_anonymous_union); 4983 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 4984 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 4985 else if (!Record->isUnion() && !getLangOpts().C11) 4986 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 4987 4988 // C and C++ require different kinds of checks for anonymous 4989 // structs/unions. 4990 bool Invalid = false; 4991 if (getLangOpts().CPlusPlus) { 4992 const char *PrevSpec = nullptr; 4993 if (Record->isUnion()) { 4994 // C++ [class.union]p6: 4995 // C++17 [class.union.anon]p2: 4996 // Anonymous unions declared in a named namespace or in the 4997 // global namespace shall be declared static. 4998 unsigned DiagID; 4999 DeclContext *OwnerScope = Owner->getRedeclContext(); 5000 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 5001 (OwnerScope->isTranslationUnit() || 5002 (OwnerScope->isNamespace() && 5003 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) { 5004 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 5005 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 5006 5007 // Recover by adding 'static'. 5008 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 5009 PrevSpec, DiagID, Policy); 5010 } 5011 // C++ [class.union]p6: 5012 // A storage class is not allowed in a declaration of an 5013 // anonymous union in a class scope. 5014 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 5015 isa<RecordDecl>(Owner)) { 5016 Diag(DS.getStorageClassSpecLoc(), 5017 diag::err_anonymous_union_with_storage_spec) 5018 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 5019 5020 // Recover by removing the storage specifier. 5021 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 5022 SourceLocation(), 5023 PrevSpec, DiagID, Context.getPrintingPolicy()); 5024 } 5025 } 5026 5027 // Ignore const/volatile/restrict qualifiers. 5028 if (DS.getTypeQualifiers()) { 5029 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 5030 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 5031 << Record->isUnion() << "const" 5032 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 5033 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 5034 Diag(DS.getVolatileSpecLoc(), 5035 diag::ext_anonymous_struct_union_qualified) 5036 << Record->isUnion() << "volatile" 5037 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 5038 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 5039 Diag(DS.getRestrictSpecLoc(), 5040 diag::ext_anonymous_struct_union_qualified) 5041 << Record->isUnion() << "restrict" 5042 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 5043 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 5044 Diag(DS.getAtomicSpecLoc(), 5045 diag::ext_anonymous_struct_union_qualified) 5046 << Record->isUnion() << "_Atomic" 5047 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 5048 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 5049 Diag(DS.getUnalignedSpecLoc(), 5050 diag::ext_anonymous_struct_union_qualified) 5051 << Record->isUnion() << "__unaligned" 5052 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 5053 5054 DS.ClearTypeQualifiers(); 5055 } 5056 5057 // C++ [class.union]p2: 5058 // The member-specification of an anonymous union shall only 5059 // define non-static data members. [Note: nested types and 5060 // functions cannot be declared within an anonymous union. ] 5061 for (auto *Mem : Record->decls()) { 5062 // Ignore invalid declarations; we already diagnosed them. 5063 if (Mem->isInvalidDecl()) 5064 continue; 5065 5066 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 5067 // C++ [class.union]p3: 5068 // An anonymous union shall not have private or protected 5069 // members (clause 11). 5070 assert(FD->getAccess() != AS_none); 5071 if (FD->getAccess() != AS_public) { 5072 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 5073 << Record->isUnion() << (FD->getAccess() == AS_protected); 5074 Invalid = true; 5075 } 5076 5077 // C++ [class.union]p1 5078 // An object of a class with a non-trivial constructor, a non-trivial 5079 // copy constructor, a non-trivial destructor, or a non-trivial copy 5080 // assignment operator cannot be a member of a union, nor can an 5081 // array of such objects. 5082 if (CheckNontrivialField(FD)) 5083 Invalid = true; 5084 } else if (Mem->isImplicit()) { 5085 // Any implicit members are fine. 5086 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 5087 // This is a type that showed up in an 5088 // elaborated-type-specifier inside the anonymous struct or 5089 // union, but which actually declares a type outside of the 5090 // anonymous struct or union. It's okay. 5091 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 5092 if (!MemRecord->isAnonymousStructOrUnion() && 5093 MemRecord->getDeclName()) { 5094 // Visual C++ allows type definition in anonymous struct or union. 5095 if (getLangOpts().MicrosoftExt) 5096 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 5097 << Record->isUnion(); 5098 else { 5099 // This is a nested type declaration. 5100 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 5101 << Record->isUnion(); 5102 Invalid = true; 5103 } 5104 } else { 5105 // This is an anonymous type definition within another anonymous type. 5106 // This is a popular extension, provided by Plan9, MSVC and GCC, but 5107 // not part of standard C++. 5108 Diag(MemRecord->getLocation(), 5109 diag::ext_anonymous_record_with_anonymous_type) 5110 << Record->isUnion(); 5111 } 5112 } else if (isa<AccessSpecDecl>(Mem)) { 5113 // Any access specifier is fine. 5114 } else if (isa<StaticAssertDecl>(Mem)) { 5115 // In C++1z, static_assert declarations are also fine. 5116 } else { 5117 // We have something that isn't a non-static data 5118 // member. Complain about it. 5119 unsigned DK = diag::err_anonymous_record_bad_member; 5120 if (isa<TypeDecl>(Mem)) 5121 DK = diag::err_anonymous_record_with_type; 5122 else if (isa<FunctionDecl>(Mem)) 5123 DK = diag::err_anonymous_record_with_function; 5124 else if (isa<VarDecl>(Mem)) 5125 DK = diag::err_anonymous_record_with_static; 5126 5127 // Visual C++ allows type definition in anonymous struct or union. 5128 if (getLangOpts().MicrosoftExt && 5129 DK == diag::err_anonymous_record_with_type) 5130 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 5131 << Record->isUnion(); 5132 else { 5133 Diag(Mem->getLocation(), DK) << Record->isUnion(); 5134 Invalid = true; 5135 } 5136 } 5137 } 5138 5139 // C++11 [class.union]p8 (DR1460): 5140 // At most one variant member of a union may have a 5141 // brace-or-equal-initializer. 5142 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 5143 Owner->isRecord()) 5144 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 5145 cast<CXXRecordDecl>(Record)); 5146 } 5147 5148 if (!Record->isUnion() && !Owner->isRecord()) { 5149 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 5150 << getLangOpts().CPlusPlus; 5151 Invalid = true; 5152 } 5153 5154 // C++ [dcl.dcl]p3: 5155 // [If there are no declarators], and except for the declaration of an 5156 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 5157 // names into the program 5158 // C++ [class.mem]p2: 5159 // each such member-declaration shall either declare at least one member 5160 // name of the class or declare at least one unnamed bit-field 5161 // 5162 // For C this is an error even for a named struct, and is diagnosed elsewhere. 5163 if (getLangOpts().CPlusPlus && Record->field_empty()) 5164 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); 5165 5166 // Mock up a declarator. 5167 Declarator Dc(DS, DeclaratorContext::MemberContext); 5168 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5169 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 5170 5171 // Create a declaration for this anonymous struct/union. 5172 NamedDecl *Anon = nullptr; 5173 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 5174 Anon = FieldDecl::Create( 5175 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(), 5176 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo, 5177 /*BitWidth=*/nullptr, /*Mutable=*/false, 5178 /*InitStyle=*/ICIS_NoInit); 5179 Anon->setAccess(AS); 5180 ProcessDeclAttributes(S, Anon, Dc); 5181 5182 if (getLangOpts().CPlusPlus) 5183 FieldCollector->Add(cast<FieldDecl>(Anon)); 5184 } else { 5185 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 5186 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 5187 if (SCSpec == DeclSpec::SCS_mutable) { 5188 // mutable can only appear on non-static class members, so it's always 5189 // an error here 5190 Diag(Record->getLocation(), diag::err_mutable_nonmember); 5191 Invalid = true; 5192 SC = SC_None; 5193 } 5194 5195 assert(DS.getAttributes().empty() && "No attribute expected"); 5196 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(), 5197 Record->getLocation(), /*IdentifierInfo=*/nullptr, 5198 Context.getTypeDeclType(Record), TInfo, SC); 5199 5200 // Default-initialize the implicit variable. This initialization will be 5201 // trivial in almost all cases, except if a union member has an in-class 5202 // initializer: 5203 // union { int n = 0; }; 5204 ActOnUninitializedDecl(Anon); 5205 } 5206 Anon->setImplicit(); 5207 5208 // Mark this as an anonymous struct/union type. 5209 Record->setAnonymousStructOrUnion(true); 5210 5211 // Add the anonymous struct/union object to the current 5212 // context. We'll be referencing this object when we refer to one of 5213 // its members. 5214 Owner->addDecl(Anon); 5215 5216 // Inject the members of the anonymous struct/union into the owning 5217 // context and into the identifier resolver chain for name lookup 5218 // purposes. 5219 SmallVector<NamedDecl*, 2> Chain; 5220 Chain.push_back(Anon); 5221 5222 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 5223 Invalid = true; 5224 5225 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 5226 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 5227 MangleNumberingContext *MCtx; 5228 Decl *ManglingContextDecl; 5229 std::tie(MCtx, ManglingContextDecl) = 5230 getCurrentMangleNumberContext(NewVD->getDeclContext()); 5231 if (MCtx) { 5232 Context.setManglingNumber( 5233 NewVD, MCtx->getManglingNumber( 5234 NewVD, getMSManglingNumber(getLangOpts(), S))); 5235 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 5236 } 5237 } 5238 } 5239 5240 if (Invalid) 5241 Anon->setInvalidDecl(); 5242 5243 return Anon; 5244 } 5245 5246 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 5247 /// Microsoft C anonymous structure. 5248 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 5249 /// Example: 5250 /// 5251 /// struct A { int a; }; 5252 /// struct B { struct A; int b; }; 5253 /// 5254 /// void foo() { 5255 /// B var; 5256 /// var.a = 3; 5257 /// } 5258 /// 5259 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 5260 RecordDecl *Record) { 5261 assert(Record && "expected a record!"); 5262 5263 // Mock up a declarator. 5264 Declarator Dc(DS, DeclaratorContext::TypeNameContext); 5265 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5266 assert(TInfo && "couldn't build declarator info for anonymous struct"); 5267 5268 auto *ParentDecl = cast<RecordDecl>(CurContext); 5269 QualType RecTy = Context.getTypeDeclType(Record); 5270 5271 // Create a declaration for this anonymous struct. 5272 NamedDecl *Anon = 5273 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(), 5274 /*IdentifierInfo=*/nullptr, RecTy, TInfo, 5275 /*BitWidth=*/nullptr, /*Mutable=*/false, 5276 /*InitStyle=*/ICIS_NoInit); 5277 Anon->setImplicit(); 5278 5279 // Add the anonymous struct object to the current context. 5280 CurContext->addDecl(Anon); 5281 5282 // Inject the members of the anonymous struct into the current 5283 // context and into the identifier resolver chain for name lookup 5284 // purposes. 5285 SmallVector<NamedDecl*, 2> Chain; 5286 Chain.push_back(Anon); 5287 5288 RecordDecl *RecordDef = Record->getDefinition(); 5289 if (RequireCompleteSizedType(Anon->getLocation(), RecTy, 5290 diag::err_field_incomplete_or_sizeless) || 5291 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 5292 AS_none, Chain)) { 5293 Anon->setInvalidDecl(); 5294 ParentDecl->setInvalidDecl(); 5295 } 5296 5297 return Anon; 5298 } 5299 5300 /// GetNameForDeclarator - Determine the full declaration name for the 5301 /// given Declarator. 5302 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 5303 return GetNameFromUnqualifiedId(D.getName()); 5304 } 5305 5306 /// Retrieves the declaration name from a parsed unqualified-id. 5307 DeclarationNameInfo 5308 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 5309 DeclarationNameInfo NameInfo; 5310 NameInfo.setLoc(Name.StartLocation); 5311 5312 switch (Name.getKind()) { 5313 5314 case UnqualifiedIdKind::IK_ImplicitSelfParam: 5315 case UnqualifiedIdKind::IK_Identifier: 5316 NameInfo.setName(Name.Identifier); 5317 return NameInfo; 5318 5319 case UnqualifiedIdKind::IK_DeductionGuideName: { 5320 // C++ [temp.deduct.guide]p3: 5321 // The simple-template-id shall name a class template specialization. 5322 // The template-name shall be the same identifier as the template-name 5323 // of the simple-template-id. 5324 // These together intend to imply that the template-name shall name a 5325 // class template. 5326 // FIXME: template<typename T> struct X {}; 5327 // template<typename T> using Y = X<T>; 5328 // Y(int) -> Y<int>; 5329 // satisfies these rules but does not name a class template. 5330 TemplateName TN = Name.TemplateName.get().get(); 5331 auto *Template = TN.getAsTemplateDecl(); 5332 if (!Template || !isa<ClassTemplateDecl>(Template)) { 5333 Diag(Name.StartLocation, 5334 diag::err_deduction_guide_name_not_class_template) 5335 << (int)getTemplateNameKindForDiagnostics(TN) << TN; 5336 if (Template) 5337 Diag(Template->getLocation(), diag::note_template_decl_here); 5338 return DeclarationNameInfo(); 5339 } 5340 5341 NameInfo.setName( 5342 Context.DeclarationNames.getCXXDeductionGuideName(Template)); 5343 return NameInfo; 5344 } 5345 5346 case UnqualifiedIdKind::IK_OperatorFunctionId: 5347 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 5348 Name.OperatorFunctionId.Operator)); 5349 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 5350 = Name.OperatorFunctionId.SymbolLocations[0]; 5351 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 5352 = Name.EndLocation.getRawEncoding(); 5353 return NameInfo; 5354 5355 case UnqualifiedIdKind::IK_LiteralOperatorId: 5356 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 5357 Name.Identifier)); 5358 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 5359 return NameInfo; 5360 5361 case UnqualifiedIdKind::IK_ConversionFunctionId: { 5362 TypeSourceInfo *TInfo; 5363 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 5364 if (Ty.isNull()) 5365 return DeclarationNameInfo(); 5366 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 5367 Context.getCanonicalType(Ty))); 5368 NameInfo.setNamedTypeInfo(TInfo); 5369 return NameInfo; 5370 } 5371 5372 case UnqualifiedIdKind::IK_ConstructorName: { 5373 TypeSourceInfo *TInfo; 5374 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 5375 if (Ty.isNull()) 5376 return DeclarationNameInfo(); 5377 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5378 Context.getCanonicalType(Ty))); 5379 NameInfo.setNamedTypeInfo(TInfo); 5380 return NameInfo; 5381 } 5382 5383 case UnqualifiedIdKind::IK_ConstructorTemplateId: { 5384 // In well-formed code, we can only have a constructor 5385 // template-id that refers to the current context, so go there 5386 // to find the actual type being constructed. 5387 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 5388 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 5389 return DeclarationNameInfo(); 5390 5391 // Determine the type of the class being constructed. 5392 QualType CurClassType = Context.getTypeDeclType(CurClass); 5393 5394 // FIXME: Check two things: that the template-id names the same type as 5395 // CurClassType, and that the template-id does not occur when the name 5396 // was qualified. 5397 5398 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5399 Context.getCanonicalType(CurClassType))); 5400 // FIXME: should we retrieve TypeSourceInfo? 5401 NameInfo.setNamedTypeInfo(nullptr); 5402 return NameInfo; 5403 } 5404 5405 case UnqualifiedIdKind::IK_DestructorName: { 5406 TypeSourceInfo *TInfo; 5407 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 5408 if (Ty.isNull()) 5409 return DeclarationNameInfo(); 5410 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 5411 Context.getCanonicalType(Ty))); 5412 NameInfo.setNamedTypeInfo(TInfo); 5413 return NameInfo; 5414 } 5415 5416 case UnqualifiedIdKind::IK_TemplateId: { 5417 TemplateName TName = Name.TemplateId->Template.get(); 5418 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 5419 return Context.getNameForTemplate(TName, TNameLoc); 5420 } 5421 5422 } // switch (Name.getKind()) 5423 5424 llvm_unreachable("Unknown name kind"); 5425 } 5426 5427 static QualType getCoreType(QualType Ty) { 5428 do { 5429 if (Ty->isPointerType() || Ty->isReferenceType()) 5430 Ty = Ty->getPointeeType(); 5431 else if (Ty->isArrayType()) 5432 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 5433 else 5434 return Ty.withoutLocalFastQualifiers(); 5435 } while (true); 5436 } 5437 5438 /// hasSimilarParameters - Determine whether the C++ functions Declaration 5439 /// and Definition have "nearly" matching parameters. This heuristic is 5440 /// used to improve diagnostics in the case where an out-of-line function 5441 /// definition doesn't match any declaration within the class or namespace. 5442 /// Also sets Params to the list of indices to the parameters that differ 5443 /// between the declaration and the definition. If hasSimilarParameters 5444 /// returns true and Params is empty, then all of the parameters match. 5445 static bool hasSimilarParameters(ASTContext &Context, 5446 FunctionDecl *Declaration, 5447 FunctionDecl *Definition, 5448 SmallVectorImpl<unsigned> &Params) { 5449 Params.clear(); 5450 if (Declaration->param_size() != Definition->param_size()) 5451 return false; 5452 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 5453 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 5454 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 5455 5456 // The parameter types are identical 5457 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy)) 5458 continue; 5459 5460 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 5461 QualType DefParamBaseTy = getCoreType(DefParamTy); 5462 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 5463 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 5464 5465 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 5466 (DeclTyName && DeclTyName == DefTyName)) 5467 Params.push_back(Idx); 5468 else // The two parameters aren't even close 5469 return false; 5470 } 5471 5472 return true; 5473 } 5474 5475 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 5476 /// declarator needs to be rebuilt in the current instantiation. 5477 /// Any bits of declarator which appear before the name are valid for 5478 /// consideration here. That's specifically the type in the decl spec 5479 /// and the base type in any member-pointer chunks. 5480 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 5481 DeclarationName Name) { 5482 // The types we specifically need to rebuild are: 5483 // - typenames, typeofs, and decltypes 5484 // - types which will become injected class names 5485 // Of course, we also need to rebuild any type referencing such a 5486 // type. It's safest to just say "dependent", but we call out a 5487 // few cases here. 5488 5489 DeclSpec &DS = D.getMutableDeclSpec(); 5490 switch (DS.getTypeSpecType()) { 5491 case DeclSpec::TST_typename: 5492 case DeclSpec::TST_typeofType: 5493 case DeclSpec::TST_underlyingType: 5494 case DeclSpec::TST_atomic: { 5495 // Grab the type from the parser. 5496 TypeSourceInfo *TSI = nullptr; 5497 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 5498 if (T.isNull() || !T->isDependentType()) break; 5499 5500 // Make sure there's a type source info. This isn't really much 5501 // of a waste; most dependent types should have type source info 5502 // attached already. 5503 if (!TSI) 5504 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 5505 5506 // Rebuild the type in the current instantiation. 5507 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 5508 if (!TSI) return true; 5509 5510 // Store the new type back in the decl spec. 5511 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 5512 DS.UpdateTypeRep(LocType); 5513 break; 5514 } 5515 5516 case DeclSpec::TST_decltype: 5517 case DeclSpec::TST_typeofExpr: { 5518 Expr *E = DS.getRepAsExpr(); 5519 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 5520 if (Result.isInvalid()) return true; 5521 DS.UpdateExprRep(Result.get()); 5522 break; 5523 } 5524 5525 default: 5526 // Nothing to do for these decl specs. 5527 break; 5528 } 5529 5530 // It doesn't matter what order we do this in. 5531 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 5532 DeclaratorChunk &Chunk = D.getTypeObject(I); 5533 5534 // The only type information in the declarator which can come 5535 // before the declaration name is the base type of a member 5536 // pointer. 5537 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 5538 continue; 5539 5540 // Rebuild the scope specifier in-place. 5541 CXXScopeSpec &SS = Chunk.Mem.Scope(); 5542 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 5543 return true; 5544 } 5545 5546 return false; 5547 } 5548 5549 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 5550 D.setFunctionDefinitionKind(FDK_Declaration); 5551 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 5552 5553 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 5554 Dcl && Dcl->getDeclContext()->isFileContext()) 5555 Dcl->setTopLevelDeclInObjCContainer(); 5556 5557 if (getLangOpts().OpenCL) 5558 setCurrentOpenCLExtensionForDecl(Dcl); 5559 5560 return Dcl; 5561 } 5562 5563 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 5564 /// If T is the name of a class, then each of the following shall have a 5565 /// name different from T: 5566 /// - every static data member of class T; 5567 /// - every member function of class T 5568 /// - every member of class T that is itself a type; 5569 /// \returns true if the declaration name violates these rules. 5570 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 5571 DeclarationNameInfo NameInfo) { 5572 DeclarationName Name = NameInfo.getName(); 5573 5574 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 5575 while (Record && Record->isAnonymousStructOrUnion()) 5576 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 5577 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 5578 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 5579 return true; 5580 } 5581 5582 return false; 5583 } 5584 5585 /// Diagnose a declaration whose declarator-id has the given 5586 /// nested-name-specifier. 5587 /// 5588 /// \param SS The nested-name-specifier of the declarator-id. 5589 /// 5590 /// \param DC The declaration context to which the nested-name-specifier 5591 /// resolves. 5592 /// 5593 /// \param Name The name of the entity being declared. 5594 /// 5595 /// \param Loc The location of the name of the entity being declared. 5596 /// 5597 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus 5598 /// we're declaring an explicit / partial specialization / instantiation. 5599 /// 5600 /// \returns true if we cannot safely recover from this error, false otherwise. 5601 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 5602 DeclarationName Name, 5603 SourceLocation Loc, bool IsTemplateId) { 5604 DeclContext *Cur = CurContext; 5605 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 5606 Cur = Cur->getParent(); 5607 5608 // If the user provided a superfluous scope specifier that refers back to the 5609 // class in which the entity is already declared, diagnose and ignore it. 5610 // 5611 // class X { 5612 // void X::f(); 5613 // }; 5614 // 5615 // Note, it was once ill-formed to give redundant qualification in all 5616 // contexts, but that rule was removed by DR482. 5617 if (Cur->Equals(DC)) { 5618 if (Cur->isRecord()) { 5619 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 5620 : diag::err_member_extra_qualification) 5621 << Name << FixItHint::CreateRemoval(SS.getRange()); 5622 SS.clear(); 5623 } else { 5624 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 5625 } 5626 return false; 5627 } 5628 5629 // Check whether the qualifying scope encloses the scope of the original 5630 // declaration. For a template-id, we perform the checks in 5631 // CheckTemplateSpecializationScope. 5632 if (!Cur->Encloses(DC) && !IsTemplateId) { 5633 if (Cur->isRecord()) 5634 Diag(Loc, diag::err_member_qualification) 5635 << Name << SS.getRange(); 5636 else if (isa<TranslationUnitDecl>(DC)) 5637 Diag(Loc, diag::err_invalid_declarator_global_scope) 5638 << Name << SS.getRange(); 5639 else if (isa<FunctionDecl>(Cur)) 5640 Diag(Loc, diag::err_invalid_declarator_in_function) 5641 << Name << SS.getRange(); 5642 else if (isa<BlockDecl>(Cur)) 5643 Diag(Loc, diag::err_invalid_declarator_in_block) 5644 << Name << SS.getRange(); 5645 else 5646 Diag(Loc, diag::err_invalid_declarator_scope) 5647 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 5648 5649 return true; 5650 } 5651 5652 if (Cur->isRecord()) { 5653 // Cannot qualify members within a class. 5654 Diag(Loc, diag::err_member_qualification) 5655 << Name << SS.getRange(); 5656 SS.clear(); 5657 5658 // C++ constructors and destructors with incorrect scopes can break 5659 // our AST invariants by having the wrong underlying types. If 5660 // that's the case, then drop this declaration entirely. 5661 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 5662 Name.getNameKind() == DeclarationName::CXXDestructorName) && 5663 !Context.hasSameType(Name.getCXXNameType(), 5664 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 5665 return true; 5666 5667 return false; 5668 } 5669 5670 // C++11 [dcl.meaning]p1: 5671 // [...] "The nested-name-specifier of the qualified declarator-id shall 5672 // not begin with a decltype-specifer" 5673 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 5674 while (SpecLoc.getPrefix()) 5675 SpecLoc = SpecLoc.getPrefix(); 5676 if (dyn_cast_or_null<DecltypeType>( 5677 SpecLoc.getNestedNameSpecifier()->getAsType())) 5678 Diag(Loc, diag::err_decltype_in_declarator) 5679 << SpecLoc.getTypeLoc().getSourceRange(); 5680 5681 return false; 5682 } 5683 5684 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 5685 MultiTemplateParamsArg TemplateParamLists) { 5686 // TODO: consider using NameInfo for diagnostic. 5687 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5688 DeclarationName Name = NameInfo.getName(); 5689 5690 // All of these full declarators require an identifier. If it doesn't have 5691 // one, the ParsedFreeStandingDeclSpec action should be used. 5692 if (D.isDecompositionDeclarator()) { 5693 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 5694 } else if (!Name) { 5695 if (!D.isInvalidType()) // Reject this if we think it is valid. 5696 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident) 5697 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 5698 return nullptr; 5699 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 5700 return nullptr; 5701 5702 // The scope passed in may not be a decl scope. Zip up the scope tree until 5703 // we find one that is. 5704 while ((S->getFlags() & Scope::DeclScope) == 0 || 5705 (S->getFlags() & Scope::TemplateParamScope) != 0) 5706 S = S->getParent(); 5707 5708 DeclContext *DC = CurContext; 5709 if (D.getCXXScopeSpec().isInvalid()) 5710 D.setInvalidType(); 5711 else if (D.getCXXScopeSpec().isSet()) { 5712 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 5713 UPPC_DeclarationQualifier)) 5714 return nullptr; 5715 5716 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 5717 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 5718 if (!DC || isa<EnumDecl>(DC)) { 5719 // If we could not compute the declaration context, it's because the 5720 // declaration context is dependent but does not refer to a class, 5721 // class template, or class template partial specialization. Complain 5722 // and return early, to avoid the coming semantic disaster. 5723 Diag(D.getIdentifierLoc(), 5724 diag::err_template_qualified_declarator_no_match) 5725 << D.getCXXScopeSpec().getScopeRep() 5726 << D.getCXXScopeSpec().getRange(); 5727 return nullptr; 5728 } 5729 bool IsDependentContext = DC->isDependentContext(); 5730 5731 if (!IsDependentContext && 5732 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 5733 return nullptr; 5734 5735 // If a class is incomplete, do not parse entities inside it. 5736 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 5737 Diag(D.getIdentifierLoc(), 5738 diag::err_member_def_undefined_record) 5739 << Name << DC << D.getCXXScopeSpec().getRange(); 5740 return nullptr; 5741 } 5742 if (!D.getDeclSpec().isFriendSpecified()) { 5743 if (diagnoseQualifiedDeclaration( 5744 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(), 5745 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) { 5746 if (DC->isRecord()) 5747 return nullptr; 5748 5749 D.setInvalidType(); 5750 } 5751 } 5752 5753 // Check whether we need to rebuild the type of the given 5754 // declaration in the current instantiation. 5755 if (EnteringContext && IsDependentContext && 5756 TemplateParamLists.size() != 0) { 5757 ContextRAII SavedContext(*this, DC); 5758 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 5759 D.setInvalidType(); 5760 } 5761 } 5762 5763 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5764 QualType R = TInfo->getType(); 5765 5766 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 5767 UPPC_DeclarationType)) 5768 D.setInvalidType(); 5769 5770 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5771 forRedeclarationInCurContext()); 5772 5773 // See if this is a redefinition of a variable in the same scope. 5774 if (!D.getCXXScopeSpec().isSet()) { 5775 bool IsLinkageLookup = false; 5776 bool CreateBuiltins = false; 5777 5778 // If the declaration we're planning to build will be a function 5779 // or object with linkage, then look for another declaration with 5780 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 5781 // 5782 // If the declaration we're planning to build will be declared with 5783 // external linkage in the translation unit, create any builtin with 5784 // the same name. 5785 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5786 /* Do nothing*/; 5787 else if (CurContext->isFunctionOrMethod() && 5788 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 5789 R->isFunctionType())) { 5790 IsLinkageLookup = true; 5791 CreateBuiltins = 5792 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 5793 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 5794 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 5795 CreateBuiltins = true; 5796 5797 if (IsLinkageLookup) { 5798 Previous.clear(LookupRedeclarationWithLinkage); 5799 Previous.setRedeclarationKind(ForExternalRedeclaration); 5800 } 5801 5802 LookupName(Previous, S, CreateBuiltins); 5803 } else { // Something like "int foo::x;" 5804 LookupQualifiedName(Previous, DC); 5805 5806 // C++ [dcl.meaning]p1: 5807 // When the declarator-id is qualified, the declaration shall refer to a 5808 // previously declared member of the class or namespace to which the 5809 // qualifier refers (or, in the case of a namespace, of an element of the 5810 // inline namespace set of that namespace (7.3.1)) or to a specialization 5811 // thereof; [...] 5812 // 5813 // Note that we already checked the context above, and that we do not have 5814 // enough information to make sure that Previous contains the declaration 5815 // we want to match. For example, given: 5816 // 5817 // class X { 5818 // void f(); 5819 // void f(float); 5820 // }; 5821 // 5822 // void X::f(int) { } // ill-formed 5823 // 5824 // In this case, Previous will point to the overload set 5825 // containing the two f's declared in X, but neither of them 5826 // matches. 5827 5828 // C++ [dcl.meaning]p1: 5829 // [...] the member shall not merely have been introduced by a 5830 // using-declaration in the scope of the class or namespace nominated by 5831 // the nested-name-specifier of the declarator-id. 5832 RemoveUsingDecls(Previous); 5833 } 5834 5835 if (Previous.isSingleResult() && 5836 Previous.getFoundDecl()->isTemplateParameter()) { 5837 // Maybe we will complain about the shadowed template parameter. 5838 if (!D.isInvalidType()) 5839 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 5840 Previous.getFoundDecl()); 5841 5842 // Just pretend that we didn't see the previous declaration. 5843 Previous.clear(); 5844 } 5845 5846 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 5847 // Forget that the previous declaration is the injected-class-name. 5848 Previous.clear(); 5849 5850 // In C++, the previous declaration we find might be a tag type 5851 // (class or enum). In this case, the new declaration will hide the 5852 // tag type. Note that this applies to functions, function templates, and 5853 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. 5854 if (Previous.isSingleTagDecl() && 5855 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 5856 (TemplateParamLists.size() == 0 || R->isFunctionType())) 5857 Previous.clear(); 5858 5859 // Check that there are no default arguments other than in the parameters 5860 // of a function declaration (C++ only). 5861 if (getLangOpts().CPlusPlus) 5862 CheckExtraCXXDefaultArguments(D); 5863 5864 NamedDecl *New; 5865 5866 bool AddToScope = true; 5867 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 5868 if (TemplateParamLists.size()) { 5869 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 5870 return nullptr; 5871 } 5872 5873 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 5874 } else if (R->isFunctionType()) { 5875 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 5876 TemplateParamLists, 5877 AddToScope); 5878 } else { 5879 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 5880 AddToScope); 5881 } 5882 5883 if (!New) 5884 return nullptr; 5885 5886 // If this has an identifier and is not a function template specialization, 5887 // add it to the scope stack. 5888 if (New->getDeclName() && AddToScope) 5889 PushOnScopeChains(New, S); 5890 5891 if (isInOpenMPDeclareTargetContext()) 5892 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 5893 5894 return New; 5895 } 5896 5897 /// Helper method to turn variable array types into constant array 5898 /// types in certain situations which would otherwise be errors (for 5899 /// GCC compatibility). 5900 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 5901 ASTContext &Context, 5902 bool &SizeIsNegative, 5903 llvm::APSInt &Oversized) { 5904 // This method tries to turn a variable array into a constant 5905 // array even when the size isn't an ICE. This is necessary 5906 // for compatibility with code that depends on gcc's buggy 5907 // constant expression folding, like struct {char x[(int)(char*)2];} 5908 SizeIsNegative = false; 5909 Oversized = 0; 5910 5911 if (T->isDependentType()) 5912 return QualType(); 5913 5914 QualifierCollector Qs; 5915 const Type *Ty = Qs.strip(T); 5916 5917 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 5918 QualType Pointee = PTy->getPointeeType(); 5919 QualType FixedType = 5920 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 5921 Oversized); 5922 if (FixedType.isNull()) return FixedType; 5923 FixedType = Context.getPointerType(FixedType); 5924 return Qs.apply(Context, FixedType); 5925 } 5926 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 5927 QualType Inner = PTy->getInnerType(); 5928 QualType FixedType = 5929 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 5930 Oversized); 5931 if (FixedType.isNull()) return FixedType; 5932 FixedType = Context.getParenType(FixedType); 5933 return Qs.apply(Context, FixedType); 5934 } 5935 5936 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 5937 if (!VLATy) 5938 return QualType(); 5939 // FIXME: We should probably handle this case 5940 if (VLATy->getElementType()->isVariablyModifiedType()) 5941 return QualType(); 5942 5943 Expr::EvalResult Result; 5944 if (!VLATy->getSizeExpr() || 5945 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context)) 5946 return QualType(); 5947 5948 llvm::APSInt Res = Result.Val.getInt(); 5949 5950 // Check whether the array size is negative. 5951 if (Res.isSigned() && Res.isNegative()) { 5952 SizeIsNegative = true; 5953 return QualType(); 5954 } 5955 5956 // Check whether the array is too large to be addressed. 5957 unsigned ActiveSizeBits 5958 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 5959 Res); 5960 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 5961 Oversized = Res; 5962 return QualType(); 5963 } 5964 5965 return Context.getConstantArrayType( 5966 VLATy->getElementType(), Res, VLATy->getSizeExpr(), ArrayType::Normal, 0); 5967 } 5968 5969 static void 5970 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 5971 SrcTL = SrcTL.getUnqualifiedLoc(); 5972 DstTL = DstTL.getUnqualifiedLoc(); 5973 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 5974 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 5975 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 5976 DstPTL.getPointeeLoc()); 5977 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 5978 return; 5979 } 5980 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 5981 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 5982 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 5983 DstPTL.getInnerLoc()); 5984 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 5985 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 5986 return; 5987 } 5988 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 5989 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 5990 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 5991 TypeLoc DstElemTL = DstATL.getElementLoc(); 5992 DstElemTL.initializeFullCopy(SrcElemTL); 5993 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 5994 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 5995 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 5996 } 5997 5998 /// Helper method to turn variable array types into constant array 5999 /// types in certain situations which would otherwise be errors (for 6000 /// GCC compatibility). 6001 static TypeSourceInfo* 6002 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 6003 ASTContext &Context, 6004 bool &SizeIsNegative, 6005 llvm::APSInt &Oversized) { 6006 QualType FixedTy 6007 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 6008 SizeIsNegative, Oversized); 6009 if (FixedTy.isNull()) 6010 return nullptr; 6011 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 6012 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 6013 FixedTInfo->getTypeLoc()); 6014 return FixedTInfo; 6015 } 6016 6017 /// Register the given locally-scoped extern "C" declaration so 6018 /// that it can be found later for redeclarations. We include any extern "C" 6019 /// declaration that is not visible in the translation unit here, not just 6020 /// function-scope declarations. 6021 void 6022 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 6023 if (!getLangOpts().CPlusPlus && 6024 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 6025 // Don't need to track declarations in the TU in C. 6026 return; 6027 6028 // Note that we have a locally-scoped external with this name. 6029 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 6030 } 6031 6032 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 6033 // FIXME: We can have multiple results via __attribute__((overloadable)). 6034 auto Result = Context.getExternCContextDecl()->lookup(Name); 6035 return Result.empty() ? nullptr : *Result.begin(); 6036 } 6037 6038 /// Diagnose function specifiers on a declaration of an identifier that 6039 /// does not identify a function. 6040 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 6041 // FIXME: We should probably indicate the identifier in question to avoid 6042 // confusion for constructs like "virtual int a(), b;" 6043 if (DS.isVirtualSpecified()) 6044 Diag(DS.getVirtualSpecLoc(), 6045 diag::err_virtual_non_function); 6046 6047 if (DS.hasExplicitSpecifier()) 6048 Diag(DS.getExplicitSpecLoc(), 6049 diag::err_explicit_non_function); 6050 6051 if (DS.isNoreturnSpecified()) 6052 Diag(DS.getNoreturnSpecLoc(), 6053 diag::err_noreturn_non_function); 6054 } 6055 6056 NamedDecl* 6057 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 6058 TypeSourceInfo *TInfo, LookupResult &Previous) { 6059 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 6060 if (D.getCXXScopeSpec().isSet()) { 6061 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 6062 << D.getCXXScopeSpec().getRange(); 6063 D.setInvalidType(); 6064 // Pretend we didn't see the scope specifier. 6065 DC = CurContext; 6066 Previous.clear(); 6067 } 6068 6069 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6070 6071 if (D.getDeclSpec().isInlineSpecified()) 6072 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6073 << getLangOpts().CPlusPlus17; 6074 if (D.getDeclSpec().hasConstexprSpecifier()) 6075 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 6076 << 1 << D.getDeclSpec().getConstexprSpecifier(); 6077 6078 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) { 6079 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName) 6080 Diag(D.getName().StartLocation, 6081 diag::err_deduction_guide_invalid_specifier) 6082 << "typedef"; 6083 else 6084 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 6085 << D.getName().getSourceRange(); 6086 return nullptr; 6087 } 6088 6089 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 6090 if (!NewTD) return nullptr; 6091 6092 // Handle attributes prior to checking for duplicates in MergeVarDecl 6093 ProcessDeclAttributes(S, NewTD, D); 6094 6095 CheckTypedefForVariablyModifiedType(S, NewTD); 6096 6097 bool Redeclaration = D.isRedeclaration(); 6098 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 6099 D.setRedeclaration(Redeclaration); 6100 return ND; 6101 } 6102 6103 void 6104 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 6105 // C99 6.7.7p2: If a typedef name specifies a variably modified type 6106 // then it shall have block scope. 6107 // Note that variably modified types must be fixed before merging the decl so 6108 // that redeclarations will match. 6109 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 6110 QualType T = TInfo->getType(); 6111 if (T->isVariablyModifiedType()) { 6112 setFunctionHasBranchProtectedScope(); 6113 6114 if (S->getFnParent() == nullptr) { 6115 bool SizeIsNegative; 6116 llvm::APSInt Oversized; 6117 TypeSourceInfo *FixedTInfo = 6118 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 6119 SizeIsNegative, 6120 Oversized); 6121 if (FixedTInfo) { 6122 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 6123 NewTD->setTypeSourceInfo(FixedTInfo); 6124 } else { 6125 if (SizeIsNegative) 6126 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 6127 else if (T->isVariableArrayType()) 6128 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 6129 else if (Oversized.getBoolValue()) 6130 Diag(NewTD->getLocation(), diag::err_array_too_large) 6131 << Oversized.toString(10); 6132 else 6133 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 6134 NewTD->setInvalidDecl(); 6135 } 6136 } 6137 } 6138 } 6139 6140 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 6141 /// declares a typedef-name, either using the 'typedef' type specifier or via 6142 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 6143 NamedDecl* 6144 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 6145 LookupResult &Previous, bool &Redeclaration) { 6146 6147 // Find the shadowed declaration before filtering for scope. 6148 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); 6149 6150 // Merge the decl with the existing one if appropriate. If the decl is 6151 // in an outer scope, it isn't the same thing. 6152 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 6153 /*AllowInlineNamespace*/false); 6154 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 6155 if (!Previous.empty()) { 6156 Redeclaration = true; 6157 MergeTypedefNameDecl(S, NewTD, Previous); 6158 } else { 6159 inferGslPointerAttribute(NewTD); 6160 } 6161 6162 if (ShadowedDecl && !Redeclaration) 6163 CheckShadow(NewTD, ShadowedDecl, Previous); 6164 6165 // If this is the C FILE type, notify the AST context. 6166 if (IdentifierInfo *II = NewTD->getIdentifier()) 6167 if (!NewTD->isInvalidDecl() && 6168 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 6169 if (II->isStr("FILE")) 6170 Context.setFILEDecl(NewTD); 6171 else if (II->isStr("jmp_buf")) 6172 Context.setjmp_bufDecl(NewTD); 6173 else if (II->isStr("sigjmp_buf")) 6174 Context.setsigjmp_bufDecl(NewTD); 6175 else if (II->isStr("ucontext_t")) 6176 Context.setucontext_tDecl(NewTD); 6177 } 6178 6179 return NewTD; 6180 } 6181 6182 /// Determines whether the given declaration is an out-of-scope 6183 /// previous declaration. 6184 /// 6185 /// This routine should be invoked when name lookup has found a 6186 /// previous declaration (PrevDecl) that is not in the scope where a 6187 /// new declaration by the same name is being introduced. If the new 6188 /// declaration occurs in a local scope, previous declarations with 6189 /// linkage may still be considered previous declarations (C99 6190 /// 6.2.2p4-5, C++ [basic.link]p6). 6191 /// 6192 /// \param PrevDecl the previous declaration found by name 6193 /// lookup 6194 /// 6195 /// \param DC the context in which the new declaration is being 6196 /// declared. 6197 /// 6198 /// \returns true if PrevDecl is an out-of-scope previous declaration 6199 /// for a new delcaration with the same name. 6200 static bool 6201 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 6202 ASTContext &Context) { 6203 if (!PrevDecl) 6204 return false; 6205 6206 if (!PrevDecl->hasLinkage()) 6207 return false; 6208 6209 if (Context.getLangOpts().CPlusPlus) { 6210 // C++ [basic.link]p6: 6211 // If there is a visible declaration of an entity with linkage 6212 // having the same name and type, ignoring entities declared 6213 // outside the innermost enclosing namespace scope, the block 6214 // scope declaration declares that same entity and receives the 6215 // linkage of the previous declaration. 6216 DeclContext *OuterContext = DC->getRedeclContext(); 6217 if (!OuterContext->isFunctionOrMethod()) 6218 // This rule only applies to block-scope declarations. 6219 return false; 6220 6221 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 6222 if (PrevOuterContext->isRecord()) 6223 // We found a member function: ignore it. 6224 return false; 6225 6226 // Find the innermost enclosing namespace for the new and 6227 // previous declarations. 6228 OuterContext = OuterContext->getEnclosingNamespaceContext(); 6229 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 6230 6231 // The previous declaration is in a different namespace, so it 6232 // isn't the same function. 6233 if (!OuterContext->Equals(PrevOuterContext)) 6234 return false; 6235 } 6236 6237 return true; 6238 } 6239 6240 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) { 6241 CXXScopeSpec &SS = D.getCXXScopeSpec(); 6242 if (!SS.isSet()) return; 6243 DD->setQualifierInfo(SS.getWithLocInContext(S.Context)); 6244 } 6245 6246 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 6247 QualType type = decl->getType(); 6248 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 6249 if (lifetime == Qualifiers::OCL_Autoreleasing) { 6250 // Various kinds of declaration aren't allowed to be __autoreleasing. 6251 unsigned kind = -1U; 6252 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6253 if (var->hasAttr<BlocksAttr>()) 6254 kind = 0; // __block 6255 else if (!var->hasLocalStorage()) 6256 kind = 1; // global 6257 } else if (isa<ObjCIvarDecl>(decl)) { 6258 kind = 3; // ivar 6259 } else if (isa<FieldDecl>(decl)) { 6260 kind = 2; // field 6261 } 6262 6263 if (kind != -1U) { 6264 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 6265 << kind; 6266 } 6267 } else if (lifetime == Qualifiers::OCL_None) { 6268 // Try to infer lifetime. 6269 if (!type->isObjCLifetimeType()) 6270 return false; 6271 6272 lifetime = type->getObjCARCImplicitLifetime(); 6273 type = Context.getLifetimeQualifiedType(type, lifetime); 6274 decl->setType(type); 6275 } 6276 6277 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6278 // Thread-local variables cannot have lifetime. 6279 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 6280 var->getTLSKind()) { 6281 Diag(var->getLocation(), diag::err_arc_thread_ownership) 6282 << var->getType(); 6283 return true; 6284 } 6285 } 6286 6287 return false; 6288 } 6289 6290 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) { 6291 if (Decl->getType().hasAddressSpace()) 6292 return; 6293 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) { 6294 QualType Type = Var->getType(); 6295 if (Type->isSamplerT() || Type->isVoidType()) 6296 return; 6297 LangAS ImplAS = LangAS::opencl_private; 6298 if ((getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) && 6299 Var->hasGlobalStorage()) 6300 ImplAS = LangAS::opencl_global; 6301 // If the original type from a decayed type is an array type and that array 6302 // type has no address space yet, deduce it now. 6303 if (auto DT = dyn_cast<DecayedType>(Type)) { 6304 auto OrigTy = DT->getOriginalType(); 6305 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) { 6306 // Add the address space to the original array type and then propagate 6307 // that to the element type through `getAsArrayType`. 6308 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS); 6309 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0); 6310 // Re-generate the decayed type. 6311 Type = Context.getDecayedType(OrigTy); 6312 } 6313 } 6314 Type = Context.getAddrSpaceQualType(Type, ImplAS); 6315 // Apply any qualifiers (including address space) from the array type to 6316 // the element type. This implements C99 6.7.3p8: "If the specification of 6317 // an array type includes any type qualifiers, the element type is so 6318 // qualified, not the array type." 6319 if (Type->isArrayType()) 6320 Type = QualType(Context.getAsArrayType(Type), 0); 6321 Decl->setType(Type); 6322 } 6323 } 6324 6325 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 6326 // Ensure that an auto decl is deduced otherwise the checks below might cache 6327 // the wrong linkage. 6328 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 6329 6330 // 'weak' only applies to declarations with external linkage. 6331 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 6332 if (!ND.isExternallyVisible()) { 6333 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 6334 ND.dropAttr<WeakAttr>(); 6335 } 6336 } 6337 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 6338 if (ND.isExternallyVisible()) { 6339 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 6340 ND.dropAttr<WeakRefAttr>(); 6341 ND.dropAttr<AliasAttr>(); 6342 } 6343 } 6344 6345 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 6346 if (VD->hasInit()) { 6347 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 6348 assert(VD->isThisDeclarationADefinition() && 6349 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 6350 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 6351 VD->dropAttr<AliasAttr>(); 6352 } 6353 } 6354 } 6355 6356 // 'selectany' only applies to externally visible variable declarations. 6357 // It does not apply to functions. 6358 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 6359 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 6360 S.Diag(Attr->getLocation(), 6361 diag::err_attribute_selectany_non_extern_data); 6362 ND.dropAttr<SelectAnyAttr>(); 6363 } 6364 } 6365 6366 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 6367 auto *VD = dyn_cast<VarDecl>(&ND); 6368 bool IsAnonymousNS = false; 6369 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6370 if (VD) { 6371 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext()); 6372 while (NS && !IsAnonymousNS) { 6373 IsAnonymousNS = NS->isAnonymousNamespace(); 6374 NS = dyn_cast<NamespaceDecl>(NS->getParent()); 6375 } 6376 } 6377 // dll attributes require external linkage. Static locals may have external 6378 // linkage but still cannot be explicitly imported or exported. 6379 // In Microsoft mode, a variable defined in anonymous namespace must have 6380 // external linkage in order to be exported. 6381 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft; 6382 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) || 6383 (!AnonNSInMicrosoftMode && 6384 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) { 6385 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 6386 << &ND << Attr; 6387 ND.setInvalidDecl(); 6388 } 6389 } 6390 6391 // Virtual functions cannot be marked as 'notail'. 6392 if (auto *Attr = ND.getAttr<NotTailCalledAttr>()) 6393 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND)) 6394 if (MD->isVirtual()) { 6395 S.Diag(ND.getLocation(), 6396 diag::err_invalid_attribute_on_virtual_function) 6397 << Attr; 6398 ND.dropAttr<NotTailCalledAttr>(); 6399 } 6400 6401 // Check the attributes on the function type, if any. 6402 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) { 6403 // Don't declare this variable in the second operand of the for-statement; 6404 // GCC miscompiles that by ending its lifetime before evaluating the 6405 // third operand. See gcc.gnu.org/PR86769. 6406 AttributedTypeLoc ATL; 6407 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc(); 6408 (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); 6409 TL = ATL.getModifiedLoc()) { 6410 // The [[lifetimebound]] attribute can be applied to the implicit object 6411 // parameter of a non-static member function (other than a ctor or dtor) 6412 // by applying it to the function type. 6413 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) { 6414 const auto *MD = dyn_cast<CXXMethodDecl>(FD); 6415 if (!MD || MD->isStatic()) { 6416 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param) 6417 << !MD << A->getRange(); 6418 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) { 6419 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor) 6420 << isa<CXXDestructorDecl>(MD) << A->getRange(); 6421 } 6422 } 6423 } 6424 } 6425 } 6426 6427 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 6428 NamedDecl *NewDecl, 6429 bool IsSpecialization, 6430 bool IsDefinition) { 6431 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl()) 6432 return; 6433 6434 bool IsTemplate = false; 6435 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 6436 OldDecl = OldTD->getTemplatedDecl(); 6437 IsTemplate = true; 6438 if (!IsSpecialization) 6439 IsDefinition = false; 6440 } 6441 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { 6442 NewDecl = NewTD->getTemplatedDecl(); 6443 IsTemplate = true; 6444 } 6445 6446 if (!OldDecl || !NewDecl) 6447 return; 6448 6449 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 6450 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 6451 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 6452 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 6453 6454 // dllimport and dllexport are inheritable attributes so we have to exclude 6455 // inherited attribute instances. 6456 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 6457 (NewExportAttr && !NewExportAttr->isInherited()); 6458 6459 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 6460 // the only exception being explicit specializations. 6461 // Implicitly generated declarations are also excluded for now because there 6462 // is no other way to switch these to use dllimport or dllexport. 6463 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 6464 6465 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 6466 // Allow with a warning for free functions and global variables. 6467 bool JustWarn = false; 6468 if (!OldDecl->isCXXClassMember()) { 6469 auto *VD = dyn_cast<VarDecl>(OldDecl); 6470 if (VD && !VD->getDescribedVarTemplate()) 6471 JustWarn = true; 6472 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 6473 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 6474 JustWarn = true; 6475 } 6476 6477 // We cannot change a declaration that's been used because IR has already 6478 // been emitted. Dllimported functions will still work though (modulo 6479 // address equality) as they can use the thunk. 6480 if (OldDecl->isUsed()) 6481 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 6482 JustWarn = false; 6483 6484 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 6485 : diag::err_attribute_dll_redeclaration; 6486 S.Diag(NewDecl->getLocation(), DiagID) 6487 << NewDecl 6488 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 6489 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6490 if (!JustWarn) { 6491 NewDecl->setInvalidDecl(); 6492 return; 6493 } 6494 } 6495 6496 // A redeclaration is not allowed to drop a dllimport attribute, the only 6497 // exceptions being inline function definitions (except for function 6498 // templates), local extern declarations, qualified friend declarations or 6499 // special MSVC extension: in the last case, the declaration is treated as if 6500 // it were marked dllexport. 6501 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 6502 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6503 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 6504 // Ignore static data because out-of-line definitions are diagnosed 6505 // separately. 6506 IsStaticDataMember = VD->isStaticDataMember(); 6507 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 6508 VarDecl::DeclarationOnly; 6509 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 6510 IsInline = FD->isInlined(); 6511 IsQualifiedFriend = FD->getQualifier() && 6512 FD->getFriendObjectKind() == Decl::FOK_Declared; 6513 } 6514 6515 if (OldImportAttr && !HasNewAttr && 6516 (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember && 6517 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 6518 if (IsMicrosoft && IsDefinition) { 6519 S.Diag(NewDecl->getLocation(), 6520 diag::warn_redeclaration_without_import_attribute) 6521 << NewDecl; 6522 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6523 NewDecl->dropAttr<DLLImportAttr>(); 6524 NewDecl->addAttr( 6525 DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange())); 6526 } else { 6527 S.Diag(NewDecl->getLocation(), 6528 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 6529 << NewDecl << OldImportAttr; 6530 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6531 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 6532 OldDecl->dropAttr<DLLImportAttr>(); 6533 NewDecl->dropAttr<DLLImportAttr>(); 6534 } 6535 } else if (IsInline && OldImportAttr && !IsMicrosoft) { 6536 // In MinGW, seeing a function declared inline drops the dllimport 6537 // attribute. 6538 OldDecl->dropAttr<DLLImportAttr>(); 6539 NewDecl->dropAttr<DLLImportAttr>(); 6540 S.Diag(NewDecl->getLocation(), 6541 diag::warn_dllimport_dropped_from_inline_function) 6542 << NewDecl << OldImportAttr; 6543 } 6544 6545 // A specialization of a class template member function is processed here 6546 // since it's a redeclaration. If the parent class is dllexport, the 6547 // specialization inherits that attribute. This doesn't happen automatically 6548 // since the parent class isn't instantiated until later. 6549 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) { 6550 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && 6551 !NewImportAttr && !NewExportAttr) { 6552 if (const DLLExportAttr *ParentExportAttr = 6553 MD->getParent()->getAttr<DLLExportAttr>()) { 6554 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context); 6555 NewAttr->setInherited(true); 6556 NewDecl->addAttr(NewAttr); 6557 } 6558 } 6559 } 6560 } 6561 6562 /// Given that we are within the definition of the given function, 6563 /// will that definition behave like C99's 'inline', where the 6564 /// definition is discarded except for optimization purposes? 6565 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 6566 // Try to avoid calling GetGVALinkageForFunction. 6567 6568 // All cases of this require the 'inline' keyword. 6569 if (!FD->isInlined()) return false; 6570 6571 // This is only possible in C++ with the gnu_inline attribute. 6572 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 6573 return false; 6574 6575 // Okay, go ahead and call the relatively-more-expensive function. 6576 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 6577 } 6578 6579 /// Determine whether a variable is extern "C" prior to attaching 6580 /// an initializer. We can't just call isExternC() here, because that 6581 /// will also compute and cache whether the declaration is externally 6582 /// visible, which might change when we attach the initializer. 6583 /// 6584 /// This can only be used if the declaration is known to not be a 6585 /// redeclaration of an internal linkage declaration. 6586 /// 6587 /// For instance: 6588 /// 6589 /// auto x = []{}; 6590 /// 6591 /// Attaching the initializer here makes this declaration not externally 6592 /// visible, because its type has internal linkage. 6593 /// 6594 /// FIXME: This is a hack. 6595 template<typename T> 6596 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 6597 if (S.getLangOpts().CPlusPlus) { 6598 // In C++, the overloadable attribute negates the effects of extern "C". 6599 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 6600 return false; 6601 6602 // So do CUDA's host/device attributes. 6603 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 6604 D->template hasAttr<CUDAHostAttr>())) 6605 return false; 6606 } 6607 return D->isExternC(); 6608 } 6609 6610 static bool shouldConsiderLinkage(const VarDecl *VD) { 6611 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 6612 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) || 6613 isa<OMPDeclareMapperDecl>(DC)) 6614 return VD->hasExternalStorage(); 6615 if (DC->isFileContext()) 6616 return true; 6617 if (DC->isRecord()) 6618 return false; 6619 if (isa<RequiresExprBodyDecl>(DC)) 6620 return false; 6621 llvm_unreachable("Unexpected context"); 6622 } 6623 6624 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 6625 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 6626 if (DC->isFileContext() || DC->isFunctionOrMethod() || 6627 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC)) 6628 return true; 6629 if (DC->isRecord()) 6630 return false; 6631 llvm_unreachable("Unexpected context"); 6632 } 6633 6634 static bool hasParsedAttr(Scope *S, const Declarator &PD, 6635 ParsedAttr::Kind Kind) { 6636 // Check decl attributes on the DeclSpec. 6637 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind)) 6638 return true; 6639 6640 // Walk the declarator structure, checking decl attributes that were in a type 6641 // position to the decl itself. 6642 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 6643 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind)) 6644 return true; 6645 } 6646 6647 // Finally, check attributes on the decl itself. 6648 return PD.getAttributes().hasAttribute(Kind); 6649 } 6650 6651 /// Adjust the \c DeclContext for a function or variable that might be a 6652 /// function-local external declaration. 6653 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 6654 if (!DC->isFunctionOrMethod()) 6655 return false; 6656 6657 // If this is a local extern function or variable declared within a function 6658 // template, don't add it into the enclosing namespace scope until it is 6659 // instantiated; it might have a dependent type right now. 6660 if (DC->isDependentContext()) 6661 return true; 6662 6663 // C++11 [basic.link]p7: 6664 // When a block scope declaration of an entity with linkage is not found to 6665 // refer to some other declaration, then that entity is a member of the 6666 // innermost enclosing namespace. 6667 // 6668 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 6669 // semantically-enclosing namespace, not a lexically-enclosing one. 6670 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 6671 DC = DC->getParent(); 6672 return true; 6673 } 6674 6675 /// Returns true if given declaration has external C language linkage. 6676 static bool isDeclExternC(const Decl *D) { 6677 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 6678 return FD->isExternC(); 6679 if (const auto *VD = dyn_cast<VarDecl>(D)) 6680 return VD->isExternC(); 6681 6682 llvm_unreachable("Unknown type of decl!"); 6683 } 6684 /// Returns true if there hasn't been any invalid type diagnosed. 6685 static bool diagnoseOpenCLTypes(Scope *S, Sema &Se, Declarator &D, 6686 DeclContext *DC, QualType R) { 6687 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 6688 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 6689 // argument. 6690 if (R->isImageType() || R->isPipeType()) { 6691 Se.Diag(D.getIdentifierLoc(), 6692 diag::err_opencl_type_can_only_be_used_as_function_parameter) 6693 << R; 6694 D.setInvalidType(); 6695 return false; 6696 } 6697 6698 // OpenCL v1.2 s6.9.r: 6699 // The event type cannot be used to declare a program scope variable. 6700 // OpenCL v2.0 s6.9.q: 6701 // The clk_event_t and reserve_id_t types cannot be declared in program 6702 // scope. 6703 if (NULL == S->getParent()) { 6704 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 6705 Se.Diag(D.getIdentifierLoc(), 6706 diag::err_invalid_type_for_program_scope_var) 6707 << R; 6708 D.setInvalidType(); 6709 return false; 6710 } 6711 } 6712 6713 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 6714 QualType NR = R; 6715 while (NR->isPointerType()) { 6716 if (NR->isFunctionPointerType()) { 6717 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer); 6718 D.setInvalidType(); 6719 return false; 6720 } 6721 NR = NR->getPointeeType(); 6722 } 6723 6724 if (!Se.getOpenCLOptions().isEnabled("cl_khr_fp16")) { 6725 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 6726 // half array type (unless the cl_khr_fp16 extension is enabled). 6727 if (Se.Context.getBaseElementType(R)->isHalfType()) { 6728 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 6729 D.setInvalidType(); 6730 return false; 6731 } 6732 } 6733 6734 // OpenCL v1.2 s6.9.r: 6735 // The event type cannot be used with the __local, __constant and __global 6736 // address space qualifiers. 6737 if (R->isEventT()) { 6738 if (R.getAddressSpace() != LangAS::opencl_private) { 6739 Se.Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual); 6740 D.setInvalidType(); 6741 return false; 6742 } 6743 } 6744 6745 // C++ for OpenCL does not allow the thread_local storage qualifier. 6746 // OpenCL C does not support thread_local either, and 6747 // also reject all other thread storage class specifiers. 6748 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec(); 6749 if (TSC != TSCS_unspecified) { 6750 bool IsCXX = Se.getLangOpts().OpenCLCPlusPlus; 6751 Se.Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6752 diag::err_opencl_unknown_type_specifier) 6753 << IsCXX << Se.getLangOpts().getOpenCLVersionTuple().getAsString() 6754 << DeclSpec::getSpecifierName(TSC) << 1; 6755 D.setInvalidType(); 6756 return false; 6757 } 6758 6759 if (R->isSamplerT()) { 6760 // OpenCL v1.2 s6.9.b p4: 6761 // The sampler type cannot be used with the __local and __global address 6762 // space qualifiers. 6763 if (R.getAddressSpace() == LangAS::opencl_local || 6764 R.getAddressSpace() == LangAS::opencl_global) { 6765 Se.Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 6766 D.setInvalidType(); 6767 } 6768 6769 // OpenCL v1.2 s6.12.14.1: 6770 // A global sampler must be declared with either the constant address 6771 // space qualifier or with the const qualifier. 6772 if (DC->isTranslationUnit() && 6773 !(R.getAddressSpace() == LangAS::opencl_constant || 6774 R.isConstQualified())) { 6775 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler); 6776 D.setInvalidType(); 6777 } 6778 if (D.isInvalidType()) 6779 return false; 6780 } 6781 return true; 6782 } 6783 6784 NamedDecl *Sema::ActOnVariableDeclarator( 6785 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 6786 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 6787 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 6788 QualType R = TInfo->getType(); 6789 DeclarationName Name = GetNameForDeclarator(D).getName(); 6790 6791 IdentifierInfo *II = Name.getAsIdentifierInfo(); 6792 6793 if (D.isDecompositionDeclarator()) { 6794 // Take the name of the first declarator as our name for diagnostic 6795 // purposes. 6796 auto &Decomp = D.getDecompositionDeclarator(); 6797 if (!Decomp.bindings().empty()) { 6798 II = Decomp.bindings()[0].Name; 6799 Name = II; 6800 } 6801 } else if (!II) { 6802 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; 6803 return nullptr; 6804 } 6805 6806 6807 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 6808 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 6809 6810 // dllimport globals without explicit storage class are treated as extern. We 6811 // have to change the storage class this early to get the right DeclContext. 6812 if (SC == SC_None && !DC->isRecord() && 6813 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) && 6814 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport)) 6815 SC = SC_Extern; 6816 6817 DeclContext *OriginalDC = DC; 6818 bool IsLocalExternDecl = SC == SC_Extern && 6819 adjustContextForLocalExternDecl(DC); 6820 6821 if (SCSpec == DeclSpec::SCS_mutable) { 6822 // mutable can only appear on non-static class members, so it's always 6823 // an error here 6824 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 6825 D.setInvalidType(); 6826 SC = SC_None; 6827 } 6828 6829 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 6830 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 6831 D.getDeclSpec().getStorageClassSpecLoc())) { 6832 // In C++11, the 'register' storage class specifier is deprecated. 6833 // Suppress the warning in system macros, it's used in macros in some 6834 // popular C system headers, such as in glibc's htonl() macro. 6835 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6836 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 6837 : diag::warn_deprecated_register) 6838 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6839 } 6840 6841 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6842 6843 if (!DC->isRecord() && S->getFnParent() == nullptr) { 6844 // C99 6.9p2: The storage-class specifiers auto and register shall not 6845 // appear in the declaration specifiers in an external declaration. 6846 // Global Register+Asm is a GNU extension we support. 6847 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 6848 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 6849 D.setInvalidType(); 6850 } 6851 } 6852 6853 bool IsMemberSpecialization = false; 6854 bool IsVariableTemplateSpecialization = false; 6855 bool IsPartialSpecialization = false; 6856 bool IsVariableTemplate = false; 6857 VarDecl *NewVD = nullptr; 6858 VarTemplateDecl *NewTemplate = nullptr; 6859 TemplateParameterList *TemplateParams = nullptr; 6860 if (!getLangOpts().CPlusPlus) { 6861 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), 6862 II, R, TInfo, SC); 6863 6864 if (R->getContainedDeducedType()) 6865 ParsingInitForAutoVars.insert(NewVD); 6866 6867 if (D.isInvalidType()) 6868 NewVD->setInvalidDecl(); 6869 6870 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() && 6871 NewVD->hasLocalStorage()) 6872 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(), 6873 NTCUC_AutoVar, NTCUK_Destruct); 6874 } else { 6875 bool Invalid = false; 6876 6877 if (DC->isRecord() && !CurContext->isRecord()) { 6878 // This is an out-of-line definition of a static data member. 6879 switch (SC) { 6880 case SC_None: 6881 break; 6882 case SC_Static: 6883 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6884 diag::err_static_out_of_line) 6885 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6886 break; 6887 case SC_Auto: 6888 case SC_Register: 6889 case SC_Extern: 6890 // [dcl.stc] p2: The auto or register specifiers shall be applied only 6891 // to names of variables declared in a block or to function parameters. 6892 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 6893 // of class members 6894 6895 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6896 diag::err_storage_class_for_static_member) 6897 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6898 break; 6899 case SC_PrivateExtern: 6900 llvm_unreachable("C storage class in c++!"); 6901 } 6902 } 6903 6904 if (SC == SC_Static && CurContext->isRecord()) { 6905 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 6906 // Walk up the enclosing DeclContexts to check for any that are 6907 // incompatible with static data members. 6908 const DeclContext *FunctionOrMethod = nullptr; 6909 const CXXRecordDecl *AnonStruct = nullptr; 6910 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) { 6911 if (Ctxt->isFunctionOrMethod()) { 6912 FunctionOrMethod = Ctxt; 6913 break; 6914 } 6915 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt); 6916 if (ParentDecl && !ParentDecl->getDeclName()) { 6917 AnonStruct = ParentDecl; 6918 break; 6919 } 6920 } 6921 if (FunctionOrMethod) { 6922 // C++ [class.static.data]p5: A local class shall not have static data 6923 // members. 6924 Diag(D.getIdentifierLoc(), 6925 diag::err_static_data_member_not_allowed_in_local_class) 6926 << Name << RD->getDeclName() << RD->getTagKind(); 6927 } else if (AnonStruct) { 6928 // C++ [class.static.data]p4: Unnamed classes and classes contained 6929 // directly or indirectly within unnamed classes shall not contain 6930 // static data members. 6931 Diag(D.getIdentifierLoc(), 6932 diag::err_static_data_member_not_allowed_in_anon_struct) 6933 << Name << AnonStruct->getTagKind(); 6934 Invalid = true; 6935 } else if (RD->isUnion()) { 6936 // C++98 [class.union]p1: If a union contains a static data member, 6937 // the program is ill-formed. C++11 drops this restriction. 6938 Diag(D.getIdentifierLoc(), 6939 getLangOpts().CPlusPlus11 6940 ? diag::warn_cxx98_compat_static_data_member_in_union 6941 : diag::ext_static_data_member_in_union) << Name; 6942 } 6943 } 6944 } 6945 6946 // Match up the template parameter lists with the scope specifier, then 6947 // determine whether we have a template or a template specialization. 6948 bool InvalidScope = false; 6949 TemplateParams = MatchTemplateParametersToScopeSpecifier( 6950 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 6951 D.getCXXScopeSpec(), 6952 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 6953 ? D.getName().TemplateId 6954 : nullptr, 6955 TemplateParamLists, 6956 /*never a friend*/ false, IsMemberSpecialization, InvalidScope); 6957 Invalid |= InvalidScope; 6958 6959 if (TemplateParams) { 6960 if (!TemplateParams->size() && 6961 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 6962 // There is an extraneous 'template<>' for this variable. Complain 6963 // about it, but allow the declaration of the variable. 6964 Diag(TemplateParams->getTemplateLoc(), 6965 diag::err_template_variable_noparams) 6966 << II 6967 << SourceRange(TemplateParams->getTemplateLoc(), 6968 TemplateParams->getRAngleLoc()); 6969 TemplateParams = nullptr; 6970 } else { 6971 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 6972 // This is an explicit specialization or a partial specialization. 6973 // FIXME: Check that we can declare a specialization here. 6974 IsVariableTemplateSpecialization = true; 6975 IsPartialSpecialization = TemplateParams->size() > 0; 6976 } else { // if (TemplateParams->size() > 0) 6977 // This is a template declaration. 6978 IsVariableTemplate = true; 6979 6980 // Check that we can declare a template here. 6981 if (CheckTemplateDeclScope(S, TemplateParams)) 6982 return nullptr; 6983 6984 // Only C++1y supports variable templates (N3651). 6985 Diag(D.getIdentifierLoc(), 6986 getLangOpts().CPlusPlus14 6987 ? diag::warn_cxx11_compat_variable_template 6988 : diag::ext_variable_template); 6989 } 6990 } 6991 } else { 6992 assert((Invalid || 6993 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && 6994 "should have a 'template<>' for this decl"); 6995 } 6996 6997 if (IsVariableTemplateSpecialization) { 6998 SourceLocation TemplateKWLoc = 6999 TemplateParamLists.size() > 0 7000 ? TemplateParamLists[0]->getTemplateLoc() 7001 : SourceLocation(); 7002 DeclResult Res = ActOnVarTemplateSpecialization( 7003 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 7004 IsPartialSpecialization); 7005 if (Res.isInvalid()) 7006 return nullptr; 7007 NewVD = cast<VarDecl>(Res.get()); 7008 AddToScope = false; 7009 } else if (D.isDecompositionDeclarator()) { 7010 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(), 7011 D.getIdentifierLoc(), R, TInfo, SC, 7012 Bindings); 7013 } else 7014 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), 7015 D.getIdentifierLoc(), II, R, TInfo, SC); 7016 7017 // If this is supposed to be a variable template, create it as such. 7018 if (IsVariableTemplate) { 7019 NewTemplate = 7020 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 7021 TemplateParams, NewVD); 7022 NewVD->setDescribedVarTemplate(NewTemplate); 7023 } 7024 7025 // If this decl has an auto type in need of deduction, make a note of the 7026 // Decl so we can diagnose uses of it in its own initializer. 7027 if (R->getContainedDeducedType()) 7028 ParsingInitForAutoVars.insert(NewVD); 7029 7030 if (D.isInvalidType() || Invalid) { 7031 NewVD->setInvalidDecl(); 7032 if (NewTemplate) 7033 NewTemplate->setInvalidDecl(); 7034 } 7035 7036 SetNestedNameSpecifier(*this, NewVD, D); 7037 7038 // If we have any template parameter lists that don't directly belong to 7039 // the variable (matching the scope specifier), store them. 7040 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 7041 if (TemplateParamLists.size() > VDTemplateParamLists) 7042 NewVD->setTemplateParameterListsInfo( 7043 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 7044 } 7045 7046 if (D.getDeclSpec().isInlineSpecified()) { 7047 if (!getLangOpts().CPlusPlus) { 7048 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 7049 << 0; 7050 } else if (CurContext->isFunctionOrMethod()) { 7051 // 'inline' is not allowed on block scope variable declaration. 7052 Diag(D.getDeclSpec().getInlineSpecLoc(), 7053 diag::err_inline_declaration_block_scope) << Name 7054 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 7055 } else { 7056 Diag(D.getDeclSpec().getInlineSpecLoc(), 7057 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable 7058 : diag::ext_inline_variable); 7059 NewVD->setInlineSpecified(); 7060 } 7061 } 7062 7063 // Set the lexical context. If the declarator has a C++ scope specifier, the 7064 // lexical context will be different from the semantic context. 7065 NewVD->setLexicalDeclContext(CurContext); 7066 if (NewTemplate) 7067 NewTemplate->setLexicalDeclContext(CurContext); 7068 7069 if (IsLocalExternDecl) { 7070 if (D.isDecompositionDeclarator()) 7071 for (auto *B : Bindings) 7072 B->setLocalExternDecl(); 7073 else 7074 NewVD->setLocalExternDecl(); 7075 } 7076 7077 bool EmitTLSUnsupportedError = false; 7078 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 7079 // C++11 [dcl.stc]p4: 7080 // When thread_local is applied to a variable of block scope the 7081 // storage-class-specifier static is implied if it does not appear 7082 // explicitly. 7083 // Core issue: 'static' is not implied if the variable is declared 7084 // 'extern'. 7085 if (NewVD->hasLocalStorage() && 7086 (SCSpec != DeclSpec::SCS_unspecified || 7087 TSCS != DeclSpec::TSCS_thread_local || 7088 !DC->isFunctionOrMethod())) 7089 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7090 diag::err_thread_non_global) 7091 << DeclSpec::getSpecifierName(TSCS); 7092 else if (!Context.getTargetInfo().isTLSSupported()) { 7093 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || 7094 getLangOpts().SYCLIsDevice) { 7095 // Postpone error emission until we've collected attributes required to 7096 // figure out whether it's a host or device variable and whether the 7097 // error should be ignored. 7098 EmitTLSUnsupportedError = true; 7099 // We still need to mark the variable as TLS so it shows up in AST with 7100 // proper storage class for other tools to use even if we're not going 7101 // to emit any code for it. 7102 NewVD->setTSCSpec(TSCS); 7103 } else 7104 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7105 diag::err_thread_unsupported); 7106 } else 7107 NewVD->setTSCSpec(TSCS); 7108 } 7109 7110 switch (D.getDeclSpec().getConstexprSpecifier()) { 7111 case CSK_unspecified: 7112 break; 7113 7114 case CSK_consteval: 7115 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7116 diag::err_constexpr_wrong_decl_kind) 7117 << D.getDeclSpec().getConstexprSpecifier(); 7118 LLVM_FALLTHROUGH; 7119 7120 case CSK_constexpr: 7121 NewVD->setConstexpr(true); 7122 MaybeAddCUDAConstantAttr(NewVD); 7123 // C++1z [dcl.spec.constexpr]p1: 7124 // A static data member declared with the constexpr specifier is 7125 // implicitly an inline variable. 7126 if (NewVD->isStaticDataMember() && 7127 (getLangOpts().CPlusPlus17 || 7128 Context.getTargetInfo().getCXXABI().isMicrosoft())) 7129 NewVD->setImplicitlyInline(); 7130 break; 7131 7132 case CSK_constinit: 7133 if (!NewVD->hasGlobalStorage()) 7134 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7135 diag::err_constinit_local_variable); 7136 else 7137 NewVD->addAttr(ConstInitAttr::Create( 7138 Context, D.getDeclSpec().getConstexprSpecLoc(), 7139 AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit)); 7140 break; 7141 } 7142 7143 // C99 6.7.4p3 7144 // An inline definition of a function with external linkage shall 7145 // not contain a definition of a modifiable object with static or 7146 // thread storage duration... 7147 // We only apply this when the function is required to be defined 7148 // elsewhere, i.e. when the function is not 'extern inline'. Note 7149 // that a local variable with thread storage duration still has to 7150 // be marked 'static'. Also note that it's possible to get these 7151 // semantics in C++ using __attribute__((gnu_inline)). 7152 if (SC == SC_Static && S->getFnParent() != nullptr && 7153 !NewVD->getType().isConstQualified()) { 7154 FunctionDecl *CurFD = getCurFunctionDecl(); 7155 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 7156 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7157 diag::warn_static_local_in_extern_inline); 7158 MaybeSuggestAddingStaticToDecl(CurFD); 7159 } 7160 } 7161 7162 if (D.getDeclSpec().isModulePrivateSpecified()) { 7163 if (IsVariableTemplateSpecialization) 7164 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7165 << (IsPartialSpecialization ? 1 : 0) 7166 << FixItHint::CreateRemoval( 7167 D.getDeclSpec().getModulePrivateSpecLoc()); 7168 else if (IsMemberSpecialization) 7169 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7170 << 2 7171 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 7172 else if (NewVD->hasLocalStorage()) 7173 Diag(NewVD->getLocation(), diag::err_module_private_local) 7174 << 0 << NewVD->getDeclName() 7175 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 7176 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 7177 else { 7178 NewVD->setModulePrivate(); 7179 if (NewTemplate) 7180 NewTemplate->setModulePrivate(); 7181 for (auto *B : Bindings) 7182 B->setModulePrivate(); 7183 } 7184 } 7185 7186 if (getLangOpts().OpenCL) { 7187 7188 deduceOpenCLAddressSpace(NewVD); 7189 7190 diagnoseOpenCLTypes(S, *this, D, DC, NewVD->getType()); 7191 } 7192 7193 // Handle attributes prior to checking for duplicates in MergeVarDecl 7194 ProcessDeclAttributes(S, NewVD, D); 7195 7196 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || 7197 getLangOpts().SYCLIsDevice) { 7198 if (EmitTLSUnsupportedError && 7199 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || 7200 (getLangOpts().OpenMPIsDevice && 7201 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD)))) 7202 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7203 diag::err_thread_unsupported); 7204 7205 if (EmitTLSUnsupportedError && 7206 (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice))) 7207 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported); 7208 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 7209 // storage [duration]." 7210 if (SC == SC_None && S->getFnParent() != nullptr && 7211 (NewVD->hasAttr<CUDASharedAttr>() || 7212 NewVD->hasAttr<CUDAConstantAttr>())) { 7213 NewVD->setStorageClass(SC_Static); 7214 } 7215 } 7216 7217 // Ensure that dllimport globals without explicit storage class are treated as 7218 // extern. The storage class is set above using parsed attributes. Now we can 7219 // check the VarDecl itself. 7220 assert(!NewVD->hasAttr<DLLImportAttr>() || 7221 NewVD->getAttr<DLLImportAttr>()->isInherited() || 7222 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 7223 7224 // In auto-retain/release, infer strong retension for variables of 7225 // retainable type. 7226 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 7227 NewVD->setInvalidDecl(); 7228 7229 // Handle GNU asm-label extension (encoded as an attribute). 7230 if (Expr *E = (Expr*)D.getAsmLabel()) { 7231 // The parser guarantees this is a string. 7232 StringLiteral *SE = cast<StringLiteral>(E); 7233 StringRef Label = SE->getString(); 7234 if (S->getFnParent() != nullptr) { 7235 switch (SC) { 7236 case SC_None: 7237 case SC_Auto: 7238 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 7239 break; 7240 case SC_Register: 7241 // Local Named register 7242 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 7243 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 7244 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7245 break; 7246 case SC_Static: 7247 case SC_Extern: 7248 case SC_PrivateExtern: 7249 break; 7250 } 7251 } else if (SC == SC_Register) { 7252 // Global Named register 7253 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 7254 const auto &TI = Context.getTargetInfo(); 7255 bool HasSizeMismatch; 7256 7257 if (!TI.isValidGCCRegisterName(Label)) 7258 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7259 else if (!TI.validateGlobalRegisterVariable(Label, 7260 Context.getTypeSize(R), 7261 HasSizeMismatch)) 7262 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 7263 else if (HasSizeMismatch) 7264 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 7265 } 7266 7267 if (!R->isIntegralType(Context) && !R->isPointerType()) { 7268 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type); 7269 NewVD->setInvalidDecl(true); 7270 } 7271 } 7272 7273 NewVD->addAttr(AsmLabelAttr::Create(Context, Label, 7274 /*IsLiteralLabel=*/true, 7275 SE->getStrTokenLoc(0))); 7276 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 7277 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 7278 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 7279 if (I != ExtnameUndeclaredIdentifiers.end()) { 7280 if (isDeclExternC(NewVD)) { 7281 NewVD->addAttr(I->second); 7282 ExtnameUndeclaredIdentifiers.erase(I); 7283 } else 7284 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 7285 << /*Variable*/1 << NewVD; 7286 } 7287 } 7288 7289 // Find the shadowed declaration before filtering for scope. 7290 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 7291 ? getShadowedDeclaration(NewVD, Previous) 7292 : nullptr; 7293 7294 // Don't consider existing declarations that are in a different 7295 // scope and are out-of-semantic-context declarations (if the new 7296 // declaration has linkage). 7297 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 7298 D.getCXXScopeSpec().isNotEmpty() || 7299 IsMemberSpecialization || 7300 IsVariableTemplateSpecialization); 7301 7302 // Check whether the previous declaration is in the same block scope. This 7303 // affects whether we merge types with it, per C++11 [dcl.array]p3. 7304 if (getLangOpts().CPlusPlus && 7305 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 7306 NewVD->setPreviousDeclInSameBlockScope( 7307 Previous.isSingleResult() && !Previous.isShadowed() && 7308 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 7309 7310 if (!getLangOpts().CPlusPlus) { 7311 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7312 } else { 7313 // If this is an explicit specialization of a static data member, check it. 7314 if (IsMemberSpecialization && !NewVD->isInvalidDecl() && 7315 CheckMemberSpecialization(NewVD, Previous)) 7316 NewVD->setInvalidDecl(); 7317 7318 // Merge the decl with the existing one if appropriate. 7319 if (!Previous.empty()) { 7320 if (Previous.isSingleResult() && 7321 isa<FieldDecl>(Previous.getFoundDecl()) && 7322 D.getCXXScopeSpec().isSet()) { 7323 // The user tried to define a non-static data member 7324 // out-of-line (C++ [dcl.meaning]p1). 7325 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 7326 << D.getCXXScopeSpec().getRange(); 7327 Previous.clear(); 7328 NewVD->setInvalidDecl(); 7329 } 7330 } else if (D.getCXXScopeSpec().isSet()) { 7331 // No previous declaration in the qualifying scope. 7332 Diag(D.getIdentifierLoc(), diag::err_no_member) 7333 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 7334 << D.getCXXScopeSpec().getRange(); 7335 NewVD->setInvalidDecl(); 7336 } 7337 7338 if (!IsVariableTemplateSpecialization) 7339 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7340 7341 if (NewTemplate) { 7342 VarTemplateDecl *PrevVarTemplate = 7343 NewVD->getPreviousDecl() 7344 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 7345 : nullptr; 7346 7347 // Check the template parameter list of this declaration, possibly 7348 // merging in the template parameter list from the previous variable 7349 // template declaration. 7350 if (CheckTemplateParameterList( 7351 TemplateParams, 7352 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 7353 : nullptr, 7354 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 7355 DC->isDependentContext()) 7356 ? TPC_ClassTemplateMember 7357 : TPC_VarTemplate)) 7358 NewVD->setInvalidDecl(); 7359 7360 // If we are providing an explicit specialization of a static variable 7361 // template, make a note of that. 7362 if (PrevVarTemplate && 7363 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 7364 PrevVarTemplate->setMemberSpecialization(); 7365 } 7366 } 7367 7368 // Diagnose shadowed variables iff this isn't a redeclaration. 7369 if (ShadowedDecl && !D.isRedeclaration()) 7370 CheckShadow(NewVD, ShadowedDecl, Previous); 7371 7372 ProcessPragmaWeak(S, NewVD); 7373 7374 // If this is the first declaration of an extern C variable, update 7375 // the map of such variables. 7376 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 7377 isIncompleteDeclExternC(*this, NewVD)) 7378 RegisterLocallyScopedExternCDecl(NewVD, S); 7379 7380 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 7381 MangleNumberingContext *MCtx; 7382 Decl *ManglingContextDecl; 7383 std::tie(MCtx, ManglingContextDecl) = 7384 getCurrentMangleNumberContext(NewVD->getDeclContext()); 7385 if (MCtx) { 7386 Context.setManglingNumber( 7387 NewVD, MCtx->getManglingNumber( 7388 NewVD, getMSManglingNumber(getLangOpts(), S))); 7389 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 7390 } 7391 } 7392 7393 // Special handling of variable named 'main'. 7394 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 7395 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 7396 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 7397 7398 // C++ [basic.start.main]p3 7399 // A program that declares a variable main at global scope is ill-formed. 7400 if (getLangOpts().CPlusPlus) 7401 Diag(D.getBeginLoc(), diag::err_main_global_variable); 7402 7403 // In C, and external-linkage variable named main results in undefined 7404 // behavior. 7405 else if (NewVD->hasExternalFormalLinkage()) 7406 Diag(D.getBeginLoc(), diag::warn_main_redefined); 7407 } 7408 7409 if (D.isRedeclaration() && !Previous.empty()) { 7410 NamedDecl *Prev = Previous.getRepresentativeDecl(); 7411 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization, 7412 D.isFunctionDefinition()); 7413 } 7414 7415 if (NewTemplate) { 7416 if (NewVD->isInvalidDecl()) 7417 NewTemplate->setInvalidDecl(); 7418 ActOnDocumentableDecl(NewTemplate); 7419 return NewTemplate; 7420 } 7421 7422 if (IsMemberSpecialization && !NewVD->isInvalidDecl()) 7423 CompleteMemberSpecialization(NewVD, Previous); 7424 7425 return NewVD; 7426 } 7427 7428 /// Enum describing the %select options in diag::warn_decl_shadow. 7429 enum ShadowedDeclKind { 7430 SDK_Local, 7431 SDK_Global, 7432 SDK_StaticMember, 7433 SDK_Field, 7434 SDK_Typedef, 7435 SDK_Using 7436 }; 7437 7438 /// Determine what kind of declaration we're shadowing. 7439 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 7440 const DeclContext *OldDC) { 7441 if (isa<TypeAliasDecl>(ShadowedDecl)) 7442 return SDK_Using; 7443 else if (isa<TypedefDecl>(ShadowedDecl)) 7444 return SDK_Typedef; 7445 else if (isa<RecordDecl>(OldDC)) 7446 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 7447 7448 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 7449 } 7450 7451 /// Return the location of the capture if the given lambda captures the given 7452 /// variable \p VD, or an invalid source location otherwise. 7453 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 7454 const VarDecl *VD) { 7455 for (const Capture &Capture : LSI->Captures) { 7456 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 7457 return Capture.getLocation(); 7458 } 7459 return SourceLocation(); 7460 } 7461 7462 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, 7463 const LookupResult &R) { 7464 // Only diagnose if we're shadowing an unambiguous field or variable. 7465 if (R.getResultKind() != LookupResult::Found) 7466 return false; 7467 7468 // Return false if warning is ignored. 7469 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); 7470 } 7471 7472 /// Return the declaration shadowed by the given variable \p D, or null 7473 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7474 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 7475 const LookupResult &R) { 7476 if (!shouldWarnIfShadowedDecl(Diags, R)) 7477 return nullptr; 7478 7479 // Don't diagnose declarations at file scope. 7480 if (D->hasGlobalStorage()) 7481 return nullptr; 7482 7483 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7484 return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl) 7485 ? ShadowedDecl 7486 : nullptr; 7487 } 7488 7489 /// Return the declaration shadowed by the given typedef \p D, or null 7490 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7491 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, 7492 const LookupResult &R) { 7493 // Don't warn if typedef declaration is part of a class 7494 if (D->getDeclContext()->isRecord()) 7495 return nullptr; 7496 7497 if (!shouldWarnIfShadowedDecl(Diags, R)) 7498 return nullptr; 7499 7500 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7501 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; 7502 } 7503 7504 /// Diagnose variable or built-in function shadowing. Implements 7505 /// -Wshadow. 7506 /// 7507 /// This method is called whenever a VarDecl is added to a "useful" 7508 /// scope. 7509 /// 7510 /// \param ShadowedDecl the declaration that is shadowed by the given variable 7511 /// \param R the lookup of the name 7512 /// 7513 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 7514 const LookupResult &R) { 7515 DeclContext *NewDC = D->getDeclContext(); 7516 7517 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 7518 // Fields are not shadowed by variables in C++ static methods. 7519 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 7520 if (MD->isStatic()) 7521 return; 7522 7523 // Fields shadowed by constructor parameters are a special case. Usually 7524 // the constructor initializes the field with the parameter. 7525 if (isa<CXXConstructorDecl>(NewDC)) 7526 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { 7527 // Remember that this was shadowed so we can either warn about its 7528 // modification or its existence depending on warning settings. 7529 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); 7530 return; 7531 } 7532 } 7533 7534 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 7535 if (shadowedVar->isExternC()) { 7536 // For shadowing external vars, make sure that we point to the global 7537 // declaration, not a locally scoped extern declaration. 7538 for (auto I : shadowedVar->redecls()) 7539 if (I->isFileVarDecl()) { 7540 ShadowedDecl = I; 7541 break; 7542 } 7543 } 7544 7545 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); 7546 7547 unsigned WarningDiag = diag::warn_decl_shadow; 7548 SourceLocation CaptureLoc; 7549 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && 7550 isa<CXXMethodDecl>(NewDC)) { 7551 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 7552 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 7553 if (RD->getLambdaCaptureDefault() == LCD_None) { 7554 // Try to avoid warnings for lambdas with an explicit capture list. 7555 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 7556 // Warn only when the lambda captures the shadowed decl explicitly. 7557 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 7558 if (CaptureLoc.isInvalid()) 7559 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 7560 } else { 7561 // Remember that this was shadowed so we can avoid the warning if the 7562 // shadowed decl isn't captured and the warning settings allow it. 7563 cast<LambdaScopeInfo>(getCurFunction()) 7564 ->ShadowingDecls.push_back( 7565 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); 7566 return; 7567 } 7568 } 7569 7570 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { 7571 // A variable can't shadow a local variable in an enclosing scope, if 7572 // they are separated by a non-capturing declaration context. 7573 for (DeclContext *ParentDC = NewDC; 7574 ParentDC && !ParentDC->Equals(OldDC); 7575 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { 7576 // Only block literals, captured statements, and lambda expressions 7577 // can capture; other scopes don't. 7578 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && 7579 !isLambdaCallOperator(ParentDC)) { 7580 return; 7581 } 7582 } 7583 } 7584 } 7585 } 7586 7587 // Only warn about certain kinds of shadowing for class members. 7588 if (NewDC && NewDC->isRecord()) { 7589 // In particular, don't warn about shadowing non-class members. 7590 if (!OldDC->isRecord()) 7591 return; 7592 7593 // TODO: should we warn about static data members shadowing 7594 // static data members from base classes? 7595 7596 // TODO: don't diagnose for inaccessible shadowed members. 7597 // This is hard to do perfectly because we might friend the 7598 // shadowing context, but that's just a false negative. 7599 } 7600 7601 7602 DeclarationName Name = R.getLookupName(); 7603 7604 // Emit warning and note. 7605 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 7606 return; 7607 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 7608 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 7609 if (!CaptureLoc.isInvalid()) 7610 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7611 << Name << /*explicitly*/ 1; 7612 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7613 } 7614 7615 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 7616 /// when these variables are captured by the lambda. 7617 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 7618 for (const auto &Shadow : LSI->ShadowingDecls) { 7619 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 7620 // Try to avoid the warning when the shadowed decl isn't captured. 7621 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 7622 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7623 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 7624 ? diag::warn_decl_shadow_uncaptured_local 7625 : diag::warn_decl_shadow) 7626 << Shadow.VD->getDeclName() 7627 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 7628 if (!CaptureLoc.isInvalid()) 7629 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7630 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 7631 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7632 } 7633 } 7634 7635 /// Check -Wshadow without the advantage of a previous lookup. 7636 void Sema::CheckShadow(Scope *S, VarDecl *D) { 7637 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 7638 return; 7639 7640 LookupResult R(*this, D->getDeclName(), D->getLocation(), 7641 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); 7642 LookupName(R, S); 7643 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 7644 CheckShadow(D, ShadowedDecl, R); 7645 } 7646 7647 /// Check if 'E', which is an expression that is about to be modified, refers 7648 /// to a constructor parameter that shadows a field. 7649 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 7650 // Quickly ignore expressions that can't be shadowing ctor parameters. 7651 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 7652 return; 7653 E = E->IgnoreParenImpCasts(); 7654 auto *DRE = dyn_cast<DeclRefExpr>(E); 7655 if (!DRE) 7656 return; 7657 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 7658 auto I = ShadowingDecls.find(D); 7659 if (I == ShadowingDecls.end()) 7660 return; 7661 const NamedDecl *ShadowedDecl = I->second; 7662 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7663 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 7664 Diag(D->getLocation(), diag::note_var_declared_here) << D; 7665 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7666 7667 // Avoid issuing multiple warnings about the same decl. 7668 ShadowingDecls.erase(I); 7669 } 7670 7671 /// Check for conflict between this global or extern "C" declaration and 7672 /// previous global or extern "C" declarations. This is only used in C++. 7673 template<typename T> 7674 static bool checkGlobalOrExternCConflict( 7675 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 7676 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 7677 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 7678 7679 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 7680 // The common case: this global doesn't conflict with any extern "C" 7681 // declaration. 7682 return false; 7683 } 7684 7685 if (Prev) { 7686 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 7687 // Both the old and new declarations have C language linkage. This is a 7688 // redeclaration. 7689 Previous.clear(); 7690 Previous.addDecl(Prev); 7691 return true; 7692 } 7693 7694 // This is a global, non-extern "C" declaration, and there is a previous 7695 // non-global extern "C" declaration. Diagnose if this is a variable 7696 // declaration. 7697 if (!isa<VarDecl>(ND)) 7698 return false; 7699 } else { 7700 // The declaration is extern "C". Check for any declaration in the 7701 // translation unit which might conflict. 7702 if (IsGlobal) { 7703 // We have already performed the lookup into the translation unit. 7704 IsGlobal = false; 7705 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7706 I != E; ++I) { 7707 if (isa<VarDecl>(*I)) { 7708 Prev = *I; 7709 break; 7710 } 7711 } 7712 } else { 7713 DeclContext::lookup_result R = 7714 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 7715 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 7716 I != E; ++I) { 7717 if (isa<VarDecl>(*I)) { 7718 Prev = *I; 7719 break; 7720 } 7721 // FIXME: If we have any other entity with this name in global scope, 7722 // the declaration is ill-formed, but that is a defect: it breaks the 7723 // 'stat' hack, for instance. Only variables can have mangled name 7724 // clashes with extern "C" declarations, so only they deserve a 7725 // diagnostic. 7726 } 7727 } 7728 7729 if (!Prev) 7730 return false; 7731 } 7732 7733 // Use the first declaration's location to ensure we point at something which 7734 // is lexically inside an extern "C" linkage-spec. 7735 assert(Prev && "should have found a previous declaration to diagnose"); 7736 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 7737 Prev = FD->getFirstDecl(); 7738 else 7739 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 7740 7741 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 7742 << IsGlobal << ND; 7743 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 7744 << IsGlobal; 7745 return false; 7746 } 7747 7748 /// Apply special rules for handling extern "C" declarations. Returns \c true 7749 /// if we have found that this is a redeclaration of some prior entity. 7750 /// 7751 /// Per C++ [dcl.link]p6: 7752 /// Two declarations [for a function or variable] with C language linkage 7753 /// with the same name that appear in different scopes refer to the same 7754 /// [entity]. An entity with C language linkage shall not be declared with 7755 /// the same name as an entity in global scope. 7756 template<typename T> 7757 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 7758 LookupResult &Previous) { 7759 if (!S.getLangOpts().CPlusPlus) { 7760 // In C, when declaring a global variable, look for a corresponding 'extern' 7761 // variable declared in function scope. We don't need this in C++, because 7762 // we find local extern decls in the surrounding file-scope DeclContext. 7763 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7764 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 7765 Previous.clear(); 7766 Previous.addDecl(Prev); 7767 return true; 7768 } 7769 } 7770 return false; 7771 } 7772 7773 // A declaration in the translation unit can conflict with an extern "C" 7774 // declaration. 7775 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 7776 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 7777 7778 // An extern "C" declaration can conflict with a declaration in the 7779 // translation unit or can be a redeclaration of an extern "C" declaration 7780 // in another scope. 7781 if (isIncompleteDeclExternC(S,ND)) 7782 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 7783 7784 // Neither global nor extern "C": nothing to do. 7785 return false; 7786 } 7787 7788 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 7789 // If the decl is already known invalid, don't check it. 7790 if (NewVD->isInvalidDecl()) 7791 return; 7792 7793 QualType T = NewVD->getType(); 7794 7795 // Defer checking an 'auto' type until its initializer is attached. 7796 if (T->isUndeducedType()) 7797 return; 7798 7799 if (NewVD->hasAttrs()) 7800 CheckAlignasUnderalignment(NewVD); 7801 7802 if (T->isObjCObjectType()) { 7803 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 7804 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 7805 T = Context.getObjCObjectPointerType(T); 7806 NewVD->setType(T); 7807 } 7808 7809 // Emit an error if an address space was applied to decl with local storage. 7810 // This includes arrays of objects with address space qualifiers, but not 7811 // automatic variables that point to other address spaces. 7812 // ISO/IEC TR 18037 S5.1.2 7813 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && 7814 T.getAddressSpace() != LangAS::Default) { 7815 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; 7816 NewVD->setInvalidDecl(); 7817 return; 7818 } 7819 7820 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 7821 // scope. 7822 if (getLangOpts().OpenCLVersion == 120 && 7823 !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") && 7824 NewVD->isStaticLocal()) { 7825 Diag(NewVD->getLocation(), diag::err_static_function_scope); 7826 NewVD->setInvalidDecl(); 7827 return; 7828 } 7829 7830 if (getLangOpts().OpenCL) { 7831 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 7832 if (NewVD->hasAttr<BlocksAttr>()) { 7833 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 7834 return; 7835 } 7836 7837 if (T->isBlockPointerType()) { 7838 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 7839 // can't use 'extern' storage class. 7840 if (!T.isConstQualified()) { 7841 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 7842 << 0 /*const*/; 7843 NewVD->setInvalidDecl(); 7844 return; 7845 } 7846 if (NewVD->hasExternalStorage()) { 7847 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 7848 NewVD->setInvalidDecl(); 7849 return; 7850 } 7851 } 7852 // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the 7853 // __constant address space. 7854 // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static 7855 // variables inside a function can also be declared in the global 7856 // address space. 7857 // C++ for OpenCL inherits rule from OpenCL C v2.0. 7858 // FIXME: Adding local AS in C++ for OpenCL might make sense. 7859 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 7860 NewVD->hasExternalStorage()) { 7861 if (!T->isSamplerT() && 7862 !(T.getAddressSpace() == LangAS::opencl_constant || 7863 (T.getAddressSpace() == LangAS::opencl_global && 7864 (getLangOpts().OpenCLVersion == 200 || 7865 getLangOpts().OpenCLCPlusPlus)))) { 7866 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 7867 if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus) 7868 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7869 << Scope << "global or constant"; 7870 else 7871 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7872 << Scope << "constant"; 7873 NewVD->setInvalidDecl(); 7874 return; 7875 } 7876 } else { 7877 if (T.getAddressSpace() == LangAS::opencl_global) { 7878 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7879 << 1 /*is any function*/ << "global"; 7880 NewVD->setInvalidDecl(); 7881 return; 7882 } 7883 if (T.getAddressSpace() == LangAS::opencl_constant || 7884 T.getAddressSpace() == LangAS::opencl_local) { 7885 FunctionDecl *FD = getCurFunctionDecl(); 7886 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables 7887 // in functions. 7888 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 7889 if (T.getAddressSpace() == LangAS::opencl_constant) 7890 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7891 << 0 /*non-kernel only*/ << "constant"; 7892 else 7893 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7894 << 0 /*non-kernel only*/ << "local"; 7895 NewVD->setInvalidDecl(); 7896 return; 7897 } 7898 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be 7899 // in the outermost scope of a kernel function. 7900 if (FD && FD->hasAttr<OpenCLKernelAttr>()) { 7901 if (!getCurScope()->isFunctionScope()) { 7902 if (T.getAddressSpace() == LangAS::opencl_constant) 7903 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7904 << "constant"; 7905 else 7906 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7907 << "local"; 7908 NewVD->setInvalidDecl(); 7909 return; 7910 } 7911 } 7912 } else if (T.getAddressSpace() != LangAS::opencl_private && 7913 // If we are parsing a template we didn't deduce an addr 7914 // space yet. 7915 T.getAddressSpace() != LangAS::Default) { 7916 // Do not allow other address spaces on automatic variable. 7917 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; 7918 NewVD->setInvalidDecl(); 7919 return; 7920 } 7921 } 7922 } 7923 7924 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 7925 && !NewVD->hasAttr<BlocksAttr>()) { 7926 if (getLangOpts().getGC() != LangOptions::NonGC) 7927 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 7928 else { 7929 assert(!getLangOpts().ObjCAutoRefCount); 7930 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 7931 } 7932 } 7933 7934 bool isVM = T->isVariablyModifiedType(); 7935 if (isVM || NewVD->hasAttr<CleanupAttr>() || 7936 NewVD->hasAttr<BlocksAttr>()) 7937 setFunctionHasBranchProtectedScope(); 7938 7939 if ((isVM && NewVD->hasLinkage()) || 7940 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 7941 bool SizeIsNegative; 7942 llvm::APSInt Oversized; 7943 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 7944 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized); 7945 QualType FixedT; 7946 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType()) 7947 FixedT = FixedTInfo->getType(); 7948 else if (FixedTInfo) { 7949 // Type and type-as-written are canonically different. We need to fix up 7950 // both types separately. 7951 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 7952 Oversized); 7953 } 7954 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) { 7955 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 7956 // FIXME: This won't give the correct result for 7957 // int a[10][n]; 7958 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 7959 7960 if (NewVD->isFileVarDecl()) 7961 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 7962 << SizeRange; 7963 else if (NewVD->isStaticLocal()) 7964 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 7965 << SizeRange; 7966 else 7967 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 7968 << SizeRange; 7969 NewVD->setInvalidDecl(); 7970 return; 7971 } 7972 7973 if (!FixedTInfo) { 7974 if (NewVD->isFileVarDecl()) 7975 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 7976 else 7977 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 7978 NewVD->setInvalidDecl(); 7979 return; 7980 } 7981 7982 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 7983 NewVD->setType(FixedT); 7984 NewVD->setTypeSourceInfo(FixedTInfo); 7985 } 7986 7987 if (T->isVoidType()) { 7988 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 7989 // of objects and functions. 7990 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 7991 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 7992 << T; 7993 NewVD->setInvalidDecl(); 7994 return; 7995 } 7996 } 7997 7998 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 7999 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 8000 NewVD->setInvalidDecl(); 8001 return; 8002 } 8003 8004 if (!NewVD->hasLocalStorage() && T->isSizelessType()) { 8005 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T; 8006 NewVD->setInvalidDecl(); 8007 return; 8008 } 8009 8010 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 8011 Diag(NewVD->getLocation(), diag::err_block_on_vm); 8012 NewVD->setInvalidDecl(); 8013 return; 8014 } 8015 8016 if (NewVD->isConstexpr() && !T->isDependentType() && 8017 RequireLiteralType(NewVD->getLocation(), T, 8018 diag::err_constexpr_var_non_literal)) { 8019 NewVD->setInvalidDecl(); 8020 return; 8021 } 8022 } 8023 8024 /// Perform semantic checking on a newly-created variable 8025 /// declaration. 8026 /// 8027 /// This routine performs all of the type-checking required for a 8028 /// variable declaration once it has been built. It is used both to 8029 /// check variables after they have been parsed and their declarators 8030 /// have been translated into a declaration, and to check variables 8031 /// that have been instantiated from a template. 8032 /// 8033 /// Sets NewVD->isInvalidDecl() if an error was encountered. 8034 /// 8035 /// Returns true if the variable declaration is a redeclaration. 8036 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 8037 CheckVariableDeclarationType(NewVD); 8038 8039 // If the decl is already known invalid, don't check it. 8040 if (NewVD->isInvalidDecl()) 8041 return false; 8042 8043 // If we did not find anything by this name, look for a non-visible 8044 // extern "C" declaration with the same name. 8045 if (Previous.empty() && 8046 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 8047 Previous.setShadowed(); 8048 8049 if (!Previous.empty()) { 8050 MergeVarDecl(NewVD, Previous); 8051 return true; 8052 } 8053 return false; 8054 } 8055 8056 namespace { 8057 struct FindOverriddenMethod { 8058 Sema *S; 8059 CXXMethodDecl *Method; 8060 8061 /// Member lookup function that determines whether a given C++ 8062 /// method overrides a method in a base class, to be used with 8063 /// CXXRecordDecl::lookupInBases(). 8064 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 8065 RecordDecl *BaseRecord = 8066 Specifier->getType()->castAs<RecordType>()->getDecl(); 8067 8068 DeclarationName Name = Method->getDeclName(); 8069 8070 // FIXME: Do we care about other names here too? 8071 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8072 // We really want to find the base class destructor here. 8073 QualType T = S->Context.getTypeDeclType(BaseRecord); 8074 CanQualType CT = S->Context.getCanonicalType(T); 8075 8076 Name = S->Context.DeclarationNames.getCXXDestructorName(CT); 8077 } 8078 8079 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 8080 Path.Decls = Path.Decls.slice(1)) { 8081 NamedDecl *D = Path.Decls.front(); 8082 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 8083 if (MD->isVirtual() && 8084 !S->IsOverload( 8085 Method, MD, /*UseMemberUsingDeclRules=*/false, 8086 /*ConsiderCudaAttrs=*/true, 8087 // C++2a [class.virtual]p2 does not consider requires clauses 8088 // when overriding. 8089 /*ConsiderRequiresClauses=*/false)) 8090 return true; 8091 } 8092 } 8093 8094 return false; 8095 } 8096 }; 8097 } // end anonymous namespace 8098 8099 /// AddOverriddenMethods - See if a method overrides any in the base classes, 8100 /// and if so, check that it's a valid override and remember it. 8101 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 8102 // Look for methods in base classes that this method might override. 8103 CXXBasePaths Paths; 8104 FindOverriddenMethod FOM; 8105 FOM.Method = MD; 8106 FOM.S = this; 8107 bool AddedAny = false; 8108 if (DC->lookupInBases(FOM, Paths)) { 8109 for (auto *I : Paths.found_decls()) { 8110 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { 8111 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 8112 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 8113 !CheckOverridingFunctionAttributes(MD, OldMD) && 8114 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 8115 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 8116 AddedAny = true; 8117 } 8118 } 8119 } 8120 } 8121 8122 return AddedAny; 8123 } 8124 8125 namespace { 8126 // Struct for holding all of the extra arguments needed by 8127 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 8128 struct ActOnFDArgs { 8129 Scope *S; 8130 Declarator &D; 8131 MultiTemplateParamsArg TemplateParamLists; 8132 bool AddToScope; 8133 }; 8134 } // end anonymous namespace 8135 8136 namespace { 8137 8138 // Callback to only accept typo corrections that have a non-zero edit distance. 8139 // Also only accept corrections that have the same parent decl. 8140 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback { 8141 public: 8142 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 8143 CXXRecordDecl *Parent) 8144 : Context(Context), OriginalFD(TypoFD), 8145 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 8146 8147 bool ValidateCandidate(const TypoCorrection &candidate) override { 8148 if (candidate.getEditDistance() == 0) 8149 return false; 8150 8151 SmallVector<unsigned, 1> MismatchedParams; 8152 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 8153 CDeclEnd = candidate.end(); 8154 CDecl != CDeclEnd; ++CDecl) { 8155 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8156 8157 if (FD && !FD->hasBody() && 8158 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 8159 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 8160 CXXRecordDecl *Parent = MD->getParent(); 8161 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 8162 return true; 8163 } else if (!ExpectedParent) { 8164 return true; 8165 } 8166 } 8167 } 8168 8169 return false; 8170 } 8171 8172 std::unique_ptr<CorrectionCandidateCallback> clone() override { 8173 return std::make_unique<DifferentNameValidatorCCC>(*this); 8174 } 8175 8176 private: 8177 ASTContext &Context; 8178 FunctionDecl *OriginalFD; 8179 CXXRecordDecl *ExpectedParent; 8180 }; 8181 8182 } // end anonymous namespace 8183 8184 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { 8185 TypoCorrectedFunctionDefinitions.insert(F); 8186 } 8187 8188 /// Generate diagnostics for an invalid function redeclaration. 8189 /// 8190 /// This routine handles generating the diagnostic messages for an invalid 8191 /// function redeclaration, including finding possible similar declarations 8192 /// or performing typo correction if there are no previous declarations with 8193 /// the same name. 8194 /// 8195 /// Returns a NamedDecl iff typo correction was performed and substituting in 8196 /// the new declaration name does not cause new errors. 8197 static NamedDecl *DiagnoseInvalidRedeclaration( 8198 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 8199 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 8200 DeclarationName Name = NewFD->getDeclName(); 8201 DeclContext *NewDC = NewFD->getDeclContext(); 8202 SmallVector<unsigned, 1> MismatchedParams; 8203 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 8204 TypoCorrection Correction; 8205 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 8206 unsigned DiagMsg = 8207 IsLocalFriend ? diag::err_no_matching_local_friend : 8208 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match : 8209 diag::err_member_decl_does_not_match; 8210 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 8211 IsLocalFriend ? Sema::LookupLocalFriendName 8212 : Sema::LookupOrdinaryName, 8213 Sema::ForVisibleRedeclaration); 8214 8215 NewFD->setInvalidDecl(); 8216 if (IsLocalFriend) 8217 SemaRef.LookupName(Prev, S); 8218 else 8219 SemaRef.LookupQualifiedName(Prev, NewDC); 8220 assert(!Prev.isAmbiguous() && 8221 "Cannot have an ambiguity in previous-declaration lookup"); 8222 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 8223 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD, 8224 MD ? MD->getParent() : nullptr); 8225 if (!Prev.empty()) { 8226 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 8227 Func != FuncEnd; ++Func) { 8228 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 8229 if (FD && 8230 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8231 // Add 1 to the index so that 0 can mean the mismatch didn't 8232 // involve a parameter 8233 unsigned ParamNum = 8234 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 8235 NearMatches.push_back(std::make_pair(FD, ParamNum)); 8236 } 8237 } 8238 // If the qualified name lookup yielded nothing, try typo correction 8239 } else if ((Correction = SemaRef.CorrectTypo( 8240 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 8241 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery, 8242 IsLocalFriend ? nullptr : NewDC))) { 8243 // Set up everything for the call to ActOnFunctionDeclarator 8244 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 8245 ExtraArgs.D.getIdentifierLoc()); 8246 Previous.clear(); 8247 Previous.setLookupName(Correction.getCorrection()); 8248 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 8249 CDeclEnd = Correction.end(); 8250 CDecl != CDeclEnd; ++CDecl) { 8251 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8252 if (FD && !FD->hasBody() && 8253 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8254 Previous.addDecl(FD); 8255 } 8256 } 8257 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 8258 8259 NamedDecl *Result; 8260 // Retry building the function declaration with the new previous 8261 // declarations, and with errors suppressed. 8262 { 8263 // Trap errors. 8264 Sema::SFINAETrap Trap(SemaRef); 8265 8266 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 8267 // pieces need to verify the typo-corrected C++ declaration and hopefully 8268 // eliminate the need for the parameter pack ExtraArgs. 8269 Result = SemaRef.ActOnFunctionDeclarator( 8270 ExtraArgs.S, ExtraArgs.D, 8271 Correction.getCorrectionDecl()->getDeclContext(), 8272 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 8273 ExtraArgs.AddToScope); 8274 8275 if (Trap.hasErrorOccurred()) 8276 Result = nullptr; 8277 } 8278 8279 if (Result) { 8280 // Determine which correction we picked. 8281 Decl *Canonical = Result->getCanonicalDecl(); 8282 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 8283 I != E; ++I) 8284 if ((*I)->getCanonicalDecl() == Canonical) 8285 Correction.setCorrectionDecl(*I); 8286 8287 // Let Sema know about the correction. 8288 SemaRef.MarkTypoCorrectedFunctionDefinition(Result); 8289 SemaRef.diagnoseTypo( 8290 Correction, 8291 SemaRef.PDiag(IsLocalFriend 8292 ? diag::err_no_matching_local_friend_suggest 8293 : diag::err_member_decl_does_not_match_suggest) 8294 << Name << NewDC << IsDefinition); 8295 return Result; 8296 } 8297 8298 // Pretend the typo correction never occurred 8299 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 8300 ExtraArgs.D.getIdentifierLoc()); 8301 ExtraArgs.D.setRedeclaration(wasRedeclaration); 8302 Previous.clear(); 8303 Previous.setLookupName(Name); 8304 } 8305 8306 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 8307 << Name << NewDC << IsDefinition << NewFD->getLocation(); 8308 8309 bool NewFDisConst = false; 8310 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 8311 NewFDisConst = NewMD->isConst(); 8312 8313 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 8314 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 8315 NearMatch != NearMatchEnd; ++NearMatch) { 8316 FunctionDecl *FD = NearMatch->first; 8317 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 8318 bool FDisConst = MD && MD->isConst(); 8319 bool IsMember = MD || !IsLocalFriend; 8320 8321 // FIXME: These notes are poorly worded for the local friend case. 8322 if (unsigned Idx = NearMatch->second) { 8323 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 8324 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 8325 if (Loc.isInvalid()) Loc = FD->getLocation(); 8326 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 8327 : diag::note_local_decl_close_param_match) 8328 << Idx << FDParam->getType() 8329 << NewFD->getParamDecl(Idx - 1)->getType(); 8330 } else if (FDisConst != NewFDisConst) { 8331 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 8332 << NewFDisConst << FD->getSourceRange().getEnd(); 8333 } else 8334 SemaRef.Diag(FD->getLocation(), 8335 IsMember ? diag::note_member_def_close_match 8336 : diag::note_local_decl_close_match); 8337 } 8338 return nullptr; 8339 } 8340 8341 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 8342 switch (D.getDeclSpec().getStorageClassSpec()) { 8343 default: llvm_unreachable("Unknown storage class!"); 8344 case DeclSpec::SCS_auto: 8345 case DeclSpec::SCS_register: 8346 case DeclSpec::SCS_mutable: 8347 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8348 diag::err_typecheck_sclass_func); 8349 D.getMutableDeclSpec().ClearStorageClassSpecs(); 8350 D.setInvalidType(); 8351 break; 8352 case DeclSpec::SCS_unspecified: break; 8353 case DeclSpec::SCS_extern: 8354 if (D.getDeclSpec().isExternInLinkageSpec()) 8355 return SC_None; 8356 return SC_Extern; 8357 case DeclSpec::SCS_static: { 8358 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 8359 // C99 6.7.1p5: 8360 // The declaration of an identifier for a function that has 8361 // block scope shall have no explicit storage-class specifier 8362 // other than extern 8363 // See also (C++ [dcl.stc]p4). 8364 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8365 diag::err_static_block_func); 8366 break; 8367 } else 8368 return SC_Static; 8369 } 8370 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 8371 } 8372 8373 // No explicit storage class has already been returned 8374 return SC_None; 8375 } 8376 8377 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 8378 DeclContext *DC, QualType &R, 8379 TypeSourceInfo *TInfo, 8380 StorageClass SC, 8381 bool &IsVirtualOkay) { 8382 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 8383 DeclarationName Name = NameInfo.getName(); 8384 8385 FunctionDecl *NewFD = nullptr; 8386 bool isInline = D.getDeclSpec().isInlineSpecified(); 8387 8388 if (!SemaRef.getLangOpts().CPlusPlus) { 8389 // Determine whether the function was written with a 8390 // prototype. This true when: 8391 // - there is a prototype in the declarator, or 8392 // - the type R of the function is some kind of typedef or other non- 8393 // attributed reference to a type name (which eventually refers to a 8394 // function type). 8395 bool HasPrototype = 8396 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 8397 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 8398 8399 NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, 8400 R, TInfo, SC, isInline, HasPrototype, 8401 CSK_unspecified, 8402 /*TrailingRequiresClause=*/nullptr); 8403 if (D.isInvalidType()) 8404 NewFD->setInvalidDecl(); 8405 8406 return NewFD; 8407 } 8408 8409 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier(); 8410 8411 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 8412 if (ConstexprKind == CSK_constinit) { 8413 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(), 8414 diag::err_constexpr_wrong_decl_kind) 8415 << ConstexprKind; 8416 ConstexprKind = CSK_unspecified; 8417 D.getMutableDeclSpec().ClearConstexprSpec(); 8418 } 8419 Expr *TrailingRequiresClause = D.getTrailingRequiresClause(); 8420 8421 // Check that the return type is not an abstract class type. 8422 // For record types, this is done by the AbstractClassUsageDiagnoser once 8423 // the class has been completely parsed. 8424 if (!DC->isRecord() && 8425 SemaRef.RequireNonAbstractType( 8426 D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(), 8427 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 8428 D.setInvalidType(); 8429 8430 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 8431 // This is a C++ constructor declaration. 8432 assert(DC->isRecord() && 8433 "Constructors can only be declared in a member context"); 8434 8435 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 8436 return CXXConstructorDecl::Create( 8437 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8438 TInfo, ExplicitSpecifier, isInline, 8439 /*isImplicitlyDeclared=*/false, ConstexprKind, InheritedConstructor(), 8440 TrailingRequiresClause); 8441 8442 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8443 // This is a C++ destructor declaration. 8444 if (DC->isRecord()) { 8445 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 8446 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 8447 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 8448 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo, 8449 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind, 8450 TrailingRequiresClause); 8451 8452 // If the destructor needs an implicit exception specification, set it 8453 // now. FIXME: It'd be nice to be able to create the right type to start 8454 // with, but the type needs to reference the destructor declaration. 8455 if (SemaRef.getLangOpts().CPlusPlus11) 8456 SemaRef.AdjustDestructorExceptionSpec(NewDD); 8457 8458 IsVirtualOkay = true; 8459 return NewDD; 8460 8461 } else { 8462 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 8463 D.setInvalidType(); 8464 8465 // Create a FunctionDecl to satisfy the function definition parsing 8466 // code path. 8467 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8468 D.getIdentifierLoc(), Name, R, TInfo, SC, 8469 isInline, 8470 /*hasPrototype=*/true, ConstexprKind, 8471 TrailingRequiresClause); 8472 } 8473 8474 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 8475 if (!DC->isRecord()) { 8476 SemaRef.Diag(D.getIdentifierLoc(), 8477 diag::err_conv_function_not_member); 8478 return nullptr; 8479 } 8480 8481 SemaRef.CheckConversionDeclarator(D, R, SC); 8482 if (D.isInvalidType()) 8483 return nullptr; 8484 8485 IsVirtualOkay = true; 8486 return CXXConversionDecl::Create( 8487 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8488 TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation(), 8489 TrailingRequiresClause); 8490 8491 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 8492 if (TrailingRequiresClause) 8493 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(), 8494 diag::err_trailing_requires_clause_on_deduction_guide) 8495 << TrailingRequiresClause->getSourceRange(); 8496 SemaRef.CheckDeductionGuideDeclarator(D, R, SC); 8497 8498 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8499 ExplicitSpecifier, NameInfo, R, TInfo, 8500 D.getEndLoc()); 8501 } else if (DC->isRecord()) { 8502 // If the name of the function is the same as the name of the record, 8503 // then this must be an invalid constructor that has a return type. 8504 // (The parser checks for a return type and makes the declarator a 8505 // constructor if it has no return type). 8506 if (Name.getAsIdentifierInfo() && 8507 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 8508 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 8509 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8510 << SourceRange(D.getIdentifierLoc()); 8511 return nullptr; 8512 } 8513 8514 // This is a C++ method declaration. 8515 CXXMethodDecl *Ret = CXXMethodDecl::Create( 8516 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8517 TInfo, SC, isInline, ConstexprKind, SourceLocation(), 8518 TrailingRequiresClause); 8519 IsVirtualOkay = !Ret->isStatic(); 8520 return Ret; 8521 } else { 8522 bool isFriend = 8523 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 8524 if (!isFriend && SemaRef.CurContext->isRecord()) 8525 return nullptr; 8526 8527 // Determine whether the function was written with a 8528 // prototype. This true when: 8529 // - we're in C++ (where every function has a prototype), 8530 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, 8531 R, TInfo, SC, isInline, true /*HasPrototype*/, 8532 ConstexprKind, TrailingRequiresClause); 8533 } 8534 } 8535 8536 enum OpenCLParamType { 8537 ValidKernelParam, 8538 PtrPtrKernelParam, 8539 PtrKernelParam, 8540 InvalidAddrSpacePtrKernelParam, 8541 InvalidKernelParam, 8542 RecordKernelParam 8543 }; 8544 8545 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) { 8546 // Size dependent types are just typedefs to normal integer types 8547 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to 8548 // integers other than by their names. 8549 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"}; 8550 8551 // Remove typedefs one by one until we reach a typedef 8552 // for a size dependent type. 8553 QualType DesugaredTy = Ty; 8554 do { 8555 ArrayRef<StringRef> Names(SizeTypeNames); 8556 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString()); 8557 if (Names.end() != Match) 8558 return true; 8559 8560 Ty = DesugaredTy; 8561 DesugaredTy = Ty.getSingleStepDesugaredType(C); 8562 } while (DesugaredTy != Ty); 8563 8564 return false; 8565 } 8566 8567 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 8568 if (PT->isPointerType()) { 8569 QualType PointeeType = PT->getPointeeType(); 8570 if (PointeeType->isPointerType()) 8571 return PtrPtrKernelParam; 8572 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 8573 PointeeType.getAddressSpace() == LangAS::opencl_private || 8574 PointeeType.getAddressSpace() == LangAS::Default) 8575 return InvalidAddrSpacePtrKernelParam; 8576 return PtrKernelParam; 8577 } 8578 8579 // OpenCL v1.2 s6.9.k: 8580 // Arguments to kernel functions in a program cannot be declared with the 8581 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8582 // uintptr_t or a struct and/or union that contain fields declared to be one 8583 // of these built-in scalar types. 8584 if (isOpenCLSizeDependentType(S.getASTContext(), PT)) 8585 return InvalidKernelParam; 8586 8587 if (PT->isImageType()) 8588 return PtrKernelParam; 8589 8590 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) 8591 return InvalidKernelParam; 8592 8593 // OpenCL extension spec v1.2 s9.5: 8594 // This extension adds support for half scalar and vector types as built-in 8595 // types that can be used for arithmetic operations, conversions etc. 8596 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType()) 8597 return InvalidKernelParam; 8598 8599 if (PT->isRecordType()) 8600 return RecordKernelParam; 8601 8602 // Look into an array argument to check if it has a forbidden type. 8603 if (PT->isArrayType()) { 8604 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType(); 8605 // Call ourself to check an underlying type of an array. Since the 8606 // getPointeeOrArrayElementType returns an innermost type which is not an 8607 // array, this recursive call only happens once. 8608 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0)); 8609 } 8610 8611 return ValidKernelParam; 8612 } 8613 8614 static void checkIsValidOpenCLKernelParameter( 8615 Sema &S, 8616 Declarator &D, 8617 ParmVarDecl *Param, 8618 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 8619 QualType PT = Param->getType(); 8620 8621 // Cache the valid types we encounter to avoid rechecking structs that are 8622 // used again 8623 if (ValidTypes.count(PT.getTypePtr())) 8624 return; 8625 8626 switch (getOpenCLKernelParameterType(S, PT)) { 8627 case PtrPtrKernelParam: 8628 // OpenCL v1.2 s6.9.a: 8629 // A kernel function argument cannot be declared as a 8630 // pointer to a pointer type. 8631 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 8632 D.setInvalidType(); 8633 return; 8634 8635 case InvalidAddrSpacePtrKernelParam: 8636 // OpenCL v1.0 s6.5: 8637 // __kernel function arguments declared to be a pointer of a type can point 8638 // to one of the following address spaces only : __global, __local or 8639 // __constant. 8640 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 8641 D.setInvalidType(); 8642 return; 8643 8644 // OpenCL v1.2 s6.9.k: 8645 // Arguments to kernel functions in a program cannot be declared with the 8646 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8647 // uintptr_t or a struct and/or union that contain fields declared to be 8648 // one of these built-in scalar types. 8649 8650 case InvalidKernelParam: 8651 // OpenCL v1.2 s6.8 n: 8652 // A kernel function argument cannot be declared 8653 // of event_t type. 8654 // Do not diagnose half type since it is diagnosed as invalid argument 8655 // type for any function elsewhere. 8656 if (!PT->isHalfType()) { 8657 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8658 8659 // Explain what typedefs are involved. 8660 const TypedefType *Typedef = nullptr; 8661 while ((Typedef = PT->getAs<TypedefType>())) { 8662 SourceLocation Loc = Typedef->getDecl()->getLocation(); 8663 // SourceLocation may be invalid for a built-in type. 8664 if (Loc.isValid()) 8665 S.Diag(Loc, diag::note_entity_declared_at) << PT; 8666 PT = Typedef->desugar(); 8667 } 8668 } 8669 8670 D.setInvalidType(); 8671 return; 8672 8673 case PtrKernelParam: 8674 case ValidKernelParam: 8675 ValidTypes.insert(PT.getTypePtr()); 8676 return; 8677 8678 case RecordKernelParam: 8679 break; 8680 } 8681 8682 // Track nested structs we will inspect 8683 SmallVector<const Decl *, 4> VisitStack; 8684 8685 // Track where we are in the nested structs. Items will migrate from 8686 // VisitStack to HistoryStack as we do the DFS for bad field. 8687 SmallVector<const FieldDecl *, 4> HistoryStack; 8688 HistoryStack.push_back(nullptr); 8689 8690 // At this point we already handled everything except of a RecordType or 8691 // an ArrayType of a RecordType. 8692 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type."); 8693 const RecordType *RecTy = 8694 PT->getPointeeOrArrayElementType()->getAs<RecordType>(); 8695 const RecordDecl *OrigRecDecl = RecTy->getDecl(); 8696 8697 VisitStack.push_back(RecTy->getDecl()); 8698 assert(VisitStack.back() && "First decl null?"); 8699 8700 do { 8701 const Decl *Next = VisitStack.pop_back_val(); 8702 if (!Next) { 8703 assert(!HistoryStack.empty()); 8704 // Found a marker, we have gone up a level 8705 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 8706 ValidTypes.insert(Hist->getType().getTypePtr()); 8707 8708 continue; 8709 } 8710 8711 // Adds everything except the original parameter declaration (which is not a 8712 // field itself) to the history stack. 8713 const RecordDecl *RD; 8714 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 8715 HistoryStack.push_back(Field); 8716 8717 QualType FieldTy = Field->getType(); 8718 // Other field types (known to be valid or invalid) are handled while we 8719 // walk around RecordDecl::fields(). 8720 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) && 8721 "Unexpected type."); 8722 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType(); 8723 8724 RD = FieldRecTy->castAs<RecordType>()->getDecl(); 8725 } else { 8726 RD = cast<RecordDecl>(Next); 8727 } 8728 8729 // Add a null marker so we know when we've gone back up a level 8730 VisitStack.push_back(nullptr); 8731 8732 for (const auto *FD : RD->fields()) { 8733 QualType QT = FD->getType(); 8734 8735 if (ValidTypes.count(QT.getTypePtr())) 8736 continue; 8737 8738 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 8739 if (ParamType == ValidKernelParam) 8740 continue; 8741 8742 if (ParamType == RecordKernelParam) { 8743 VisitStack.push_back(FD); 8744 continue; 8745 } 8746 8747 // OpenCL v1.2 s6.9.p: 8748 // Arguments to kernel functions that are declared to be a struct or union 8749 // do not allow OpenCL objects to be passed as elements of the struct or 8750 // union. 8751 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 8752 ParamType == InvalidAddrSpacePtrKernelParam) { 8753 S.Diag(Param->getLocation(), 8754 diag::err_record_with_pointers_kernel_param) 8755 << PT->isUnionType() 8756 << PT; 8757 } else { 8758 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8759 } 8760 8761 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type) 8762 << OrigRecDecl->getDeclName(); 8763 8764 // We have an error, now let's go back up through history and show where 8765 // the offending field came from 8766 for (ArrayRef<const FieldDecl *>::const_iterator 8767 I = HistoryStack.begin() + 1, 8768 E = HistoryStack.end(); 8769 I != E; ++I) { 8770 const FieldDecl *OuterField = *I; 8771 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 8772 << OuterField->getType(); 8773 } 8774 8775 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 8776 << QT->isPointerType() 8777 << QT; 8778 D.setInvalidType(); 8779 return; 8780 } 8781 } while (!VisitStack.empty()); 8782 } 8783 8784 /// Find the DeclContext in which a tag is implicitly declared if we see an 8785 /// elaborated type specifier in the specified context, and lookup finds 8786 /// nothing. 8787 static DeclContext *getTagInjectionContext(DeclContext *DC) { 8788 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 8789 DC = DC->getParent(); 8790 return DC; 8791 } 8792 8793 /// Find the Scope in which a tag is implicitly declared if we see an 8794 /// elaborated type specifier in the specified context, and lookup finds 8795 /// nothing. 8796 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 8797 while (S->isClassScope() || 8798 (LangOpts.CPlusPlus && 8799 S->isFunctionPrototypeScope()) || 8800 ((S->getFlags() & Scope::DeclScope) == 0) || 8801 (S->getEntity() && S->getEntity()->isTransparentContext())) 8802 S = S->getParent(); 8803 return S; 8804 } 8805 8806 NamedDecl* 8807 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 8808 TypeSourceInfo *TInfo, LookupResult &Previous, 8809 MultiTemplateParamsArg TemplateParamListsRef, 8810 bool &AddToScope) { 8811 QualType R = TInfo->getType(); 8812 8813 assert(R->isFunctionType()); 8814 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr()) 8815 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call); 8816 8817 SmallVector<TemplateParameterList *, 4> TemplateParamLists; 8818 for (TemplateParameterList *TPL : TemplateParamListsRef) 8819 TemplateParamLists.push_back(TPL); 8820 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) { 8821 if (!TemplateParamLists.empty() && 8822 Invented->getDepth() == TemplateParamLists.back()->getDepth()) 8823 TemplateParamLists.back() = Invented; 8824 else 8825 TemplateParamLists.push_back(Invented); 8826 } 8827 8828 // TODO: consider using NameInfo for diagnostic. 8829 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 8830 DeclarationName Name = NameInfo.getName(); 8831 StorageClass SC = getFunctionStorageClass(*this, D); 8832 8833 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 8834 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 8835 diag::err_invalid_thread) 8836 << DeclSpec::getSpecifierName(TSCS); 8837 8838 if (D.isFirstDeclarationOfMember()) 8839 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 8840 D.getIdentifierLoc()); 8841 8842 bool isFriend = false; 8843 FunctionTemplateDecl *FunctionTemplate = nullptr; 8844 bool isMemberSpecialization = false; 8845 bool isFunctionTemplateSpecialization = false; 8846 8847 bool isDependentClassScopeExplicitSpecialization = false; 8848 bool HasExplicitTemplateArgs = false; 8849 TemplateArgumentListInfo TemplateArgs; 8850 8851 bool isVirtualOkay = false; 8852 8853 DeclContext *OriginalDC = DC; 8854 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 8855 8856 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 8857 isVirtualOkay); 8858 if (!NewFD) return nullptr; 8859 8860 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 8861 NewFD->setTopLevelDeclInObjCContainer(); 8862 8863 // Set the lexical context. If this is a function-scope declaration, or has a 8864 // C++ scope specifier, or is the object of a friend declaration, the lexical 8865 // context will be different from the semantic context. 8866 NewFD->setLexicalDeclContext(CurContext); 8867 8868 if (IsLocalExternDecl) 8869 NewFD->setLocalExternDecl(); 8870 8871 if (getLangOpts().CPlusPlus) { 8872 bool isInline = D.getDeclSpec().isInlineSpecified(); 8873 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 8874 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier(); 8875 isFriend = D.getDeclSpec().isFriendSpecified(); 8876 if (isFriend && !isInline && D.isFunctionDefinition()) { 8877 // C++ [class.friend]p5 8878 // A function can be defined in a friend declaration of a 8879 // class . . . . Such a function is implicitly inline. 8880 NewFD->setImplicitlyInline(); 8881 } 8882 8883 // If this is a method defined in an __interface, and is not a constructor 8884 // or an overloaded operator, then set the pure flag (isVirtual will already 8885 // return true). 8886 if (const CXXRecordDecl *Parent = 8887 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 8888 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 8889 NewFD->setPure(true); 8890 8891 // C++ [class.union]p2 8892 // A union can have member functions, but not virtual functions. 8893 if (isVirtual && Parent->isUnion()) 8894 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 8895 } 8896 8897 SetNestedNameSpecifier(*this, NewFD, D); 8898 isMemberSpecialization = false; 8899 isFunctionTemplateSpecialization = false; 8900 if (D.isInvalidType()) 8901 NewFD->setInvalidDecl(); 8902 8903 // Match up the template parameter lists with the scope specifier, then 8904 // determine whether we have a template or a template specialization. 8905 bool Invalid = false; 8906 TemplateParameterList *TemplateParams = 8907 MatchTemplateParametersToScopeSpecifier( 8908 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 8909 D.getCXXScopeSpec(), 8910 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 8911 ? D.getName().TemplateId 8912 : nullptr, 8913 TemplateParamLists, isFriend, isMemberSpecialization, 8914 Invalid); 8915 if (TemplateParams) { 8916 if (TemplateParams->size() > 0) { 8917 // This is a function template 8918 8919 // Check that we can declare a template here. 8920 if (CheckTemplateDeclScope(S, TemplateParams)) 8921 NewFD->setInvalidDecl(); 8922 8923 // A destructor cannot be a template. 8924 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8925 Diag(NewFD->getLocation(), diag::err_destructor_template); 8926 NewFD->setInvalidDecl(); 8927 } 8928 8929 // If we're adding a template to a dependent context, we may need to 8930 // rebuilding some of the types used within the template parameter list, 8931 // now that we know what the current instantiation is. 8932 if (DC->isDependentContext()) { 8933 ContextRAII SavedContext(*this, DC); 8934 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 8935 Invalid = true; 8936 } 8937 8938 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 8939 NewFD->getLocation(), 8940 Name, TemplateParams, 8941 NewFD); 8942 FunctionTemplate->setLexicalDeclContext(CurContext); 8943 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 8944 8945 // For source fidelity, store the other template param lists. 8946 if (TemplateParamLists.size() > 1) { 8947 NewFD->setTemplateParameterListsInfo(Context, 8948 ArrayRef<TemplateParameterList *>(TemplateParamLists) 8949 .drop_back(1)); 8950 } 8951 } else { 8952 // This is a function template specialization. 8953 isFunctionTemplateSpecialization = true; 8954 // For source fidelity, store all the template param lists. 8955 if (TemplateParamLists.size() > 0) 8956 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8957 8958 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 8959 if (isFriend) { 8960 // We want to remove the "template<>", found here. 8961 SourceRange RemoveRange = TemplateParams->getSourceRange(); 8962 8963 // If we remove the template<> and the name is not a 8964 // template-id, we're actually silently creating a problem: 8965 // the friend declaration will refer to an untemplated decl, 8966 // and clearly the user wants a template specialization. So 8967 // we need to insert '<>' after the name. 8968 SourceLocation InsertLoc; 8969 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 8970 InsertLoc = D.getName().getSourceRange().getEnd(); 8971 InsertLoc = getLocForEndOfToken(InsertLoc); 8972 } 8973 8974 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 8975 << Name << RemoveRange 8976 << FixItHint::CreateRemoval(RemoveRange) 8977 << FixItHint::CreateInsertion(InsertLoc, "<>"); 8978 } 8979 } 8980 } else { 8981 // All template param lists were matched against the scope specifier: 8982 // this is NOT (an explicit specialization of) a template. 8983 if (TemplateParamLists.size() > 0) 8984 // For source fidelity, store all the template param lists. 8985 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8986 } 8987 8988 if (Invalid) { 8989 NewFD->setInvalidDecl(); 8990 if (FunctionTemplate) 8991 FunctionTemplate->setInvalidDecl(); 8992 } 8993 8994 // C++ [dcl.fct.spec]p5: 8995 // The virtual specifier shall only be used in declarations of 8996 // nonstatic class member functions that appear within a 8997 // member-specification of a class declaration; see 10.3. 8998 // 8999 if (isVirtual && !NewFD->isInvalidDecl()) { 9000 if (!isVirtualOkay) { 9001 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9002 diag::err_virtual_non_function); 9003 } else if (!CurContext->isRecord()) { 9004 // 'virtual' was specified outside of the class. 9005 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9006 diag::err_virtual_out_of_class) 9007 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 9008 } else if (NewFD->getDescribedFunctionTemplate()) { 9009 // C++ [temp.mem]p3: 9010 // A member function template shall not be virtual. 9011 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9012 diag::err_virtual_member_function_template) 9013 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 9014 } else { 9015 // Okay: Add virtual to the method. 9016 NewFD->setVirtualAsWritten(true); 9017 } 9018 9019 if (getLangOpts().CPlusPlus14 && 9020 NewFD->getReturnType()->isUndeducedType()) 9021 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 9022 } 9023 9024 if (getLangOpts().CPlusPlus14 && 9025 (NewFD->isDependentContext() || 9026 (isFriend && CurContext->isDependentContext())) && 9027 NewFD->getReturnType()->isUndeducedType()) { 9028 // If the function template is referenced directly (for instance, as a 9029 // member of the current instantiation), pretend it has a dependent type. 9030 // This is not really justified by the standard, but is the only sane 9031 // thing to do. 9032 // FIXME: For a friend function, we have not marked the function as being 9033 // a friend yet, so 'isDependentContext' on the FD doesn't work. 9034 const FunctionProtoType *FPT = 9035 NewFD->getType()->castAs<FunctionProtoType>(); 9036 QualType Result = 9037 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 9038 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 9039 FPT->getExtProtoInfo())); 9040 } 9041 9042 // C++ [dcl.fct.spec]p3: 9043 // The inline specifier shall not appear on a block scope function 9044 // declaration. 9045 if (isInline && !NewFD->isInvalidDecl()) { 9046 if (CurContext->isFunctionOrMethod()) { 9047 // 'inline' is not allowed on block scope function declaration. 9048 Diag(D.getDeclSpec().getInlineSpecLoc(), 9049 diag::err_inline_declaration_block_scope) << Name 9050 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 9051 } 9052 } 9053 9054 // C++ [dcl.fct.spec]p6: 9055 // The explicit specifier shall be used only in the declaration of a 9056 // constructor or conversion function within its class definition; 9057 // see 12.3.1 and 12.3.2. 9058 if (hasExplicit && !NewFD->isInvalidDecl() && 9059 !isa<CXXDeductionGuideDecl>(NewFD)) { 9060 if (!CurContext->isRecord()) { 9061 // 'explicit' was specified outside of the class. 9062 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9063 diag::err_explicit_out_of_class) 9064 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9065 } else if (!isa<CXXConstructorDecl>(NewFD) && 9066 !isa<CXXConversionDecl>(NewFD)) { 9067 // 'explicit' was specified on a function that wasn't a constructor 9068 // or conversion function. 9069 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9070 diag::err_explicit_non_ctor_or_conv_function) 9071 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9072 } 9073 } 9074 9075 if (ConstexprSpecKind ConstexprKind = 9076 D.getDeclSpec().getConstexprSpecifier()) { 9077 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 9078 // are implicitly inline. 9079 NewFD->setImplicitlyInline(); 9080 9081 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 9082 // be either constructors or to return a literal type. Therefore, 9083 // destructors cannot be declared constexpr. 9084 if (isa<CXXDestructorDecl>(NewFD) && 9085 (!getLangOpts().CPlusPlus20 || ConstexprKind == CSK_consteval)) { 9086 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor) 9087 << ConstexprKind; 9088 NewFD->setConstexprKind(getLangOpts().CPlusPlus20 ? CSK_unspecified : CSK_constexpr); 9089 } 9090 // C++20 [dcl.constexpr]p2: An allocation function, or a 9091 // deallocation function shall not be declared with the consteval 9092 // specifier. 9093 if (ConstexprKind == CSK_consteval && 9094 (NewFD->getOverloadedOperator() == OO_New || 9095 NewFD->getOverloadedOperator() == OO_Array_New || 9096 NewFD->getOverloadedOperator() == OO_Delete || 9097 NewFD->getOverloadedOperator() == OO_Array_Delete)) { 9098 Diag(D.getDeclSpec().getConstexprSpecLoc(), 9099 diag::err_invalid_consteval_decl_kind) 9100 << NewFD; 9101 NewFD->setConstexprKind(CSK_constexpr); 9102 } 9103 } 9104 9105 // If __module_private__ was specified, mark the function accordingly. 9106 if (D.getDeclSpec().isModulePrivateSpecified()) { 9107 if (isFunctionTemplateSpecialization) { 9108 SourceLocation ModulePrivateLoc 9109 = D.getDeclSpec().getModulePrivateSpecLoc(); 9110 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 9111 << 0 9112 << FixItHint::CreateRemoval(ModulePrivateLoc); 9113 } else { 9114 NewFD->setModulePrivate(); 9115 if (FunctionTemplate) 9116 FunctionTemplate->setModulePrivate(); 9117 } 9118 } 9119 9120 if (isFriend) { 9121 if (FunctionTemplate) { 9122 FunctionTemplate->setObjectOfFriendDecl(); 9123 FunctionTemplate->setAccess(AS_public); 9124 } 9125 NewFD->setObjectOfFriendDecl(); 9126 NewFD->setAccess(AS_public); 9127 } 9128 9129 // If a function is defined as defaulted or deleted, mark it as such now. 9130 // We'll do the relevant checks on defaulted / deleted functions later. 9131 switch (D.getFunctionDefinitionKind()) { 9132 case FDK_Declaration: 9133 case FDK_Definition: 9134 break; 9135 9136 case FDK_Defaulted: 9137 NewFD->setDefaulted(); 9138 break; 9139 9140 case FDK_Deleted: 9141 NewFD->setDeletedAsWritten(); 9142 break; 9143 } 9144 9145 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 9146 D.isFunctionDefinition()) { 9147 // C++ [class.mfct]p2: 9148 // A member function may be defined (8.4) in its class definition, in 9149 // which case it is an inline member function (7.1.2) 9150 NewFD->setImplicitlyInline(); 9151 } 9152 9153 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 9154 !CurContext->isRecord()) { 9155 // C++ [class.static]p1: 9156 // A data or function member of a class may be declared static 9157 // in a class definition, in which case it is a static member of 9158 // the class. 9159 9160 // Complain about the 'static' specifier if it's on an out-of-line 9161 // member function definition. 9162 9163 // MSVC permits the use of a 'static' storage specifier on an out-of-line 9164 // member function template declaration and class member template 9165 // declaration (MSVC versions before 2015), warn about this. 9166 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 9167 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 9168 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) || 9169 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate())) 9170 ? diag::ext_static_out_of_line : diag::err_static_out_of_line) 9171 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 9172 } 9173 9174 // C++11 [except.spec]p15: 9175 // A deallocation function with no exception-specification is treated 9176 // as if it were specified with noexcept(true). 9177 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 9178 if ((Name.getCXXOverloadedOperator() == OO_Delete || 9179 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 9180 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 9181 NewFD->setType(Context.getFunctionType( 9182 FPT->getReturnType(), FPT->getParamTypes(), 9183 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 9184 } 9185 9186 // Filter out previous declarations that don't match the scope. 9187 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 9188 D.getCXXScopeSpec().isNotEmpty() || 9189 isMemberSpecialization || 9190 isFunctionTemplateSpecialization); 9191 9192 // Handle GNU asm-label extension (encoded as an attribute). 9193 if (Expr *E = (Expr*) D.getAsmLabel()) { 9194 // The parser guarantees this is a string. 9195 StringLiteral *SE = cast<StringLiteral>(E); 9196 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(), 9197 /*IsLiteralLabel=*/true, 9198 SE->getStrTokenLoc(0))); 9199 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 9200 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 9201 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 9202 if (I != ExtnameUndeclaredIdentifiers.end()) { 9203 if (isDeclExternC(NewFD)) { 9204 NewFD->addAttr(I->second); 9205 ExtnameUndeclaredIdentifiers.erase(I); 9206 } else 9207 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 9208 << /*Variable*/0 << NewFD; 9209 } 9210 } 9211 9212 // Copy the parameter declarations from the declarator D to the function 9213 // declaration NewFD, if they are available. First scavenge them into Params. 9214 SmallVector<ParmVarDecl*, 16> Params; 9215 unsigned FTIIdx; 9216 if (D.isFunctionDeclarator(FTIIdx)) { 9217 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 9218 9219 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 9220 // function that takes no arguments, not a function that takes a 9221 // single void argument. 9222 // We let through "const void" here because Sema::GetTypeForDeclarator 9223 // already checks for that case. 9224 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 9225 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 9226 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 9227 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 9228 Param->setDeclContext(NewFD); 9229 Params.push_back(Param); 9230 9231 if (Param->isInvalidDecl()) 9232 NewFD->setInvalidDecl(); 9233 } 9234 } 9235 9236 if (!getLangOpts().CPlusPlus) { 9237 // In C, find all the tag declarations from the prototype and move them 9238 // into the function DeclContext. Remove them from the surrounding tag 9239 // injection context of the function, which is typically but not always 9240 // the TU. 9241 DeclContext *PrototypeTagContext = 9242 getTagInjectionContext(NewFD->getLexicalDeclContext()); 9243 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 9244 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 9245 9246 // We don't want to reparent enumerators. Look at their parent enum 9247 // instead. 9248 if (!TD) { 9249 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 9250 TD = cast<EnumDecl>(ECD->getDeclContext()); 9251 } 9252 if (!TD) 9253 continue; 9254 DeclContext *TagDC = TD->getLexicalDeclContext(); 9255 if (!TagDC->containsDecl(TD)) 9256 continue; 9257 TagDC->removeDecl(TD); 9258 TD->setDeclContext(NewFD); 9259 NewFD->addDecl(TD); 9260 9261 // Preserve the lexical DeclContext if it is not the surrounding tag 9262 // injection context of the FD. In this example, the semantic context of 9263 // E will be f and the lexical context will be S, while both the 9264 // semantic and lexical contexts of S will be f: 9265 // void f(struct S { enum E { a } f; } s); 9266 if (TagDC != PrototypeTagContext) 9267 TD->setLexicalDeclContext(TagDC); 9268 } 9269 } 9270 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 9271 // When we're declaring a function with a typedef, typeof, etc as in the 9272 // following example, we'll need to synthesize (unnamed) 9273 // parameters for use in the declaration. 9274 // 9275 // @code 9276 // typedef void fn(int); 9277 // fn f; 9278 // @endcode 9279 9280 // Synthesize a parameter for each argument type. 9281 for (const auto &AI : FT->param_types()) { 9282 ParmVarDecl *Param = 9283 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 9284 Param->setScopeInfo(0, Params.size()); 9285 Params.push_back(Param); 9286 } 9287 } else { 9288 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 9289 "Should not need args for typedef of non-prototype fn"); 9290 } 9291 9292 // Finally, we know we have the right number of parameters, install them. 9293 NewFD->setParams(Params); 9294 9295 if (D.getDeclSpec().isNoreturnSpecified()) 9296 NewFD->addAttr(C11NoReturnAttr::Create(Context, 9297 D.getDeclSpec().getNoreturnSpecLoc(), 9298 AttributeCommonInfo::AS_Keyword)); 9299 9300 // Functions returning a variably modified type violate C99 6.7.5.2p2 9301 // because all functions have linkage. 9302 if (!NewFD->isInvalidDecl() && 9303 NewFD->getReturnType()->isVariablyModifiedType()) { 9304 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 9305 NewFD->setInvalidDecl(); 9306 } 9307 9308 // Apply an implicit SectionAttr if '#pragma clang section text' is active 9309 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && 9310 !NewFD->hasAttr<SectionAttr>()) 9311 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit( 9312 Context, PragmaClangTextSection.SectionName, 9313 PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma)); 9314 9315 // Apply an implicit SectionAttr if #pragma code_seg is active. 9316 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 9317 !NewFD->hasAttr<SectionAttr>()) { 9318 NewFD->addAttr(SectionAttr::CreateImplicit( 9319 Context, CodeSegStack.CurrentValue->getString(), 9320 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 9321 SectionAttr::Declspec_allocate)); 9322 if (UnifySection(CodeSegStack.CurrentValue->getString(), 9323 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 9324 ASTContext::PSF_Read, 9325 NewFD)) 9326 NewFD->dropAttr<SectionAttr>(); 9327 } 9328 9329 // Apply an implicit CodeSegAttr from class declspec or 9330 // apply an implicit SectionAttr from #pragma code_seg if active. 9331 if (!NewFD->hasAttr<CodeSegAttr>()) { 9332 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD, 9333 D.isFunctionDefinition())) { 9334 NewFD->addAttr(SAttr); 9335 } 9336 } 9337 9338 // Handle attributes. 9339 ProcessDeclAttributes(S, NewFD, D); 9340 9341 if (getLangOpts().OpenCL) { 9342 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 9343 // type declaration will generate a compilation error. 9344 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); 9345 if (AddressSpace != LangAS::Default) { 9346 Diag(NewFD->getLocation(), 9347 diag::err_opencl_return_value_with_address_space); 9348 NewFD->setInvalidDecl(); 9349 } 9350 } 9351 9352 if (!getLangOpts().CPlusPlus) { 9353 // Perform semantic checking on the function declaration. 9354 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9355 CheckMain(NewFD, D.getDeclSpec()); 9356 9357 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9358 CheckMSVCRTEntryPoint(NewFD); 9359 9360 if (!NewFD->isInvalidDecl()) 9361 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9362 isMemberSpecialization)); 9363 else if (!Previous.empty()) 9364 // Recover gracefully from an invalid redeclaration. 9365 D.setRedeclaration(true); 9366 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9367 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9368 "previous declaration set still overloaded"); 9369 9370 // Diagnose no-prototype function declarations with calling conventions that 9371 // don't support variadic calls. Only do this in C and do it after merging 9372 // possibly prototyped redeclarations. 9373 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 9374 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 9375 CallingConv CC = FT->getExtInfo().getCC(); 9376 if (!supportsVariadicCall(CC)) { 9377 // Windows system headers sometimes accidentally use stdcall without 9378 // (void) parameters, so we relax this to a warning. 9379 int DiagID = 9380 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 9381 Diag(NewFD->getLocation(), DiagID) 9382 << FunctionType::getNameForCallConv(CC); 9383 } 9384 } 9385 9386 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() || 9387 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion()) 9388 checkNonTrivialCUnion(NewFD->getReturnType(), 9389 NewFD->getReturnTypeSourceRange().getBegin(), 9390 NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy); 9391 } else { 9392 // C++11 [replacement.functions]p3: 9393 // The program's definitions shall not be specified as inline. 9394 // 9395 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 9396 // 9397 // Suppress the diagnostic if the function is __attribute__((used)), since 9398 // that forces an external definition to be emitted. 9399 if (D.getDeclSpec().isInlineSpecified() && 9400 NewFD->isReplaceableGlobalAllocationFunction() && 9401 !NewFD->hasAttr<UsedAttr>()) 9402 Diag(D.getDeclSpec().getInlineSpecLoc(), 9403 diag::ext_operator_new_delete_declared_inline) 9404 << NewFD->getDeclName(); 9405 9406 // If the declarator is a template-id, translate the parser's template 9407 // argument list into our AST format. 9408 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 9409 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 9410 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 9411 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 9412 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 9413 TemplateId->NumArgs); 9414 translateTemplateArguments(TemplateArgsPtr, 9415 TemplateArgs); 9416 9417 HasExplicitTemplateArgs = true; 9418 9419 if (NewFD->isInvalidDecl()) { 9420 HasExplicitTemplateArgs = false; 9421 } else if (FunctionTemplate) { 9422 // Function template with explicit template arguments. 9423 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 9424 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 9425 9426 HasExplicitTemplateArgs = false; 9427 } else { 9428 assert((isFunctionTemplateSpecialization || 9429 D.getDeclSpec().isFriendSpecified()) && 9430 "should have a 'template<>' for this decl"); 9431 // "friend void foo<>(int);" is an implicit specialization decl. 9432 isFunctionTemplateSpecialization = true; 9433 } 9434 } else if (isFriend && isFunctionTemplateSpecialization) { 9435 // This combination is only possible in a recovery case; the user 9436 // wrote something like: 9437 // template <> friend void foo(int); 9438 // which we're recovering from as if the user had written: 9439 // friend void foo<>(int); 9440 // Go ahead and fake up a template id. 9441 HasExplicitTemplateArgs = true; 9442 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 9443 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 9444 } 9445 9446 // We do not add HD attributes to specializations here because 9447 // they may have different constexpr-ness compared to their 9448 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 9449 // may end up with different effective targets. Instead, a 9450 // specialization inherits its target attributes from its template 9451 // in the CheckFunctionTemplateSpecialization() call below. 9452 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization) 9453 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 9454 9455 // If it's a friend (and only if it's a friend), it's possible 9456 // that either the specialized function type or the specialized 9457 // template is dependent, and therefore matching will fail. In 9458 // this case, don't check the specialization yet. 9459 bool InstantiationDependent = false; 9460 if (isFunctionTemplateSpecialization && isFriend && 9461 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 9462 TemplateSpecializationType::anyDependentTemplateArguments( 9463 TemplateArgs, 9464 InstantiationDependent))) { 9465 assert(HasExplicitTemplateArgs && 9466 "friend function specialization without template args"); 9467 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 9468 Previous)) 9469 NewFD->setInvalidDecl(); 9470 } else if (isFunctionTemplateSpecialization) { 9471 if (CurContext->isDependentContext() && CurContext->isRecord() 9472 && !isFriend) { 9473 isDependentClassScopeExplicitSpecialization = true; 9474 } else if (!NewFD->isInvalidDecl() && 9475 CheckFunctionTemplateSpecialization( 9476 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), 9477 Previous)) 9478 NewFD->setInvalidDecl(); 9479 9480 // C++ [dcl.stc]p1: 9481 // A storage-class-specifier shall not be specified in an explicit 9482 // specialization (14.7.3) 9483 FunctionTemplateSpecializationInfo *Info = 9484 NewFD->getTemplateSpecializationInfo(); 9485 if (Info && SC != SC_None) { 9486 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 9487 Diag(NewFD->getLocation(), 9488 diag::err_explicit_specialization_inconsistent_storage_class) 9489 << SC 9490 << FixItHint::CreateRemoval( 9491 D.getDeclSpec().getStorageClassSpecLoc()); 9492 9493 else 9494 Diag(NewFD->getLocation(), 9495 diag::ext_explicit_specialization_storage_class) 9496 << FixItHint::CreateRemoval( 9497 D.getDeclSpec().getStorageClassSpecLoc()); 9498 } 9499 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 9500 if (CheckMemberSpecialization(NewFD, Previous)) 9501 NewFD->setInvalidDecl(); 9502 } 9503 9504 // Perform semantic checking on the function declaration. 9505 if (!isDependentClassScopeExplicitSpecialization) { 9506 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9507 CheckMain(NewFD, D.getDeclSpec()); 9508 9509 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9510 CheckMSVCRTEntryPoint(NewFD); 9511 9512 if (!NewFD->isInvalidDecl()) 9513 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9514 isMemberSpecialization)); 9515 else if (!Previous.empty()) 9516 // Recover gracefully from an invalid redeclaration. 9517 D.setRedeclaration(true); 9518 } 9519 9520 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9521 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9522 "previous declaration set still overloaded"); 9523 9524 NamedDecl *PrincipalDecl = (FunctionTemplate 9525 ? cast<NamedDecl>(FunctionTemplate) 9526 : NewFD); 9527 9528 if (isFriend && NewFD->getPreviousDecl()) { 9529 AccessSpecifier Access = AS_public; 9530 if (!NewFD->isInvalidDecl()) 9531 Access = NewFD->getPreviousDecl()->getAccess(); 9532 9533 NewFD->setAccess(Access); 9534 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 9535 } 9536 9537 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 9538 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 9539 PrincipalDecl->setNonMemberOperator(); 9540 9541 // If we have a function template, check the template parameter 9542 // list. This will check and merge default template arguments. 9543 if (FunctionTemplate) { 9544 FunctionTemplateDecl *PrevTemplate = 9545 FunctionTemplate->getPreviousDecl(); 9546 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 9547 PrevTemplate ? PrevTemplate->getTemplateParameters() 9548 : nullptr, 9549 D.getDeclSpec().isFriendSpecified() 9550 ? (D.isFunctionDefinition() 9551 ? TPC_FriendFunctionTemplateDefinition 9552 : TPC_FriendFunctionTemplate) 9553 : (D.getCXXScopeSpec().isSet() && 9554 DC && DC->isRecord() && 9555 DC->isDependentContext()) 9556 ? TPC_ClassTemplateMember 9557 : TPC_FunctionTemplate); 9558 } 9559 9560 if (NewFD->isInvalidDecl()) { 9561 // Ignore all the rest of this. 9562 } else if (!D.isRedeclaration()) { 9563 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 9564 AddToScope }; 9565 // Fake up an access specifier if it's supposed to be a class member. 9566 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 9567 NewFD->setAccess(AS_public); 9568 9569 // Qualified decls generally require a previous declaration. 9570 if (D.getCXXScopeSpec().isSet()) { 9571 // ...with the major exception of templated-scope or 9572 // dependent-scope friend declarations. 9573 9574 // TODO: we currently also suppress this check in dependent 9575 // contexts because (1) the parameter depth will be off when 9576 // matching friend templates and (2) we might actually be 9577 // selecting a friend based on a dependent factor. But there 9578 // are situations where these conditions don't apply and we 9579 // can actually do this check immediately. 9580 // 9581 // Unless the scope is dependent, it's always an error if qualified 9582 // redeclaration lookup found nothing at all. Diagnose that now; 9583 // nothing will diagnose that error later. 9584 if (isFriend && 9585 (D.getCXXScopeSpec().getScopeRep()->isDependent() || 9586 (!Previous.empty() && CurContext->isDependentContext()))) { 9587 // ignore these 9588 } else { 9589 // The user tried to provide an out-of-line definition for a 9590 // function that is a member of a class or namespace, but there 9591 // was no such member function declared (C++ [class.mfct]p2, 9592 // C++ [namespace.memdef]p2). For example: 9593 // 9594 // class X { 9595 // void f() const; 9596 // }; 9597 // 9598 // void X::f() { } // ill-formed 9599 // 9600 // Complain about this problem, and attempt to suggest close 9601 // matches (e.g., those that differ only in cv-qualifiers and 9602 // whether the parameter types are references). 9603 9604 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9605 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 9606 AddToScope = ExtraArgs.AddToScope; 9607 return Result; 9608 } 9609 } 9610 9611 // Unqualified local friend declarations are required to resolve 9612 // to something. 9613 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 9614 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9615 *this, Previous, NewFD, ExtraArgs, true, S)) { 9616 AddToScope = ExtraArgs.AddToScope; 9617 return Result; 9618 } 9619 } 9620 } else if (!D.isFunctionDefinition() && 9621 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 9622 !isFriend && !isFunctionTemplateSpecialization && 9623 !isMemberSpecialization) { 9624 // An out-of-line member function declaration must also be a 9625 // definition (C++ [class.mfct]p2). 9626 // Note that this is not the case for explicit specializations of 9627 // function templates or member functions of class templates, per 9628 // C++ [temp.expl.spec]p2. We also allow these declarations as an 9629 // extension for compatibility with old SWIG code which likes to 9630 // generate them. 9631 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 9632 << D.getCXXScopeSpec().getRange(); 9633 } 9634 } 9635 9636 ProcessPragmaWeak(S, NewFD); 9637 checkAttributesAfterMerging(*this, *NewFD); 9638 9639 AddKnownFunctionAttributes(NewFD); 9640 9641 if (NewFD->hasAttr<OverloadableAttr>() && 9642 !NewFD->getType()->getAs<FunctionProtoType>()) { 9643 Diag(NewFD->getLocation(), 9644 diag::err_attribute_overloadable_no_prototype) 9645 << NewFD; 9646 9647 // Turn this into a variadic function with no parameters. 9648 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 9649 FunctionProtoType::ExtProtoInfo EPI( 9650 Context.getDefaultCallingConvention(true, false)); 9651 EPI.Variadic = true; 9652 EPI.ExtInfo = FT->getExtInfo(); 9653 9654 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 9655 NewFD->setType(R); 9656 } 9657 9658 // If there's a #pragma GCC visibility in scope, and this isn't a class 9659 // member, set the visibility of this function. 9660 if (!DC->isRecord() && NewFD->isExternallyVisible()) 9661 AddPushedVisibilityAttribute(NewFD); 9662 9663 // If there's a #pragma clang arc_cf_code_audited in scope, consider 9664 // marking the function. 9665 AddCFAuditedAttribute(NewFD); 9666 9667 // If this is a function definition, check if we have to apply optnone due to 9668 // a pragma. 9669 if(D.isFunctionDefinition()) 9670 AddRangeBasedOptnone(NewFD); 9671 9672 // If this is the first declaration of an extern C variable, update 9673 // the map of such variables. 9674 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 9675 isIncompleteDeclExternC(*this, NewFD)) 9676 RegisterLocallyScopedExternCDecl(NewFD, S); 9677 9678 // Set this FunctionDecl's range up to the right paren. 9679 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 9680 9681 if (D.isRedeclaration() && !Previous.empty()) { 9682 NamedDecl *Prev = Previous.getRepresentativeDecl(); 9683 checkDLLAttributeRedeclaration(*this, Prev, NewFD, 9684 isMemberSpecialization || 9685 isFunctionTemplateSpecialization, 9686 D.isFunctionDefinition()); 9687 } 9688 9689 if (getLangOpts().CUDA) { 9690 IdentifierInfo *II = NewFD->getIdentifier(); 9691 if (II && II->isStr(getCudaConfigureFuncName()) && 9692 !NewFD->isInvalidDecl() && 9693 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 9694 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 9695 Diag(NewFD->getLocation(), diag::err_config_scalar_return) 9696 << getCudaConfigureFuncName(); 9697 Context.setcudaConfigureCallDecl(NewFD); 9698 } 9699 9700 // Variadic functions, other than a *declaration* of printf, are not allowed 9701 // in device-side CUDA code, unless someone passed 9702 // -fcuda-allow-variadic-functions. 9703 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 9704 (NewFD->hasAttr<CUDADeviceAttr>() || 9705 NewFD->hasAttr<CUDAGlobalAttr>()) && 9706 !(II && II->isStr("printf") && NewFD->isExternC() && 9707 !D.isFunctionDefinition())) { 9708 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 9709 } 9710 } 9711 9712 MarkUnusedFileScopedDecl(NewFD); 9713 9714 9715 9716 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) { 9717 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 9718 if ((getLangOpts().OpenCLVersion >= 120) 9719 && (SC == SC_Static)) { 9720 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 9721 D.setInvalidType(); 9722 } 9723 9724 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 9725 if (!NewFD->getReturnType()->isVoidType()) { 9726 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 9727 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 9728 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 9729 : FixItHint()); 9730 D.setInvalidType(); 9731 } 9732 9733 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 9734 for (auto Param : NewFD->parameters()) 9735 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 9736 9737 if (getLangOpts().OpenCLCPlusPlus) { 9738 if (DC->isRecord()) { 9739 Diag(D.getIdentifierLoc(), diag::err_method_kernel); 9740 D.setInvalidType(); 9741 } 9742 if (FunctionTemplate) { 9743 Diag(D.getIdentifierLoc(), diag::err_template_kernel); 9744 D.setInvalidType(); 9745 } 9746 } 9747 } 9748 9749 if (getLangOpts().CPlusPlus) { 9750 if (FunctionTemplate) { 9751 if (NewFD->isInvalidDecl()) 9752 FunctionTemplate->setInvalidDecl(); 9753 return FunctionTemplate; 9754 } 9755 9756 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 9757 CompleteMemberSpecialization(NewFD, Previous); 9758 } 9759 9760 for (const ParmVarDecl *Param : NewFD->parameters()) { 9761 QualType PT = Param->getType(); 9762 9763 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 9764 // types. 9765 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 9766 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 9767 QualType ElemTy = PipeTy->getElementType(); 9768 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 9769 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 9770 D.setInvalidType(); 9771 } 9772 } 9773 } 9774 } 9775 9776 // Here we have an function template explicit specialization at class scope. 9777 // The actual specialization will be postponed to template instatiation 9778 // time via the ClassScopeFunctionSpecializationDecl node. 9779 if (isDependentClassScopeExplicitSpecialization) { 9780 ClassScopeFunctionSpecializationDecl *NewSpec = 9781 ClassScopeFunctionSpecializationDecl::Create( 9782 Context, CurContext, NewFD->getLocation(), 9783 cast<CXXMethodDecl>(NewFD), 9784 HasExplicitTemplateArgs, TemplateArgs); 9785 CurContext->addDecl(NewSpec); 9786 AddToScope = false; 9787 } 9788 9789 // Diagnose availability attributes. Availability cannot be used on functions 9790 // that are run during load/unload. 9791 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { 9792 if (NewFD->hasAttr<ConstructorAttr>()) { 9793 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9794 << 1; 9795 NewFD->dropAttr<AvailabilityAttr>(); 9796 } 9797 if (NewFD->hasAttr<DestructorAttr>()) { 9798 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9799 << 2; 9800 NewFD->dropAttr<AvailabilityAttr>(); 9801 } 9802 } 9803 9804 // Diagnose no_builtin attribute on function declaration that are not a 9805 // definition. 9806 // FIXME: We should really be doing this in 9807 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to 9808 // the FunctionDecl and at this point of the code 9809 // FunctionDecl::isThisDeclarationADefinition() which always returns `false` 9810 // because Sema::ActOnStartOfFunctionDef has not been called yet. 9811 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>()) 9812 switch (D.getFunctionDefinitionKind()) { 9813 case FDK_Defaulted: 9814 case FDK_Deleted: 9815 Diag(NBA->getLocation(), 9816 diag::err_attribute_no_builtin_on_defaulted_deleted_function) 9817 << NBA->getSpelling(); 9818 break; 9819 case FDK_Declaration: 9820 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition) 9821 << NBA->getSpelling(); 9822 break; 9823 case FDK_Definition: 9824 break; 9825 } 9826 9827 return NewFD; 9828 } 9829 9830 /// Return a CodeSegAttr from a containing class. The Microsoft docs say 9831 /// when __declspec(code_seg) "is applied to a class, all member functions of 9832 /// the class and nested classes -- this includes compiler-generated special 9833 /// member functions -- are put in the specified segment." 9834 /// The actual behavior is a little more complicated. The Microsoft compiler 9835 /// won't check outer classes if there is an active value from #pragma code_seg. 9836 /// The CodeSeg is always applied from the direct parent but only from outer 9837 /// classes when the #pragma code_seg stack is empty. See: 9838 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer 9839 /// available since MS has removed the page. 9840 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) { 9841 const auto *Method = dyn_cast<CXXMethodDecl>(FD); 9842 if (!Method) 9843 return nullptr; 9844 const CXXRecordDecl *Parent = Method->getParent(); 9845 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 9846 Attr *NewAttr = SAttr->clone(S.getASTContext()); 9847 NewAttr->setImplicit(true); 9848 return NewAttr; 9849 } 9850 9851 // The Microsoft compiler won't check outer classes for the CodeSeg 9852 // when the #pragma code_seg stack is active. 9853 if (S.CodeSegStack.CurrentValue) 9854 return nullptr; 9855 9856 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) { 9857 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 9858 Attr *NewAttr = SAttr->clone(S.getASTContext()); 9859 NewAttr->setImplicit(true); 9860 return NewAttr; 9861 } 9862 } 9863 return nullptr; 9864 } 9865 9866 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a 9867 /// containing class. Otherwise it will return implicit SectionAttr if the 9868 /// function is a definition and there is an active value on CodeSegStack 9869 /// (from the current #pragma code-seg value). 9870 /// 9871 /// \param FD Function being declared. 9872 /// \param IsDefinition Whether it is a definition or just a declarartion. 9873 /// \returns A CodeSegAttr or SectionAttr to apply to the function or 9874 /// nullptr if no attribute should be added. 9875 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, 9876 bool IsDefinition) { 9877 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD)) 9878 return A; 9879 if (!FD->hasAttr<SectionAttr>() && IsDefinition && 9880 CodeSegStack.CurrentValue) 9881 return SectionAttr::CreateImplicit( 9882 getASTContext(), CodeSegStack.CurrentValue->getString(), 9883 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 9884 SectionAttr::Declspec_allocate); 9885 return nullptr; 9886 } 9887 9888 /// Determines if we can perform a correct type check for \p D as a 9889 /// redeclaration of \p PrevDecl. If not, we can generally still perform a 9890 /// best-effort check. 9891 /// 9892 /// \param NewD The new declaration. 9893 /// \param OldD The old declaration. 9894 /// \param NewT The portion of the type of the new declaration to check. 9895 /// \param OldT The portion of the type of the old declaration to check. 9896 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, 9897 QualType NewT, QualType OldT) { 9898 if (!NewD->getLexicalDeclContext()->isDependentContext()) 9899 return true; 9900 9901 // For dependently-typed local extern declarations and friends, we can't 9902 // perform a correct type check in general until instantiation: 9903 // 9904 // int f(); 9905 // template<typename T> void g() { T f(); } 9906 // 9907 // (valid if g() is only instantiated with T = int). 9908 if (NewT->isDependentType() && 9909 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind())) 9910 return false; 9911 9912 // Similarly, if the previous declaration was a dependent local extern 9913 // declaration, we don't really know its type yet. 9914 if (OldT->isDependentType() && OldD->isLocalExternDecl()) 9915 return false; 9916 9917 return true; 9918 } 9919 9920 /// Checks if the new declaration declared in dependent context must be 9921 /// put in the same redeclaration chain as the specified declaration. 9922 /// 9923 /// \param D Declaration that is checked. 9924 /// \param PrevDecl Previous declaration found with proper lookup method for the 9925 /// same declaration name. 9926 /// \returns True if D must be added to the redeclaration chain which PrevDecl 9927 /// belongs to. 9928 /// 9929 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 9930 if (!D->getLexicalDeclContext()->isDependentContext()) 9931 return true; 9932 9933 // Don't chain dependent friend function definitions until instantiation, to 9934 // permit cases like 9935 // 9936 // void func(); 9937 // template<typename T> class C1 { friend void func() {} }; 9938 // template<typename T> class C2 { friend void func() {} }; 9939 // 9940 // ... which is valid if only one of C1 and C2 is ever instantiated. 9941 // 9942 // FIXME: This need only apply to function definitions. For now, we proxy 9943 // this by checking for a file-scope function. We do not want this to apply 9944 // to friend declarations nominating member functions, because that gets in 9945 // the way of access checks. 9946 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext()) 9947 return false; 9948 9949 auto *VD = dyn_cast<ValueDecl>(D); 9950 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl); 9951 return !VD || !PrevVD || 9952 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(), 9953 PrevVD->getType()); 9954 } 9955 9956 /// Check the target attribute of the function for MultiVersion 9957 /// validity. 9958 /// 9959 /// Returns true if there was an error, false otherwise. 9960 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { 9961 const auto *TA = FD->getAttr<TargetAttr>(); 9962 assert(TA && "MultiVersion Candidate requires a target attribute"); 9963 ParsedTargetAttr ParseInfo = TA->parse(); 9964 const TargetInfo &TargetInfo = S.Context.getTargetInfo(); 9965 enum ErrType { Feature = 0, Architecture = 1 }; 9966 9967 if (!ParseInfo.Architecture.empty() && 9968 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) { 9969 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9970 << Architecture << ParseInfo.Architecture; 9971 return true; 9972 } 9973 9974 for (const auto &Feat : ParseInfo.Features) { 9975 auto BareFeat = StringRef{Feat}.substr(1); 9976 if (Feat[0] == '-') { 9977 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9978 << Feature << ("no-" + BareFeat).str(); 9979 return true; 9980 } 9981 9982 if (!TargetInfo.validateCpuSupports(BareFeat) || 9983 !TargetInfo.isValidFeatureName(BareFeat)) { 9984 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9985 << Feature << BareFeat; 9986 return true; 9987 } 9988 } 9989 return false; 9990 } 9991 9992 // Provide a white-list of attributes that are allowed to be combined with 9993 // multiversion functions. 9994 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, 9995 MultiVersionKind MVType) { 9996 switch (Kind) { 9997 default: 9998 return false; 9999 case attr::Used: 10000 return MVType == MultiVersionKind::Target; 10001 } 10002 } 10003 10004 static bool HasNonMultiVersionAttributes(const FunctionDecl *FD, 10005 MultiVersionKind MVType) { 10006 for (const Attr *A : FD->attrs()) { 10007 switch (A->getKind()) { 10008 case attr::CPUDispatch: 10009 case attr::CPUSpecific: 10010 if (MVType != MultiVersionKind::CPUDispatch && 10011 MVType != MultiVersionKind::CPUSpecific) 10012 return true; 10013 break; 10014 case attr::Target: 10015 if (MVType != MultiVersionKind::Target) 10016 return true; 10017 break; 10018 default: 10019 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType)) 10020 return true; 10021 break; 10022 } 10023 } 10024 return false; 10025 } 10026 10027 bool Sema::areMultiversionVariantFunctionsCompatible( 10028 const FunctionDecl *OldFD, const FunctionDecl *NewFD, 10029 const PartialDiagnostic &NoProtoDiagID, 10030 const PartialDiagnosticAt &NoteCausedDiagIDAt, 10031 const PartialDiagnosticAt &NoSupportDiagIDAt, 10032 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, 10033 bool ConstexprSupported, bool CLinkageMayDiffer) { 10034 enum DoesntSupport { 10035 FuncTemplates = 0, 10036 VirtFuncs = 1, 10037 DeducedReturn = 2, 10038 Constructors = 3, 10039 Destructors = 4, 10040 DeletedFuncs = 5, 10041 DefaultedFuncs = 6, 10042 ConstexprFuncs = 7, 10043 ConstevalFuncs = 8, 10044 }; 10045 enum Different { 10046 CallingConv = 0, 10047 ReturnType = 1, 10048 ConstexprSpec = 2, 10049 InlineSpec = 3, 10050 StorageClass = 4, 10051 Linkage = 5, 10052 }; 10053 10054 if (NoProtoDiagID.getDiagID() != 0 && OldFD && 10055 !OldFD->getType()->getAs<FunctionProtoType>()) { 10056 Diag(OldFD->getLocation(), NoProtoDiagID); 10057 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second); 10058 return true; 10059 } 10060 10061 if (NoProtoDiagID.getDiagID() != 0 && 10062 !NewFD->getType()->getAs<FunctionProtoType>()) 10063 return Diag(NewFD->getLocation(), NoProtoDiagID); 10064 10065 if (!TemplatesSupported && 10066 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 10067 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10068 << FuncTemplates; 10069 10070 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { 10071 if (NewCXXFD->isVirtual()) 10072 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10073 << VirtFuncs; 10074 10075 if (isa<CXXConstructorDecl>(NewCXXFD)) 10076 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10077 << Constructors; 10078 10079 if (isa<CXXDestructorDecl>(NewCXXFD)) 10080 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10081 << Destructors; 10082 } 10083 10084 if (NewFD->isDeleted()) 10085 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10086 << DeletedFuncs; 10087 10088 if (NewFD->isDefaulted()) 10089 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10090 << DefaultedFuncs; 10091 10092 if (!ConstexprSupported && NewFD->isConstexpr()) 10093 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10094 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs); 10095 10096 QualType NewQType = Context.getCanonicalType(NewFD->getType()); 10097 const auto *NewType = cast<FunctionType>(NewQType); 10098 QualType NewReturnType = NewType->getReturnType(); 10099 10100 if (NewReturnType->isUndeducedType()) 10101 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10102 << DeducedReturn; 10103 10104 // Ensure the return type is identical. 10105 if (OldFD) { 10106 QualType OldQType = Context.getCanonicalType(OldFD->getType()); 10107 const auto *OldType = cast<FunctionType>(OldQType); 10108 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 10109 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 10110 10111 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) 10112 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv; 10113 10114 QualType OldReturnType = OldType->getReturnType(); 10115 10116 if (OldReturnType != NewReturnType) 10117 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType; 10118 10119 if (OldFD->getConstexprKind() != NewFD->getConstexprKind()) 10120 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec; 10121 10122 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) 10123 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec; 10124 10125 if (OldFD->getStorageClass() != NewFD->getStorageClass()) 10126 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass; 10127 10128 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC()) 10129 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage; 10130 10131 if (CheckEquivalentExceptionSpec( 10132 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), 10133 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) 10134 return true; 10135 } 10136 return false; 10137 } 10138 10139 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, 10140 const FunctionDecl *NewFD, 10141 bool CausesMV, 10142 MultiVersionKind MVType) { 10143 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10144 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10145 if (OldFD) 10146 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10147 return true; 10148 } 10149 10150 bool IsCPUSpecificCPUDispatchMVType = 10151 MVType == MultiVersionKind::CPUDispatch || 10152 MVType == MultiVersionKind::CPUSpecific; 10153 10154 // For now, disallow all other attributes. These should be opt-in, but 10155 // an analysis of all of them is a future FIXME. 10156 if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) { 10157 S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs) 10158 << IsCPUSpecificCPUDispatchMVType; 10159 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10160 return true; 10161 } 10162 10163 if (HasNonMultiVersionAttributes(NewFD, MVType)) 10164 return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs) 10165 << IsCPUSpecificCPUDispatchMVType; 10166 10167 // Only allow transition to MultiVersion if it hasn't been used. 10168 if (OldFD && CausesMV && OldFD->isUsed(false)) 10169 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 10170 10171 return S.areMultiversionVariantFunctionsCompatible( 10172 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto), 10173 PartialDiagnosticAt(NewFD->getLocation(), 10174 S.PDiag(diag::note_multiversioning_caused_here)), 10175 PartialDiagnosticAt(NewFD->getLocation(), 10176 S.PDiag(diag::err_multiversion_doesnt_support) 10177 << IsCPUSpecificCPUDispatchMVType), 10178 PartialDiagnosticAt(NewFD->getLocation(), 10179 S.PDiag(diag::err_multiversion_diff)), 10180 /*TemplatesSupported=*/false, 10181 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType, 10182 /*CLinkageMayDiffer=*/false); 10183 } 10184 10185 /// Check the validity of a multiversion function declaration that is the 10186 /// first of its kind. Also sets the multiversion'ness' of the function itself. 10187 /// 10188 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10189 /// 10190 /// Returns true if there was an error, false otherwise. 10191 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD, 10192 MultiVersionKind MVType, 10193 const TargetAttr *TA) { 10194 assert(MVType != MultiVersionKind::None && 10195 "Function lacks multiversion attribute"); 10196 10197 // Target only causes MV if it is default, otherwise this is a normal 10198 // function. 10199 if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion()) 10200 return false; 10201 10202 if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) { 10203 FD->setInvalidDecl(); 10204 return true; 10205 } 10206 10207 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) { 10208 FD->setInvalidDecl(); 10209 return true; 10210 } 10211 10212 FD->setIsMultiVersion(); 10213 return false; 10214 } 10215 10216 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) { 10217 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) { 10218 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None) 10219 return true; 10220 } 10221 10222 return false; 10223 } 10224 10225 static bool CheckTargetCausesMultiVersioning( 10226 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA, 10227 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 10228 LookupResult &Previous) { 10229 const auto *OldTA = OldFD->getAttr<TargetAttr>(); 10230 ParsedTargetAttr NewParsed = NewTA->parse(); 10231 // Sort order doesn't matter, it just needs to be consistent. 10232 llvm::sort(NewParsed.Features); 10233 10234 // If the old decl is NOT MultiVersioned yet, and we don't cause that 10235 // to change, this is a simple redeclaration. 10236 if (!NewTA->isDefaultVersion() && 10237 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) 10238 return false; 10239 10240 // Otherwise, this decl causes MultiVersioning. 10241 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10242 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10243 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10244 NewFD->setInvalidDecl(); 10245 return true; 10246 } 10247 10248 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true, 10249 MultiVersionKind::Target)) { 10250 NewFD->setInvalidDecl(); 10251 return true; 10252 } 10253 10254 if (CheckMultiVersionValue(S, NewFD)) { 10255 NewFD->setInvalidDecl(); 10256 return true; 10257 } 10258 10259 // If this is 'default', permit the forward declaration. 10260 if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) { 10261 Redeclaration = true; 10262 OldDecl = OldFD; 10263 OldFD->setIsMultiVersion(); 10264 NewFD->setIsMultiVersion(); 10265 return false; 10266 } 10267 10268 if (CheckMultiVersionValue(S, OldFD)) { 10269 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10270 NewFD->setInvalidDecl(); 10271 return true; 10272 } 10273 10274 ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>()); 10275 10276 if (OldParsed == NewParsed) { 10277 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10278 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10279 NewFD->setInvalidDecl(); 10280 return true; 10281 } 10282 10283 for (const auto *FD : OldFD->redecls()) { 10284 const auto *CurTA = FD->getAttr<TargetAttr>(); 10285 // We allow forward declarations before ANY multiversioning attributes, but 10286 // nothing after the fact. 10287 if (PreviousDeclsHaveMultiVersionAttribute(FD) && 10288 (!CurTA || CurTA->isInherited())) { 10289 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl) 10290 << 0; 10291 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10292 NewFD->setInvalidDecl(); 10293 return true; 10294 } 10295 } 10296 10297 OldFD->setIsMultiVersion(); 10298 NewFD->setIsMultiVersion(); 10299 Redeclaration = false; 10300 MergeTypeWithPrevious = false; 10301 OldDecl = nullptr; 10302 Previous.clear(); 10303 return false; 10304 } 10305 10306 /// Check the validity of a new function declaration being added to an existing 10307 /// multiversioned declaration collection. 10308 static bool CheckMultiVersionAdditionalDecl( 10309 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, 10310 MultiVersionKind NewMVType, const TargetAttr *NewTA, 10311 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, 10312 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 10313 LookupResult &Previous) { 10314 10315 MultiVersionKind OldMVType = OldFD->getMultiVersionKind(); 10316 // Disallow mixing of multiversioning types. 10317 if ((OldMVType == MultiVersionKind::Target && 10318 NewMVType != MultiVersionKind::Target) || 10319 (NewMVType == MultiVersionKind::Target && 10320 OldMVType != MultiVersionKind::Target)) { 10321 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10322 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10323 NewFD->setInvalidDecl(); 10324 return true; 10325 } 10326 10327 ParsedTargetAttr NewParsed; 10328 if (NewTA) { 10329 NewParsed = NewTA->parse(); 10330 llvm::sort(NewParsed.Features); 10331 } 10332 10333 bool UseMemberUsingDeclRules = 10334 S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); 10335 10336 // Next, check ALL non-overloads to see if this is a redeclaration of a 10337 // previous member of the MultiVersion set. 10338 for (NamedDecl *ND : Previous) { 10339 FunctionDecl *CurFD = ND->getAsFunction(); 10340 if (!CurFD) 10341 continue; 10342 if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) 10343 continue; 10344 10345 if (NewMVType == MultiVersionKind::Target) { 10346 const auto *CurTA = CurFD->getAttr<TargetAttr>(); 10347 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { 10348 NewFD->setIsMultiVersion(); 10349 Redeclaration = true; 10350 OldDecl = ND; 10351 return false; 10352 } 10353 10354 ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>()); 10355 if (CurParsed == NewParsed) { 10356 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10357 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10358 NewFD->setInvalidDecl(); 10359 return true; 10360 } 10361 } else { 10362 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>(); 10363 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>(); 10364 // Handle CPUDispatch/CPUSpecific versions. 10365 // Only 1 CPUDispatch function is allowed, this will make it go through 10366 // the redeclaration errors. 10367 if (NewMVType == MultiVersionKind::CPUDispatch && 10368 CurFD->hasAttr<CPUDispatchAttr>()) { 10369 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() && 10370 std::equal( 10371 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(), 10372 NewCPUDisp->cpus_begin(), 10373 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10374 return Cur->getName() == New->getName(); 10375 })) { 10376 NewFD->setIsMultiVersion(); 10377 Redeclaration = true; 10378 OldDecl = ND; 10379 return false; 10380 } 10381 10382 // If the declarations don't match, this is an error condition. 10383 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch); 10384 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10385 NewFD->setInvalidDecl(); 10386 return true; 10387 } 10388 if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) { 10389 10390 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() && 10391 std::equal( 10392 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(), 10393 NewCPUSpec->cpus_begin(), 10394 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10395 return Cur->getName() == New->getName(); 10396 })) { 10397 NewFD->setIsMultiVersion(); 10398 Redeclaration = true; 10399 OldDecl = ND; 10400 return false; 10401 } 10402 10403 // Only 1 version of CPUSpecific is allowed for each CPU. 10404 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) { 10405 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) { 10406 if (CurII == NewII) { 10407 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs) 10408 << NewII; 10409 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10410 NewFD->setInvalidDecl(); 10411 return true; 10412 } 10413 } 10414 } 10415 } 10416 // If the two decls aren't the same MVType, there is no possible error 10417 // condition. 10418 } 10419 } 10420 10421 // Else, this is simply a non-redecl case. Checking the 'value' is only 10422 // necessary in the Target case, since The CPUSpecific/Dispatch cases are 10423 // handled in the attribute adding step. 10424 if (NewMVType == MultiVersionKind::Target && 10425 CheckMultiVersionValue(S, NewFD)) { 10426 NewFD->setInvalidDecl(); 10427 return true; 10428 } 10429 10430 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, 10431 !OldFD->isMultiVersion(), NewMVType)) { 10432 NewFD->setInvalidDecl(); 10433 return true; 10434 } 10435 10436 // Permit forward declarations in the case where these two are compatible. 10437 if (!OldFD->isMultiVersion()) { 10438 OldFD->setIsMultiVersion(); 10439 NewFD->setIsMultiVersion(); 10440 Redeclaration = true; 10441 OldDecl = OldFD; 10442 return false; 10443 } 10444 10445 NewFD->setIsMultiVersion(); 10446 Redeclaration = false; 10447 MergeTypeWithPrevious = false; 10448 OldDecl = nullptr; 10449 Previous.clear(); 10450 return false; 10451 } 10452 10453 10454 /// Check the validity of a mulitversion function declaration. 10455 /// Also sets the multiversion'ness' of the function itself. 10456 /// 10457 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10458 /// 10459 /// Returns true if there was an error, false otherwise. 10460 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, 10461 bool &Redeclaration, NamedDecl *&OldDecl, 10462 bool &MergeTypeWithPrevious, 10463 LookupResult &Previous) { 10464 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 10465 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>(); 10466 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>(); 10467 10468 // Mixing Multiversioning types is prohibited. 10469 if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) || 10470 (NewCPUDisp && NewCPUSpec)) { 10471 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10472 NewFD->setInvalidDecl(); 10473 return true; 10474 } 10475 10476 MultiVersionKind MVType = NewFD->getMultiVersionKind(); 10477 10478 // Main isn't allowed to become a multiversion function, however it IS 10479 // permitted to have 'main' be marked with the 'target' optimization hint. 10480 if (NewFD->isMain()) { 10481 if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) || 10482 MVType == MultiVersionKind::CPUDispatch || 10483 MVType == MultiVersionKind::CPUSpecific) { 10484 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); 10485 NewFD->setInvalidDecl(); 10486 return true; 10487 } 10488 return false; 10489 } 10490 10491 if (!OldDecl || !OldDecl->getAsFunction() || 10492 OldDecl->getDeclContext()->getRedeclContext() != 10493 NewFD->getDeclContext()->getRedeclContext()) { 10494 // If there's no previous declaration, AND this isn't attempting to cause 10495 // multiversioning, this isn't an error condition. 10496 if (MVType == MultiVersionKind::None) 10497 return false; 10498 return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA); 10499 } 10500 10501 FunctionDecl *OldFD = OldDecl->getAsFunction(); 10502 10503 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None) 10504 return false; 10505 10506 if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) { 10507 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl) 10508 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target); 10509 NewFD->setInvalidDecl(); 10510 return true; 10511 } 10512 10513 // Handle the target potentially causes multiversioning case. 10514 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target) 10515 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA, 10516 Redeclaration, OldDecl, 10517 MergeTypeWithPrevious, Previous); 10518 10519 // At this point, we have a multiversion function decl (in OldFD) AND an 10520 // appropriate attribute in the current function decl. Resolve that these are 10521 // still compatible with previous declarations. 10522 return CheckMultiVersionAdditionalDecl( 10523 S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration, 10524 OldDecl, MergeTypeWithPrevious, Previous); 10525 } 10526 10527 /// Perform semantic checking of a new function declaration. 10528 /// 10529 /// Performs semantic analysis of the new function declaration 10530 /// NewFD. This routine performs all semantic checking that does not 10531 /// require the actual declarator involved in the declaration, and is 10532 /// used both for the declaration of functions as they are parsed 10533 /// (called via ActOnDeclarator) and for the declaration of functions 10534 /// that have been instantiated via C++ template instantiation (called 10535 /// via InstantiateDecl). 10536 /// 10537 /// \param IsMemberSpecialization whether this new function declaration is 10538 /// a member specialization (that replaces any definition provided by the 10539 /// previous declaration). 10540 /// 10541 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10542 /// 10543 /// \returns true if the function declaration is a redeclaration. 10544 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 10545 LookupResult &Previous, 10546 bool IsMemberSpecialization) { 10547 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 10548 "Variably modified return types are not handled here"); 10549 10550 // Determine whether the type of this function should be merged with 10551 // a previous visible declaration. This never happens for functions in C++, 10552 // and always happens in C if the previous declaration was visible. 10553 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 10554 !Previous.isShadowed(); 10555 10556 bool Redeclaration = false; 10557 NamedDecl *OldDecl = nullptr; 10558 bool MayNeedOverloadableChecks = false; 10559 10560 // Merge or overload the declaration with an existing declaration of 10561 // the same name, if appropriate. 10562 if (!Previous.empty()) { 10563 // Determine whether NewFD is an overload of PrevDecl or 10564 // a declaration that requires merging. If it's an overload, 10565 // there's no more work to do here; we'll just add the new 10566 // function to the scope. 10567 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { 10568 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 10569 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 10570 Redeclaration = true; 10571 OldDecl = Candidate; 10572 } 10573 } else { 10574 MayNeedOverloadableChecks = true; 10575 switch (CheckOverload(S, NewFD, Previous, OldDecl, 10576 /*NewIsUsingDecl*/ false)) { 10577 case Ovl_Match: 10578 Redeclaration = true; 10579 break; 10580 10581 case Ovl_NonFunction: 10582 Redeclaration = true; 10583 break; 10584 10585 case Ovl_Overload: 10586 Redeclaration = false; 10587 break; 10588 } 10589 } 10590 } 10591 10592 // Check for a previous extern "C" declaration with this name. 10593 if (!Redeclaration && 10594 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 10595 if (!Previous.empty()) { 10596 // This is an extern "C" declaration with the same name as a previous 10597 // declaration, and thus redeclares that entity... 10598 Redeclaration = true; 10599 OldDecl = Previous.getFoundDecl(); 10600 MergeTypeWithPrevious = false; 10601 10602 // ... except in the presence of __attribute__((overloadable)). 10603 if (OldDecl->hasAttr<OverloadableAttr>() || 10604 NewFD->hasAttr<OverloadableAttr>()) { 10605 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 10606 MayNeedOverloadableChecks = true; 10607 Redeclaration = false; 10608 OldDecl = nullptr; 10609 } 10610 } 10611 } 10612 } 10613 10614 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, 10615 MergeTypeWithPrevious, Previous)) 10616 return Redeclaration; 10617 10618 // C++11 [dcl.constexpr]p8: 10619 // A constexpr specifier for a non-static member function that is not 10620 // a constructor declares that member function to be const. 10621 // 10622 // This needs to be delayed until we know whether this is an out-of-line 10623 // definition of a static member function. 10624 // 10625 // This rule is not present in C++1y, so we produce a backwards 10626 // compatibility warning whenever it happens in C++11. 10627 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 10628 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 10629 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 10630 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) { 10631 CXXMethodDecl *OldMD = nullptr; 10632 if (OldDecl) 10633 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 10634 if (!OldMD || !OldMD->isStatic()) { 10635 const FunctionProtoType *FPT = 10636 MD->getType()->castAs<FunctionProtoType>(); 10637 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10638 EPI.TypeQuals.addConst(); 10639 MD->setType(Context.getFunctionType(FPT->getReturnType(), 10640 FPT->getParamTypes(), EPI)); 10641 10642 // Warn that we did this, if we're not performing template instantiation. 10643 // In that case, we'll have warned already when the template was defined. 10644 if (!inTemplateInstantiation()) { 10645 SourceLocation AddConstLoc; 10646 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 10647 .IgnoreParens().getAs<FunctionTypeLoc>()) 10648 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 10649 10650 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 10651 << FixItHint::CreateInsertion(AddConstLoc, " const"); 10652 } 10653 } 10654 } 10655 10656 if (Redeclaration) { 10657 // NewFD and OldDecl represent declarations that need to be 10658 // merged. 10659 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 10660 NewFD->setInvalidDecl(); 10661 return Redeclaration; 10662 } 10663 10664 Previous.clear(); 10665 Previous.addDecl(OldDecl); 10666 10667 if (FunctionTemplateDecl *OldTemplateDecl = 10668 dyn_cast<FunctionTemplateDecl>(OldDecl)) { 10669 auto *OldFD = OldTemplateDecl->getTemplatedDecl(); 10670 FunctionTemplateDecl *NewTemplateDecl 10671 = NewFD->getDescribedFunctionTemplate(); 10672 assert(NewTemplateDecl && "Template/non-template mismatch"); 10673 10674 // The call to MergeFunctionDecl above may have created some state in 10675 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we 10676 // can add it as a redeclaration. 10677 NewTemplateDecl->mergePrevDecl(OldTemplateDecl); 10678 10679 NewFD->setPreviousDeclaration(OldFD); 10680 adjustDeclContextForDeclaratorDecl(NewFD, OldFD); 10681 if (NewFD->isCXXClassMember()) { 10682 NewFD->setAccess(OldTemplateDecl->getAccess()); 10683 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 10684 } 10685 10686 // If this is an explicit specialization of a member that is a function 10687 // template, mark it as a member specialization. 10688 if (IsMemberSpecialization && 10689 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 10690 NewTemplateDecl->setMemberSpecialization(); 10691 assert(OldTemplateDecl->isMemberSpecialization()); 10692 // Explicit specializations of a member template do not inherit deleted 10693 // status from the parent member template that they are specializing. 10694 if (OldFD->isDeleted()) { 10695 // FIXME: This assert will not hold in the presence of modules. 10696 assert(OldFD->getCanonicalDecl() == OldFD); 10697 // FIXME: We need an update record for this AST mutation. 10698 OldFD->setDeletedAsWritten(false); 10699 } 10700 } 10701 10702 } else { 10703 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 10704 auto *OldFD = cast<FunctionDecl>(OldDecl); 10705 // This needs to happen first so that 'inline' propagates. 10706 NewFD->setPreviousDeclaration(OldFD); 10707 adjustDeclContextForDeclaratorDecl(NewFD, OldFD); 10708 if (NewFD->isCXXClassMember()) 10709 NewFD->setAccess(OldFD->getAccess()); 10710 } 10711 } 10712 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && 10713 !NewFD->getAttr<OverloadableAttr>()) { 10714 assert((Previous.empty() || 10715 llvm::any_of(Previous, 10716 [](const NamedDecl *ND) { 10717 return ND->hasAttr<OverloadableAttr>(); 10718 })) && 10719 "Non-redecls shouldn't happen without overloadable present"); 10720 10721 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { 10722 const auto *FD = dyn_cast<FunctionDecl>(ND); 10723 return FD && !FD->hasAttr<OverloadableAttr>(); 10724 }); 10725 10726 if (OtherUnmarkedIter != Previous.end()) { 10727 Diag(NewFD->getLocation(), 10728 diag::err_attribute_overloadable_multiple_unmarked_overloads); 10729 Diag((*OtherUnmarkedIter)->getLocation(), 10730 diag::note_attribute_overloadable_prev_overload) 10731 << false; 10732 10733 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 10734 } 10735 } 10736 10737 // Semantic checking for this function declaration (in isolation). 10738 10739 if (getLangOpts().CPlusPlus) { 10740 // C++-specific checks. 10741 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 10742 CheckConstructor(Constructor); 10743 } else if (CXXDestructorDecl *Destructor = 10744 dyn_cast<CXXDestructorDecl>(NewFD)) { 10745 CXXRecordDecl *Record = Destructor->getParent(); 10746 QualType ClassType = Context.getTypeDeclType(Record); 10747 10748 // FIXME: Shouldn't we be able to perform this check even when the class 10749 // type is dependent? Both gcc and edg can handle that. 10750 if (!ClassType->isDependentType()) { 10751 DeclarationName Name 10752 = Context.DeclarationNames.getCXXDestructorName( 10753 Context.getCanonicalType(ClassType)); 10754 if (NewFD->getDeclName() != Name) { 10755 Diag(NewFD->getLocation(), diag::err_destructor_name); 10756 NewFD->setInvalidDecl(); 10757 return Redeclaration; 10758 } 10759 } 10760 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 10761 if (auto *TD = Guide->getDescribedFunctionTemplate()) 10762 CheckDeductionGuideTemplate(TD); 10763 10764 // A deduction guide is not on the list of entities that can be 10765 // explicitly specialized. 10766 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 10767 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized) 10768 << /*explicit specialization*/ 1; 10769 } 10770 10771 // Find any virtual functions that this function overrides. 10772 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 10773 if (!Method->isFunctionTemplateSpecialization() && 10774 !Method->getDescribedFunctionTemplate() && 10775 Method->isCanonicalDecl()) { 10776 AddOverriddenMethods(Method->getParent(), Method); 10777 } 10778 if (Method->isVirtual() && NewFD->getTrailingRequiresClause()) 10779 // C++2a [class.virtual]p6 10780 // A virtual method shall not have a requires-clause. 10781 Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(), 10782 diag::err_constrained_virtual_method); 10783 10784 if (Method->isStatic()) 10785 checkThisInStaticMemberFunctionType(Method); 10786 } 10787 10788 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD)) 10789 ActOnConversionDeclarator(Conversion); 10790 10791 // Extra checking for C++ overloaded operators (C++ [over.oper]). 10792 if (NewFD->isOverloadedOperator() && 10793 CheckOverloadedOperatorDeclaration(NewFD)) { 10794 NewFD->setInvalidDecl(); 10795 return Redeclaration; 10796 } 10797 10798 // Extra checking for C++0x literal operators (C++0x [over.literal]). 10799 if (NewFD->getLiteralIdentifier() && 10800 CheckLiteralOperatorDeclaration(NewFD)) { 10801 NewFD->setInvalidDecl(); 10802 return Redeclaration; 10803 } 10804 10805 // In C++, check default arguments now that we have merged decls. Unless 10806 // the lexical context is the class, because in this case this is done 10807 // during delayed parsing anyway. 10808 if (!CurContext->isRecord()) 10809 CheckCXXDefaultArguments(NewFD); 10810 10811 // If this function declares a builtin function, check the type of this 10812 // declaration against the expected type for the builtin. 10813 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 10814 ASTContext::GetBuiltinTypeError Error; 10815 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 10816 QualType T = Context.GetBuiltinType(BuiltinID, Error); 10817 // If the type of the builtin differs only in its exception 10818 // specification, that's OK. 10819 // FIXME: If the types do differ in this way, it would be better to 10820 // retain the 'noexcept' form of the type. 10821 if (!T.isNull() && 10822 !Context.hasSameFunctionTypeIgnoringExceptionSpec(T, 10823 NewFD->getType())) 10824 // The type of this function differs from the type of the builtin, 10825 // so forget about the builtin entirely. 10826 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); 10827 } 10828 10829 // If this function is declared as being extern "C", then check to see if 10830 // the function returns a UDT (class, struct, or union type) that is not C 10831 // compatible, and if it does, warn the user. 10832 // But, issue any diagnostic on the first declaration only. 10833 if (Previous.empty() && NewFD->isExternC()) { 10834 QualType R = NewFD->getReturnType(); 10835 if (R->isIncompleteType() && !R->isVoidType()) 10836 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 10837 << NewFD << R; 10838 else if (!R.isPODType(Context) && !R->isVoidType() && 10839 !R->isObjCObjectPointerType()) 10840 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 10841 } 10842 10843 // C++1z [dcl.fct]p6: 10844 // [...] whether the function has a non-throwing exception-specification 10845 // [is] part of the function type 10846 // 10847 // This results in an ABI break between C++14 and C++17 for functions whose 10848 // declared type includes an exception-specification in a parameter or 10849 // return type. (Exception specifications on the function itself are OK in 10850 // most cases, and exception specifications are not permitted in most other 10851 // contexts where they could make it into a mangling.) 10852 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { 10853 auto HasNoexcept = [&](QualType T) -> bool { 10854 // Strip off declarator chunks that could be between us and a function 10855 // type. We don't need to look far, exception specifications are very 10856 // restricted prior to C++17. 10857 if (auto *RT = T->getAs<ReferenceType>()) 10858 T = RT->getPointeeType(); 10859 else if (T->isAnyPointerType()) 10860 T = T->getPointeeType(); 10861 else if (auto *MPT = T->getAs<MemberPointerType>()) 10862 T = MPT->getPointeeType(); 10863 if (auto *FPT = T->getAs<FunctionProtoType>()) 10864 if (FPT->isNothrow()) 10865 return true; 10866 return false; 10867 }; 10868 10869 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 10870 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 10871 for (QualType T : FPT->param_types()) 10872 AnyNoexcept |= HasNoexcept(T); 10873 if (AnyNoexcept) 10874 Diag(NewFD->getLocation(), 10875 diag::warn_cxx17_compat_exception_spec_in_signature) 10876 << NewFD; 10877 } 10878 10879 if (!Redeclaration && LangOpts.CUDA) 10880 checkCUDATargetOverload(NewFD, Previous); 10881 } 10882 return Redeclaration; 10883 } 10884 10885 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 10886 // C++11 [basic.start.main]p3: 10887 // A program that [...] declares main to be inline, static or 10888 // constexpr is ill-formed. 10889 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 10890 // appear in a declaration of main. 10891 // static main is not an error under C99, but we should warn about it. 10892 // We accept _Noreturn main as an extension. 10893 if (FD->getStorageClass() == SC_Static) 10894 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 10895 ? diag::err_static_main : diag::warn_static_main) 10896 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 10897 if (FD->isInlineSpecified()) 10898 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 10899 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 10900 if (DS.isNoreturnSpecified()) { 10901 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 10902 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 10903 Diag(NoreturnLoc, diag::ext_noreturn_main); 10904 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 10905 << FixItHint::CreateRemoval(NoreturnRange); 10906 } 10907 if (FD->isConstexpr()) { 10908 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 10909 << FD->isConsteval() 10910 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 10911 FD->setConstexprKind(CSK_unspecified); 10912 } 10913 10914 if (getLangOpts().OpenCL) { 10915 Diag(FD->getLocation(), diag::err_opencl_no_main) 10916 << FD->hasAttr<OpenCLKernelAttr>(); 10917 FD->setInvalidDecl(); 10918 return; 10919 } 10920 10921 QualType T = FD->getType(); 10922 assert(T->isFunctionType() && "function decl is not of function type"); 10923 const FunctionType* FT = T->castAs<FunctionType>(); 10924 10925 // Set default calling convention for main() 10926 if (FT->getCallConv() != CC_C) { 10927 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); 10928 FD->setType(QualType(FT, 0)); 10929 T = Context.getCanonicalType(FD->getType()); 10930 } 10931 10932 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 10933 // In C with GNU extensions we allow main() to have non-integer return 10934 // type, but we should warn about the extension, and we disable the 10935 // implicit-return-zero rule. 10936 10937 // GCC in C mode accepts qualified 'int'. 10938 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 10939 FD->setHasImplicitReturnZero(true); 10940 else { 10941 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 10942 SourceRange RTRange = FD->getReturnTypeSourceRange(); 10943 if (RTRange.isValid()) 10944 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 10945 << FixItHint::CreateReplacement(RTRange, "int"); 10946 } 10947 } else { 10948 // In C and C++, main magically returns 0 if you fall off the end; 10949 // set the flag which tells us that. 10950 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 10951 10952 // All the standards say that main() should return 'int'. 10953 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 10954 FD->setHasImplicitReturnZero(true); 10955 else { 10956 // Otherwise, this is just a flat-out error. 10957 SourceRange RTRange = FD->getReturnTypeSourceRange(); 10958 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 10959 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 10960 : FixItHint()); 10961 FD->setInvalidDecl(true); 10962 } 10963 } 10964 10965 // Treat protoless main() as nullary. 10966 if (isa<FunctionNoProtoType>(FT)) return; 10967 10968 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 10969 unsigned nparams = FTP->getNumParams(); 10970 assert(FD->getNumParams() == nparams); 10971 10972 bool HasExtraParameters = (nparams > 3); 10973 10974 if (FTP->isVariadic()) { 10975 Diag(FD->getLocation(), diag::ext_variadic_main); 10976 // FIXME: if we had information about the location of the ellipsis, we 10977 // could add a FixIt hint to remove it as a parameter. 10978 } 10979 10980 // Darwin passes an undocumented fourth argument of type char**. If 10981 // other platforms start sprouting these, the logic below will start 10982 // getting shifty. 10983 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 10984 HasExtraParameters = false; 10985 10986 if (HasExtraParameters) { 10987 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 10988 FD->setInvalidDecl(true); 10989 nparams = 3; 10990 } 10991 10992 // FIXME: a lot of the following diagnostics would be improved 10993 // if we had some location information about types. 10994 10995 QualType CharPP = 10996 Context.getPointerType(Context.getPointerType(Context.CharTy)); 10997 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 10998 10999 for (unsigned i = 0; i < nparams; ++i) { 11000 QualType AT = FTP->getParamType(i); 11001 11002 bool mismatch = true; 11003 11004 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 11005 mismatch = false; 11006 else if (Expected[i] == CharPP) { 11007 // As an extension, the following forms are okay: 11008 // char const ** 11009 // char const * const * 11010 // char * const * 11011 11012 QualifierCollector qs; 11013 const PointerType* PT; 11014 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 11015 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 11016 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 11017 Context.CharTy)) { 11018 qs.removeConst(); 11019 mismatch = !qs.empty(); 11020 } 11021 } 11022 11023 if (mismatch) { 11024 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 11025 // TODO: suggest replacing given type with expected type 11026 FD->setInvalidDecl(true); 11027 } 11028 } 11029 11030 if (nparams == 1 && !FD->isInvalidDecl()) { 11031 Diag(FD->getLocation(), diag::warn_main_one_arg); 11032 } 11033 11034 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11035 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11036 FD->setInvalidDecl(); 11037 } 11038 } 11039 11040 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 11041 QualType T = FD->getType(); 11042 assert(T->isFunctionType() && "function decl is not of function type"); 11043 const FunctionType *FT = T->castAs<FunctionType>(); 11044 11045 // Set an implicit return of 'zero' if the function can return some integral, 11046 // enumeration, pointer or nullptr type. 11047 if (FT->getReturnType()->isIntegralOrEnumerationType() || 11048 FT->getReturnType()->isAnyPointerType() || 11049 FT->getReturnType()->isNullPtrType()) 11050 // DllMain is exempt because a return value of zero means it failed. 11051 if (FD->getName() != "DllMain") 11052 FD->setHasImplicitReturnZero(true); 11053 11054 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11055 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11056 FD->setInvalidDecl(); 11057 } 11058 } 11059 11060 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 11061 // FIXME: Need strict checking. In C89, we need to check for 11062 // any assignment, increment, decrement, function-calls, or 11063 // commas outside of a sizeof. In C99, it's the same list, 11064 // except that the aforementioned are allowed in unevaluated 11065 // expressions. Everything else falls under the 11066 // "may accept other forms of constant expressions" exception. 11067 // (We never end up here for C++, so the constant expression 11068 // rules there don't matter.) 11069 const Expr *Culprit; 11070 if (Init->isConstantInitializer(Context, false, &Culprit)) 11071 return false; 11072 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 11073 << Culprit->getSourceRange(); 11074 return true; 11075 } 11076 11077 namespace { 11078 // Visits an initialization expression to see if OrigDecl is evaluated in 11079 // its own initialization and throws a warning if it does. 11080 class SelfReferenceChecker 11081 : public EvaluatedExprVisitor<SelfReferenceChecker> { 11082 Sema &S; 11083 Decl *OrigDecl; 11084 bool isRecordType; 11085 bool isPODType; 11086 bool isReferenceType; 11087 11088 bool isInitList; 11089 llvm::SmallVector<unsigned, 4> InitFieldIndex; 11090 11091 public: 11092 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 11093 11094 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 11095 S(S), OrigDecl(OrigDecl) { 11096 isPODType = false; 11097 isRecordType = false; 11098 isReferenceType = false; 11099 isInitList = false; 11100 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 11101 isPODType = VD->getType().isPODType(S.Context); 11102 isRecordType = VD->getType()->isRecordType(); 11103 isReferenceType = VD->getType()->isReferenceType(); 11104 } 11105 } 11106 11107 // For most expressions, just call the visitor. For initializer lists, 11108 // track the index of the field being initialized since fields are 11109 // initialized in order allowing use of previously initialized fields. 11110 void CheckExpr(Expr *E) { 11111 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 11112 if (!InitList) { 11113 Visit(E); 11114 return; 11115 } 11116 11117 // Track and increment the index here. 11118 isInitList = true; 11119 InitFieldIndex.push_back(0); 11120 for (auto Child : InitList->children()) { 11121 CheckExpr(cast<Expr>(Child)); 11122 ++InitFieldIndex.back(); 11123 } 11124 InitFieldIndex.pop_back(); 11125 } 11126 11127 // Returns true if MemberExpr is checked and no further checking is needed. 11128 // Returns false if additional checking is required. 11129 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 11130 llvm::SmallVector<FieldDecl*, 4> Fields; 11131 Expr *Base = E; 11132 bool ReferenceField = false; 11133 11134 // Get the field members used. 11135 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11136 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 11137 if (!FD) 11138 return false; 11139 Fields.push_back(FD); 11140 if (FD->getType()->isReferenceType()) 11141 ReferenceField = true; 11142 Base = ME->getBase()->IgnoreParenImpCasts(); 11143 } 11144 11145 // Keep checking only if the base Decl is the same. 11146 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 11147 if (!DRE || DRE->getDecl() != OrigDecl) 11148 return false; 11149 11150 // A reference field can be bound to an unininitialized field. 11151 if (CheckReference && !ReferenceField) 11152 return true; 11153 11154 // Convert FieldDecls to their index number. 11155 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 11156 for (const FieldDecl *I : llvm::reverse(Fields)) 11157 UsedFieldIndex.push_back(I->getFieldIndex()); 11158 11159 // See if a warning is needed by checking the first difference in index 11160 // numbers. If field being used has index less than the field being 11161 // initialized, then the use is safe. 11162 for (auto UsedIter = UsedFieldIndex.begin(), 11163 UsedEnd = UsedFieldIndex.end(), 11164 OrigIter = InitFieldIndex.begin(), 11165 OrigEnd = InitFieldIndex.end(); 11166 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 11167 if (*UsedIter < *OrigIter) 11168 return true; 11169 if (*UsedIter > *OrigIter) 11170 break; 11171 } 11172 11173 // TODO: Add a different warning which will print the field names. 11174 HandleDeclRefExpr(DRE); 11175 return true; 11176 } 11177 11178 // For most expressions, the cast is directly above the DeclRefExpr. 11179 // For conditional operators, the cast can be outside the conditional 11180 // operator if both expressions are DeclRefExpr's. 11181 void HandleValue(Expr *E) { 11182 E = E->IgnoreParens(); 11183 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 11184 HandleDeclRefExpr(DRE); 11185 return; 11186 } 11187 11188 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 11189 Visit(CO->getCond()); 11190 HandleValue(CO->getTrueExpr()); 11191 HandleValue(CO->getFalseExpr()); 11192 return; 11193 } 11194 11195 if (BinaryConditionalOperator *BCO = 11196 dyn_cast<BinaryConditionalOperator>(E)) { 11197 Visit(BCO->getCond()); 11198 HandleValue(BCO->getFalseExpr()); 11199 return; 11200 } 11201 11202 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 11203 HandleValue(OVE->getSourceExpr()); 11204 return; 11205 } 11206 11207 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11208 if (BO->getOpcode() == BO_Comma) { 11209 Visit(BO->getLHS()); 11210 HandleValue(BO->getRHS()); 11211 return; 11212 } 11213 } 11214 11215 if (isa<MemberExpr>(E)) { 11216 if (isInitList) { 11217 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 11218 false /*CheckReference*/)) 11219 return; 11220 } 11221 11222 Expr *Base = E->IgnoreParenImpCasts(); 11223 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11224 // Check for static member variables and don't warn on them. 11225 if (!isa<FieldDecl>(ME->getMemberDecl())) 11226 return; 11227 Base = ME->getBase()->IgnoreParenImpCasts(); 11228 } 11229 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 11230 HandleDeclRefExpr(DRE); 11231 return; 11232 } 11233 11234 Visit(E); 11235 } 11236 11237 // Reference types not handled in HandleValue are handled here since all 11238 // uses of references are bad, not just r-value uses. 11239 void VisitDeclRefExpr(DeclRefExpr *E) { 11240 if (isReferenceType) 11241 HandleDeclRefExpr(E); 11242 } 11243 11244 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 11245 if (E->getCastKind() == CK_LValueToRValue) { 11246 HandleValue(E->getSubExpr()); 11247 return; 11248 } 11249 11250 Inherited::VisitImplicitCastExpr(E); 11251 } 11252 11253 void VisitMemberExpr(MemberExpr *E) { 11254 if (isInitList) { 11255 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 11256 return; 11257 } 11258 11259 // Don't warn on arrays since they can be treated as pointers. 11260 if (E->getType()->canDecayToPointerType()) return; 11261 11262 // Warn when a non-static method call is followed by non-static member 11263 // field accesses, which is followed by a DeclRefExpr. 11264 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 11265 bool Warn = (MD && !MD->isStatic()); 11266 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 11267 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11268 if (!isa<FieldDecl>(ME->getMemberDecl())) 11269 Warn = false; 11270 Base = ME->getBase()->IgnoreParenImpCasts(); 11271 } 11272 11273 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 11274 if (Warn) 11275 HandleDeclRefExpr(DRE); 11276 return; 11277 } 11278 11279 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 11280 // Visit that expression. 11281 Visit(Base); 11282 } 11283 11284 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 11285 Expr *Callee = E->getCallee(); 11286 11287 if (isa<UnresolvedLookupExpr>(Callee)) 11288 return Inherited::VisitCXXOperatorCallExpr(E); 11289 11290 Visit(Callee); 11291 for (auto Arg: E->arguments()) 11292 HandleValue(Arg->IgnoreParenImpCasts()); 11293 } 11294 11295 void VisitUnaryOperator(UnaryOperator *E) { 11296 // For POD record types, addresses of its own members are well-defined. 11297 if (E->getOpcode() == UO_AddrOf && isRecordType && 11298 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 11299 if (!isPODType) 11300 HandleValue(E->getSubExpr()); 11301 return; 11302 } 11303 11304 if (E->isIncrementDecrementOp()) { 11305 HandleValue(E->getSubExpr()); 11306 return; 11307 } 11308 11309 Inherited::VisitUnaryOperator(E); 11310 } 11311 11312 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 11313 11314 void VisitCXXConstructExpr(CXXConstructExpr *E) { 11315 if (E->getConstructor()->isCopyConstructor()) { 11316 Expr *ArgExpr = E->getArg(0); 11317 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 11318 if (ILE->getNumInits() == 1) 11319 ArgExpr = ILE->getInit(0); 11320 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 11321 if (ICE->getCastKind() == CK_NoOp) 11322 ArgExpr = ICE->getSubExpr(); 11323 HandleValue(ArgExpr); 11324 return; 11325 } 11326 Inherited::VisitCXXConstructExpr(E); 11327 } 11328 11329 void VisitCallExpr(CallExpr *E) { 11330 // Treat std::move as a use. 11331 if (E->isCallToStdMove()) { 11332 HandleValue(E->getArg(0)); 11333 return; 11334 } 11335 11336 Inherited::VisitCallExpr(E); 11337 } 11338 11339 void VisitBinaryOperator(BinaryOperator *E) { 11340 if (E->isCompoundAssignmentOp()) { 11341 HandleValue(E->getLHS()); 11342 Visit(E->getRHS()); 11343 return; 11344 } 11345 11346 Inherited::VisitBinaryOperator(E); 11347 } 11348 11349 // A custom visitor for BinaryConditionalOperator is needed because the 11350 // regular visitor would check the condition and true expression separately 11351 // but both point to the same place giving duplicate diagnostics. 11352 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 11353 Visit(E->getCond()); 11354 Visit(E->getFalseExpr()); 11355 } 11356 11357 void HandleDeclRefExpr(DeclRefExpr *DRE) { 11358 Decl* ReferenceDecl = DRE->getDecl(); 11359 if (OrigDecl != ReferenceDecl) return; 11360 unsigned diag; 11361 if (isReferenceType) { 11362 diag = diag::warn_uninit_self_reference_in_reference_init; 11363 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 11364 diag = diag::warn_static_self_reference_in_init; 11365 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 11366 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 11367 DRE->getDecl()->getType()->isRecordType()) { 11368 diag = diag::warn_uninit_self_reference_in_init; 11369 } else { 11370 // Local variables will be handled by the CFG analysis. 11371 return; 11372 } 11373 11374 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE, 11375 S.PDiag(diag) 11376 << DRE->getDecl() << OrigDecl->getLocation() 11377 << DRE->getSourceRange()); 11378 } 11379 }; 11380 11381 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 11382 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 11383 bool DirectInit) { 11384 // Parameters arguments are occassionially constructed with itself, 11385 // for instance, in recursive functions. Skip them. 11386 if (isa<ParmVarDecl>(OrigDecl)) 11387 return; 11388 11389 E = E->IgnoreParens(); 11390 11391 // Skip checking T a = a where T is not a record or reference type. 11392 // Doing so is a way to silence uninitialized warnings. 11393 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 11394 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 11395 if (ICE->getCastKind() == CK_LValueToRValue) 11396 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 11397 if (DRE->getDecl() == OrigDecl) 11398 return; 11399 11400 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 11401 } 11402 } // end anonymous namespace 11403 11404 namespace { 11405 // Simple wrapper to add the name of a variable or (if no variable is 11406 // available) a DeclarationName into a diagnostic. 11407 struct VarDeclOrName { 11408 VarDecl *VDecl; 11409 DeclarationName Name; 11410 11411 friend const Sema::SemaDiagnosticBuilder & 11412 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 11413 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 11414 } 11415 }; 11416 } // end anonymous namespace 11417 11418 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 11419 DeclarationName Name, QualType Type, 11420 TypeSourceInfo *TSI, 11421 SourceRange Range, bool DirectInit, 11422 Expr *Init) { 11423 bool IsInitCapture = !VDecl; 11424 assert((!VDecl || !VDecl->isInitCapture()) && 11425 "init captures are expected to be deduced prior to initialization"); 11426 11427 VarDeclOrName VN{VDecl, Name}; 11428 11429 DeducedType *Deduced = Type->getContainedDeducedType(); 11430 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 11431 11432 // C++11 [dcl.spec.auto]p3 11433 if (!Init) { 11434 assert(VDecl && "no init for init capture deduction?"); 11435 11436 // Except for class argument deduction, and then for an initializing 11437 // declaration only, i.e. no static at class scope or extern. 11438 if (!isa<DeducedTemplateSpecializationType>(Deduced) || 11439 VDecl->hasExternalStorage() || 11440 VDecl->isStaticDataMember()) { 11441 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 11442 << VDecl->getDeclName() << Type; 11443 return QualType(); 11444 } 11445 } 11446 11447 ArrayRef<Expr*> DeduceInits; 11448 if (Init) 11449 DeduceInits = Init; 11450 11451 if (DirectInit) { 11452 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) 11453 DeduceInits = PL->exprs(); 11454 } 11455 11456 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 11457 assert(VDecl && "non-auto type for init capture deduction?"); 11458 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 11459 InitializationKind Kind = InitializationKind::CreateForInit( 11460 VDecl->getLocation(), DirectInit, Init); 11461 // FIXME: Initialization should not be taking a mutable list of inits. 11462 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 11463 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 11464 InitsCopy); 11465 } 11466 11467 if (DirectInit) { 11468 if (auto *IL = dyn_cast<InitListExpr>(Init)) 11469 DeduceInits = IL->inits(); 11470 } 11471 11472 // Deduction only works if we have exactly one source expression. 11473 if (DeduceInits.empty()) { 11474 // It isn't possible to write this directly, but it is possible to 11475 // end up in this situation with "auto x(some_pack...);" 11476 Diag(Init->getBeginLoc(), IsInitCapture 11477 ? diag::err_init_capture_no_expression 11478 : diag::err_auto_var_init_no_expression) 11479 << VN << Type << Range; 11480 return QualType(); 11481 } 11482 11483 if (DeduceInits.size() > 1) { 11484 Diag(DeduceInits[1]->getBeginLoc(), 11485 IsInitCapture ? diag::err_init_capture_multiple_expressions 11486 : diag::err_auto_var_init_multiple_expressions) 11487 << VN << Type << Range; 11488 return QualType(); 11489 } 11490 11491 Expr *DeduceInit = DeduceInits[0]; 11492 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 11493 Diag(Init->getBeginLoc(), IsInitCapture 11494 ? diag::err_init_capture_paren_braces 11495 : diag::err_auto_var_init_paren_braces) 11496 << isa<InitListExpr>(Init) << VN << Type << Range; 11497 return QualType(); 11498 } 11499 11500 // Expressions default to 'id' when we're in a debugger. 11501 bool DefaultedAnyToId = false; 11502 if (getLangOpts().DebuggerCastResultToId && 11503 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 11504 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 11505 if (Result.isInvalid()) { 11506 return QualType(); 11507 } 11508 Init = Result.get(); 11509 DefaultedAnyToId = true; 11510 } 11511 11512 // C++ [dcl.decomp]p1: 11513 // If the assignment-expression [...] has array type A and no ref-qualifier 11514 // is present, e has type cv A 11515 if (VDecl && isa<DecompositionDecl>(VDecl) && 11516 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 11517 DeduceInit->getType()->isConstantArrayType()) 11518 return Context.getQualifiedType(DeduceInit->getType(), 11519 Type.getQualifiers()); 11520 11521 QualType DeducedType; 11522 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 11523 if (!IsInitCapture) 11524 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 11525 else if (isa<InitListExpr>(Init)) 11526 Diag(Range.getBegin(), 11527 diag::err_init_capture_deduction_failure_from_init_list) 11528 << VN 11529 << (DeduceInit->getType().isNull() ? TSI->getType() 11530 : DeduceInit->getType()) 11531 << DeduceInit->getSourceRange(); 11532 else 11533 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 11534 << VN << TSI->getType() 11535 << (DeduceInit->getType().isNull() ? TSI->getType() 11536 : DeduceInit->getType()) 11537 << DeduceInit->getSourceRange(); 11538 } 11539 11540 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 11541 // 'id' instead of a specific object type prevents most of our usual 11542 // checks. 11543 // We only want to warn outside of template instantiations, though: 11544 // inside a template, the 'id' could have come from a parameter. 11545 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 11546 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 11547 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 11548 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 11549 } 11550 11551 return DeducedType; 11552 } 11553 11554 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 11555 Expr *Init) { 11556 assert(!Init || !Init->containsErrors()); 11557 QualType DeducedType = deduceVarTypeFromInitializer( 11558 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 11559 VDecl->getSourceRange(), DirectInit, Init); 11560 if (DeducedType.isNull()) { 11561 VDecl->setInvalidDecl(); 11562 return true; 11563 } 11564 11565 VDecl->setType(DeducedType); 11566 assert(VDecl->isLinkageValid()); 11567 11568 // In ARC, infer lifetime. 11569 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 11570 VDecl->setInvalidDecl(); 11571 11572 if (getLangOpts().OpenCL) 11573 deduceOpenCLAddressSpace(VDecl); 11574 11575 // If this is a redeclaration, check that the type we just deduced matches 11576 // the previously declared type. 11577 if (VarDecl *Old = VDecl->getPreviousDecl()) { 11578 // We never need to merge the type, because we cannot form an incomplete 11579 // array of auto, nor deduce such a type. 11580 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 11581 } 11582 11583 // Check the deduced type is valid for a variable declaration. 11584 CheckVariableDeclarationType(VDecl); 11585 return VDecl->isInvalidDecl(); 11586 } 11587 11588 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init, 11589 SourceLocation Loc) { 11590 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init)) 11591 Init = EWC->getSubExpr(); 11592 11593 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 11594 Init = CE->getSubExpr(); 11595 11596 QualType InitType = Init->getType(); 11597 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 11598 InitType.hasNonTrivialToPrimitiveCopyCUnion()) && 11599 "shouldn't be called if type doesn't have a non-trivial C struct"); 11600 if (auto *ILE = dyn_cast<InitListExpr>(Init)) { 11601 for (auto I : ILE->inits()) { 11602 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() && 11603 !I->getType().hasNonTrivialToPrimitiveCopyCUnion()) 11604 continue; 11605 SourceLocation SL = I->getExprLoc(); 11606 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc); 11607 } 11608 return; 11609 } 11610 11611 if (isa<ImplicitValueInitExpr>(Init)) { 11612 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 11613 checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject, 11614 NTCUK_Init); 11615 } else { 11616 // Assume all other explicit initializers involving copying some existing 11617 // object. 11618 // TODO: ignore any explicit initializers where we can guarantee 11619 // copy-elision. 11620 if (InitType.hasNonTrivialToPrimitiveCopyCUnion()) 11621 checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy); 11622 } 11623 } 11624 11625 namespace { 11626 11627 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) { 11628 // Ignore unavailable fields. A field can be marked as unavailable explicitly 11629 // in the source code or implicitly by the compiler if it is in a union 11630 // defined in a system header and has non-trivial ObjC ownership 11631 // qualifications. We don't want those fields to participate in determining 11632 // whether the containing union is non-trivial. 11633 return FD->hasAttr<UnavailableAttr>(); 11634 } 11635 11636 struct DiagNonTrivalCUnionDefaultInitializeVisitor 11637 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 11638 void> { 11639 using Super = 11640 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 11641 void>; 11642 11643 DiagNonTrivalCUnionDefaultInitializeVisitor( 11644 QualType OrigTy, SourceLocation OrigLoc, 11645 Sema::NonTrivialCUnionContext UseContext, Sema &S) 11646 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11647 11648 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT, 11649 const FieldDecl *FD, bool InNonTrivialUnion) { 11650 if (const auto *AT = S.Context.getAsArrayType(QT)) 11651 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11652 InNonTrivialUnion); 11653 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion); 11654 } 11655 11656 void visitARCStrong(QualType QT, const FieldDecl *FD, 11657 bool InNonTrivialUnion) { 11658 if (InNonTrivialUnion) 11659 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11660 << 1 << 0 << QT << FD->getName(); 11661 } 11662 11663 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11664 if (InNonTrivialUnion) 11665 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11666 << 1 << 0 << QT << FD->getName(); 11667 } 11668 11669 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11670 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11671 if (RD->isUnion()) { 11672 if (OrigLoc.isValid()) { 11673 bool IsUnion = false; 11674 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11675 IsUnion = OrigRD->isUnion(); 11676 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11677 << 0 << OrigTy << IsUnion << UseContext; 11678 // Reset OrigLoc so that this diagnostic is emitted only once. 11679 OrigLoc = SourceLocation(); 11680 } 11681 InNonTrivialUnion = true; 11682 } 11683 11684 if (InNonTrivialUnion) 11685 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11686 << 0 << 0 << QT.getUnqualifiedType() << ""; 11687 11688 for (const FieldDecl *FD : RD->fields()) 11689 if (!shouldIgnoreForRecordTriviality(FD)) 11690 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11691 } 11692 11693 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11694 11695 // The non-trivial C union type or the struct/union type that contains a 11696 // non-trivial C union. 11697 QualType OrigTy; 11698 SourceLocation OrigLoc; 11699 Sema::NonTrivialCUnionContext UseContext; 11700 Sema &S; 11701 }; 11702 11703 struct DiagNonTrivalCUnionDestructedTypeVisitor 11704 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> { 11705 using Super = 11706 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>; 11707 11708 DiagNonTrivalCUnionDestructedTypeVisitor( 11709 QualType OrigTy, SourceLocation OrigLoc, 11710 Sema::NonTrivialCUnionContext UseContext, Sema &S) 11711 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11712 11713 void visitWithKind(QualType::DestructionKind DK, QualType QT, 11714 const FieldDecl *FD, bool InNonTrivialUnion) { 11715 if (const auto *AT = S.Context.getAsArrayType(QT)) 11716 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11717 InNonTrivialUnion); 11718 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion); 11719 } 11720 11721 void visitARCStrong(QualType QT, const FieldDecl *FD, 11722 bool InNonTrivialUnion) { 11723 if (InNonTrivialUnion) 11724 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11725 << 1 << 1 << QT << FD->getName(); 11726 } 11727 11728 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11729 if (InNonTrivialUnion) 11730 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11731 << 1 << 1 << QT << FD->getName(); 11732 } 11733 11734 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11735 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11736 if (RD->isUnion()) { 11737 if (OrigLoc.isValid()) { 11738 bool IsUnion = false; 11739 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11740 IsUnion = OrigRD->isUnion(); 11741 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11742 << 1 << OrigTy << IsUnion << UseContext; 11743 // Reset OrigLoc so that this diagnostic is emitted only once. 11744 OrigLoc = SourceLocation(); 11745 } 11746 InNonTrivialUnion = true; 11747 } 11748 11749 if (InNonTrivialUnion) 11750 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11751 << 0 << 1 << QT.getUnqualifiedType() << ""; 11752 11753 for (const FieldDecl *FD : RD->fields()) 11754 if (!shouldIgnoreForRecordTriviality(FD)) 11755 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11756 } 11757 11758 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11759 void visitCXXDestructor(QualType QT, const FieldDecl *FD, 11760 bool InNonTrivialUnion) {} 11761 11762 // The non-trivial C union type or the struct/union type that contains a 11763 // non-trivial C union. 11764 QualType OrigTy; 11765 SourceLocation OrigLoc; 11766 Sema::NonTrivialCUnionContext UseContext; 11767 Sema &S; 11768 }; 11769 11770 struct DiagNonTrivalCUnionCopyVisitor 11771 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> { 11772 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>; 11773 11774 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc, 11775 Sema::NonTrivialCUnionContext UseContext, 11776 Sema &S) 11777 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11778 11779 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT, 11780 const FieldDecl *FD, bool InNonTrivialUnion) { 11781 if (const auto *AT = S.Context.getAsArrayType(QT)) 11782 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11783 InNonTrivialUnion); 11784 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion); 11785 } 11786 11787 void visitARCStrong(QualType QT, const FieldDecl *FD, 11788 bool InNonTrivialUnion) { 11789 if (InNonTrivialUnion) 11790 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11791 << 1 << 2 << QT << FD->getName(); 11792 } 11793 11794 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11795 if (InNonTrivialUnion) 11796 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11797 << 1 << 2 << QT << FD->getName(); 11798 } 11799 11800 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11801 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11802 if (RD->isUnion()) { 11803 if (OrigLoc.isValid()) { 11804 bool IsUnion = false; 11805 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11806 IsUnion = OrigRD->isUnion(); 11807 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11808 << 2 << OrigTy << IsUnion << UseContext; 11809 // Reset OrigLoc so that this diagnostic is emitted only once. 11810 OrigLoc = SourceLocation(); 11811 } 11812 InNonTrivialUnion = true; 11813 } 11814 11815 if (InNonTrivialUnion) 11816 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11817 << 0 << 2 << QT.getUnqualifiedType() << ""; 11818 11819 for (const FieldDecl *FD : RD->fields()) 11820 if (!shouldIgnoreForRecordTriviality(FD)) 11821 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11822 } 11823 11824 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT, 11825 const FieldDecl *FD, bool InNonTrivialUnion) {} 11826 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11827 void visitVolatileTrivial(QualType QT, const FieldDecl *FD, 11828 bool InNonTrivialUnion) {} 11829 11830 // The non-trivial C union type or the struct/union type that contains a 11831 // non-trivial C union. 11832 QualType OrigTy; 11833 SourceLocation OrigLoc; 11834 Sema::NonTrivialCUnionContext UseContext; 11835 Sema &S; 11836 }; 11837 11838 } // namespace 11839 11840 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc, 11841 NonTrivialCUnionContext UseContext, 11842 unsigned NonTrivialKind) { 11843 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 11844 QT.hasNonTrivialToPrimitiveDestructCUnion() || 11845 QT.hasNonTrivialToPrimitiveCopyCUnion()) && 11846 "shouldn't be called if type doesn't have a non-trivial C union"); 11847 11848 if ((NonTrivialKind & NTCUK_Init) && 11849 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 11850 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this) 11851 .visit(QT, nullptr, false); 11852 if ((NonTrivialKind & NTCUK_Destruct) && 11853 QT.hasNonTrivialToPrimitiveDestructCUnion()) 11854 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this) 11855 .visit(QT, nullptr, false); 11856 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion()) 11857 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this) 11858 .visit(QT, nullptr, false); 11859 } 11860 11861 /// AddInitializerToDecl - Adds the initializer Init to the 11862 /// declaration dcl. If DirectInit is true, this is C++ direct 11863 /// initialization rather than copy initialization. 11864 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 11865 // If there is no declaration, there was an error parsing it. Just ignore 11866 // the initializer. 11867 if (!RealDecl || RealDecl->isInvalidDecl()) { 11868 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 11869 return; 11870 } 11871 11872 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 11873 // Pure-specifiers are handled in ActOnPureSpecifier. 11874 Diag(Method->getLocation(), diag::err_member_function_initialization) 11875 << Method->getDeclName() << Init->getSourceRange(); 11876 Method->setInvalidDecl(); 11877 return; 11878 } 11879 11880 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 11881 if (!VDecl) { 11882 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 11883 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 11884 RealDecl->setInvalidDecl(); 11885 return; 11886 } 11887 11888 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 11889 if (VDecl->getType()->isUndeducedType()) { 11890 // Attempt typo correction early so that the type of the init expression can 11891 // be deduced based on the chosen correction if the original init contains a 11892 // TypoExpr. 11893 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 11894 if (!Res.isUsable()) { 11895 // There are unresolved typos in Init, just drop them. 11896 // FIXME: improve the recovery strategy to preserve the Init. 11897 RealDecl->setInvalidDecl(); 11898 return; 11899 } 11900 if (Res.get()->containsErrors()) { 11901 // Invalidate the decl as we don't know the type for recovery-expr yet. 11902 RealDecl->setInvalidDecl(); 11903 VDecl->setInit(Res.get()); 11904 return; 11905 } 11906 Init = Res.get(); 11907 11908 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 11909 return; 11910 } 11911 11912 // dllimport cannot be used on variable definitions. 11913 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 11914 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 11915 VDecl->setInvalidDecl(); 11916 return; 11917 } 11918 11919 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 11920 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 11921 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 11922 VDecl->setInvalidDecl(); 11923 return; 11924 } 11925 11926 if (!VDecl->getType()->isDependentType()) { 11927 // A definition must end up with a complete type, which means it must be 11928 // complete with the restriction that an array type might be completed by 11929 // the initializer; note that later code assumes this restriction. 11930 QualType BaseDeclType = VDecl->getType(); 11931 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 11932 BaseDeclType = Array->getElementType(); 11933 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 11934 diag::err_typecheck_decl_incomplete_type)) { 11935 RealDecl->setInvalidDecl(); 11936 return; 11937 } 11938 11939 // The variable can not have an abstract class type. 11940 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 11941 diag::err_abstract_type_in_decl, 11942 AbstractVariableType)) 11943 VDecl->setInvalidDecl(); 11944 } 11945 11946 // If adding the initializer will turn this declaration into a definition, 11947 // and we already have a definition for this variable, diagnose or otherwise 11948 // handle the situation. 11949 VarDecl *Def; 11950 if ((Def = VDecl->getDefinition()) && Def != VDecl && 11951 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 11952 !VDecl->isThisDeclarationADemotedDefinition() && 11953 checkVarDeclRedefinition(Def, VDecl)) 11954 return; 11955 11956 if (getLangOpts().CPlusPlus) { 11957 // C++ [class.static.data]p4 11958 // If a static data member is of const integral or const 11959 // enumeration type, its declaration in the class definition can 11960 // specify a constant-initializer which shall be an integral 11961 // constant expression (5.19). In that case, the member can appear 11962 // in integral constant expressions. The member shall still be 11963 // defined in a namespace scope if it is used in the program and the 11964 // namespace scope definition shall not contain an initializer. 11965 // 11966 // We already performed a redefinition check above, but for static 11967 // data members we also need to check whether there was an in-class 11968 // declaration with an initializer. 11969 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 11970 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 11971 << VDecl->getDeclName(); 11972 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 11973 diag::note_previous_initializer) 11974 << 0; 11975 return; 11976 } 11977 11978 if (VDecl->hasLocalStorage()) 11979 setFunctionHasBranchProtectedScope(); 11980 11981 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 11982 VDecl->setInvalidDecl(); 11983 return; 11984 } 11985 } 11986 11987 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 11988 // a kernel function cannot be initialized." 11989 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 11990 Diag(VDecl->getLocation(), diag::err_local_cant_init); 11991 VDecl->setInvalidDecl(); 11992 return; 11993 } 11994 11995 // The LoaderUninitialized attribute acts as a definition (of undef). 11996 if (VDecl->hasAttr<LoaderUninitializedAttr>()) { 11997 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init); 11998 VDecl->setInvalidDecl(); 11999 return; 12000 } 12001 12002 // Get the decls type and save a reference for later, since 12003 // CheckInitializerTypes may change it. 12004 QualType DclT = VDecl->getType(), SavT = DclT; 12005 12006 // Expressions default to 'id' when we're in a debugger 12007 // and we are assigning it to a variable of Objective-C pointer type. 12008 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 12009 Init->getType() == Context.UnknownAnyTy) { 12010 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 12011 if (Result.isInvalid()) { 12012 VDecl->setInvalidDecl(); 12013 return; 12014 } 12015 Init = Result.get(); 12016 } 12017 12018 // Perform the initialization. 12019 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 12020 if (!VDecl->isInvalidDecl()) { 12021 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 12022 InitializationKind Kind = InitializationKind::CreateForInit( 12023 VDecl->getLocation(), DirectInit, Init); 12024 12025 MultiExprArg Args = Init; 12026 if (CXXDirectInit) 12027 Args = MultiExprArg(CXXDirectInit->getExprs(), 12028 CXXDirectInit->getNumExprs()); 12029 12030 // Try to correct any TypoExprs in the initialization arguments. 12031 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 12032 ExprResult Res = CorrectDelayedTyposInExpr( 12033 Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/false, 12034 [this, Entity, Kind](Expr *E) { 12035 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 12036 return Init.Failed() ? ExprError() : E; 12037 }); 12038 if (Res.isInvalid()) { 12039 VDecl->setInvalidDecl(); 12040 } else if (Res.get() != Args[Idx]) { 12041 Args[Idx] = Res.get(); 12042 } 12043 } 12044 if (VDecl->isInvalidDecl()) 12045 return; 12046 12047 InitializationSequence InitSeq(*this, Entity, Kind, Args, 12048 /*TopLevelOfInitList=*/false, 12049 /*TreatUnavailableAsInvalid=*/false); 12050 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 12051 if (Result.isInvalid()) { 12052 // If the provied initializer fails to initialize the var decl, 12053 // we attach a recovery expr for better recovery. 12054 auto RecoveryExpr = 12055 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args); 12056 if (RecoveryExpr.get()) 12057 VDecl->setInit(RecoveryExpr.get()); 12058 return; 12059 } 12060 12061 Init = Result.getAs<Expr>(); 12062 } 12063 12064 // Check for self-references within variable initializers. 12065 // Variables declared within a function/method body (except for references) 12066 // are handled by a dataflow analysis. 12067 // This is undefined behavior in C++, but valid in C. 12068 if (getLangOpts().CPlusPlus) { 12069 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 12070 VDecl->getType()->isReferenceType()) { 12071 CheckSelfReference(*this, RealDecl, Init, DirectInit); 12072 } 12073 } 12074 12075 // If the type changed, it means we had an incomplete type that was 12076 // completed by the initializer. For example: 12077 // int ary[] = { 1, 3, 5 }; 12078 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 12079 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 12080 VDecl->setType(DclT); 12081 12082 if (!VDecl->isInvalidDecl()) { 12083 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 12084 12085 if (VDecl->hasAttr<BlocksAttr>()) 12086 checkRetainCycles(VDecl, Init); 12087 12088 // It is safe to assign a weak reference into a strong variable. 12089 // Although this code can still have problems: 12090 // id x = self.weakProp; 12091 // id y = self.weakProp; 12092 // we do not warn to warn spuriously when 'x' and 'y' are on separate 12093 // paths through the function. This should be revisited if 12094 // -Wrepeated-use-of-weak is made flow-sensitive. 12095 if (FunctionScopeInfo *FSI = getCurFunction()) 12096 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 12097 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 12098 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 12099 Init->getBeginLoc())) 12100 FSI->markSafeWeakUse(Init); 12101 } 12102 12103 // The initialization is usually a full-expression. 12104 // 12105 // FIXME: If this is a braced initialization of an aggregate, it is not 12106 // an expression, and each individual field initializer is a separate 12107 // full-expression. For instance, in: 12108 // 12109 // struct Temp { ~Temp(); }; 12110 // struct S { S(Temp); }; 12111 // struct T { S a, b; } t = { Temp(), Temp() } 12112 // 12113 // we should destroy the first Temp before constructing the second. 12114 ExprResult Result = 12115 ActOnFinishFullExpr(Init, VDecl->getLocation(), 12116 /*DiscardedValue*/ false, VDecl->isConstexpr()); 12117 if (Result.isInvalid()) { 12118 VDecl->setInvalidDecl(); 12119 return; 12120 } 12121 Init = Result.get(); 12122 12123 // Attach the initializer to the decl. 12124 VDecl->setInit(Init); 12125 12126 if (VDecl->isLocalVarDecl()) { 12127 // Don't check the initializer if the declaration is malformed. 12128 if (VDecl->isInvalidDecl()) { 12129 // do nothing 12130 12131 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 12132 // This is true even in C++ for OpenCL. 12133 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 12134 CheckForConstantInitializer(Init, DclT); 12135 12136 // Otherwise, C++ does not restrict the initializer. 12137 } else if (getLangOpts().CPlusPlus) { 12138 // do nothing 12139 12140 // C99 6.7.8p4: All the expressions in an initializer for an object that has 12141 // static storage duration shall be constant expressions or string literals. 12142 } else if (VDecl->getStorageClass() == SC_Static) { 12143 CheckForConstantInitializer(Init, DclT); 12144 12145 // C89 is stricter than C99 for aggregate initializers. 12146 // C89 6.5.7p3: All the expressions [...] in an initializer list 12147 // for an object that has aggregate or union type shall be 12148 // constant expressions. 12149 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 12150 isa<InitListExpr>(Init)) { 12151 const Expr *Culprit; 12152 if (!Init->isConstantInitializer(Context, false, &Culprit)) { 12153 Diag(Culprit->getExprLoc(), 12154 diag::ext_aggregate_init_not_constant) 12155 << Culprit->getSourceRange(); 12156 } 12157 } 12158 12159 if (auto *E = dyn_cast<ExprWithCleanups>(Init)) 12160 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens())) 12161 if (VDecl->hasLocalStorage()) 12162 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 12163 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 12164 VDecl->getLexicalDeclContext()->isRecord()) { 12165 // This is an in-class initialization for a static data member, e.g., 12166 // 12167 // struct S { 12168 // static const int value = 17; 12169 // }; 12170 12171 // C++ [class.mem]p4: 12172 // A member-declarator can contain a constant-initializer only 12173 // if it declares a static member (9.4) of const integral or 12174 // const enumeration type, see 9.4.2. 12175 // 12176 // C++11 [class.static.data]p3: 12177 // If a non-volatile non-inline const static data member is of integral 12178 // or enumeration type, its declaration in the class definition can 12179 // specify a brace-or-equal-initializer in which every initializer-clause 12180 // that is an assignment-expression is a constant expression. A static 12181 // data member of literal type can be declared in the class definition 12182 // with the constexpr specifier; if so, its declaration shall specify a 12183 // brace-or-equal-initializer in which every initializer-clause that is 12184 // an assignment-expression is a constant expression. 12185 12186 // Do nothing on dependent types. 12187 if (DclT->isDependentType()) { 12188 12189 // Allow any 'static constexpr' members, whether or not they are of literal 12190 // type. We separately check that every constexpr variable is of literal 12191 // type. 12192 } else if (VDecl->isConstexpr()) { 12193 12194 // Require constness. 12195 } else if (!DclT.isConstQualified()) { 12196 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 12197 << Init->getSourceRange(); 12198 VDecl->setInvalidDecl(); 12199 12200 // We allow integer constant expressions in all cases. 12201 } else if (DclT->isIntegralOrEnumerationType()) { 12202 // Check whether the expression is a constant expression. 12203 SourceLocation Loc; 12204 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 12205 // In C++11, a non-constexpr const static data member with an 12206 // in-class initializer cannot be volatile. 12207 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 12208 else if (Init->isValueDependent()) 12209 ; // Nothing to check. 12210 else if (Init->isIntegerConstantExpr(Context, &Loc)) 12211 ; // Ok, it's an ICE! 12212 else if (Init->getType()->isScopedEnumeralType() && 12213 Init->isCXX11ConstantExpr(Context)) 12214 ; // Ok, it is a scoped-enum constant expression. 12215 else if (Init->isEvaluatable(Context)) { 12216 // If we can constant fold the initializer through heroics, accept it, 12217 // but report this as a use of an extension for -pedantic. 12218 Diag(Loc, diag::ext_in_class_initializer_non_constant) 12219 << Init->getSourceRange(); 12220 } else { 12221 // Otherwise, this is some crazy unknown case. Report the issue at the 12222 // location provided by the isIntegerConstantExpr failed check. 12223 Diag(Loc, diag::err_in_class_initializer_non_constant) 12224 << Init->getSourceRange(); 12225 VDecl->setInvalidDecl(); 12226 } 12227 12228 // We allow foldable floating-point constants as an extension. 12229 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 12230 // In C++98, this is a GNU extension. In C++11, it is not, but we support 12231 // it anyway and provide a fixit to add the 'constexpr'. 12232 if (getLangOpts().CPlusPlus11) { 12233 Diag(VDecl->getLocation(), 12234 diag::ext_in_class_initializer_float_type_cxx11) 12235 << DclT << Init->getSourceRange(); 12236 Diag(VDecl->getBeginLoc(), 12237 diag::note_in_class_initializer_float_type_cxx11) 12238 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12239 } else { 12240 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 12241 << DclT << Init->getSourceRange(); 12242 12243 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 12244 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 12245 << Init->getSourceRange(); 12246 VDecl->setInvalidDecl(); 12247 } 12248 } 12249 12250 // Suggest adding 'constexpr' in C++11 for literal types. 12251 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 12252 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 12253 << DclT << Init->getSourceRange() 12254 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12255 VDecl->setConstexpr(true); 12256 12257 } else { 12258 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 12259 << DclT << Init->getSourceRange(); 12260 VDecl->setInvalidDecl(); 12261 } 12262 } else if (VDecl->isFileVarDecl()) { 12263 // In C, extern is typically used to avoid tentative definitions when 12264 // declaring variables in headers, but adding an intializer makes it a 12265 // definition. This is somewhat confusing, so GCC and Clang both warn on it. 12266 // In C++, extern is often used to give implictly static const variables 12267 // external linkage, so don't warn in that case. If selectany is present, 12268 // this might be header code intended for C and C++ inclusion, so apply the 12269 // C++ rules. 12270 if (VDecl->getStorageClass() == SC_Extern && 12271 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 12272 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 12273 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 12274 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 12275 Diag(VDecl->getLocation(), diag::warn_extern_init); 12276 12277 // In Microsoft C++ mode, a const variable defined in namespace scope has 12278 // external linkage by default if the variable is declared with 12279 // __declspec(dllexport). 12280 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 12281 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() && 12282 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition()) 12283 VDecl->setStorageClass(SC_Extern); 12284 12285 // C99 6.7.8p4. All file scoped initializers need to be constant. 12286 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 12287 CheckForConstantInitializer(Init, DclT); 12288 } 12289 12290 QualType InitType = Init->getType(); 12291 if (!InitType.isNull() && 12292 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12293 InitType.hasNonTrivialToPrimitiveCopyCUnion())) 12294 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc()); 12295 12296 // We will represent direct-initialization similarly to copy-initialization: 12297 // int x(1); -as-> int x = 1; 12298 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 12299 // 12300 // Clients that want to distinguish between the two forms, can check for 12301 // direct initializer using VarDecl::getInitStyle(). 12302 // A major benefit is that clients that don't particularly care about which 12303 // exactly form was it (like the CodeGen) can handle both cases without 12304 // special case code. 12305 12306 // C++ 8.5p11: 12307 // The form of initialization (using parentheses or '=') is generally 12308 // insignificant, but does matter when the entity being initialized has a 12309 // class type. 12310 if (CXXDirectInit) { 12311 assert(DirectInit && "Call-style initializer must be direct init."); 12312 VDecl->setInitStyle(VarDecl::CallInit); 12313 } else if (DirectInit) { 12314 // This must be list-initialization. No other way is direct-initialization. 12315 VDecl->setInitStyle(VarDecl::ListInit); 12316 } 12317 12318 if (LangOpts.OpenMP && VDecl->isFileVarDecl()) 12319 DeclsToCheckForDeferredDiags.push_back(VDecl); 12320 CheckCompleteVariableDeclaration(VDecl); 12321 } 12322 12323 /// ActOnInitializerError - Given that there was an error parsing an 12324 /// initializer for the given declaration, try to return to some form 12325 /// of sanity. 12326 void Sema::ActOnInitializerError(Decl *D) { 12327 // Our main concern here is re-establishing invariants like "a 12328 // variable's type is either dependent or complete". 12329 if (!D || D->isInvalidDecl()) return; 12330 12331 VarDecl *VD = dyn_cast<VarDecl>(D); 12332 if (!VD) return; 12333 12334 // Bindings are not usable if we can't make sense of the initializer. 12335 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 12336 for (auto *BD : DD->bindings()) 12337 BD->setInvalidDecl(); 12338 12339 // Auto types are meaningless if we can't make sense of the initializer. 12340 if (VD->getType()->isUndeducedType()) { 12341 D->setInvalidDecl(); 12342 return; 12343 } 12344 12345 QualType Ty = VD->getType(); 12346 if (Ty->isDependentType()) return; 12347 12348 // Require a complete type. 12349 if (RequireCompleteType(VD->getLocation(), 12350 Context.getBaseElementType(Ty), 12351 diag::err_typecheck_decl_incomplete_type)) { 12352 VD->setInvalidDecl(); 12353 return; 12354 } 12355 12356 // Require a non-abstract type. 12357 if (RequireNonAbstractType(VD->getLocation(), Ty, 12358 diag::err_abstract_type_in_decl, 12359 AbstractVariableType)) { 12360 VD->setInvalidDecl(); 12361 return; 12362 } 12363 12364 // Don't bother complaining about constructors or destructors, 12365 // though. 12366 } 12367 12368 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 12369 // If there is no declaration, there was an error parsing it. Just ignore it. 12370 if (!RealDecl) 12371 return; 12372 12373 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 12374 QualType Type = Var->getType(); 12375 12376 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 12377 if (isa<DecompositionDecl>(RealDecl)) { 12378 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 12379 Var->setInvalidDecl(); 12380 return; 12381 } 12382 12383 if (Type->isUndeducedType() && 12384 DeduceVariableDeclarationType(Var, false, nullptr)) 12385 return; 12386 12387 // C++11 [class.static.data]p3: A static data member can be declared with 12388 // the constexpr specifier; if so, its declaration shall specify 12389 // a brace-or-equal-initializer. 12390 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 12391 // the definition of a variable [...] or the declaration of a static data 12392 // member. 12393 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 12394 !Var->isThisDeclarationADemotedDefinition()) { 12395 if (Var->isStaticDataMember()) { 12396 // C++1z removes the relevant rule; the in-class declaration is always 12397 // a definition there. 12398 if (!getLangOpts().CPlusPlus17 && 12399 !Context.getTargetInfo().getCXXABI().isMicrosoft()) { 12400 Diag(Var->getLocation(), 12401 diag::err_constexpr_static_mem_var_requires_init) 12402 << Var->getDeclName(); 12403 Var->setInvalidDecl(); 12404 return; 12405 } 12406 } else { 12407 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 12408 Var->setInvalidDecl(); 12409 return; 12410 } 12411 } 12412 12413 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 12414 // be initialized. 12415 if (!Var->isInvalidDecl() && 12416 Var->getType().getAddressSpace() == LangAS::opencl_constant && 12417 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 12418 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 12419 Var->setInvalidDecl(); 12420 return; 12421 } 12422 12423 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) { 12424 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) { 12425 if (!RD->hasTrivialDefaultConstructor()) { 12426 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor); 12427 Var->setInvalidDecl(); 12428 return; 12429 } 12430 } 12431 if (Var->getStorageClass() == SC_Extern) { 12432 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl) 12433 << Var; 12434 Var->setInvalidDecl(); 12435 return; 12436 } 12437 } 12438 12439 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition(); 12440 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly && 12441 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 12442 checkNonTrivialCUnion(Var->getType(), Var->getLocation(), 12443 NTCUC_DefaultInitializedObject, NTCUK_Init); 12444 12445 12446 switch (DefKind) { 12447 case VarDecl::Definition: 12448 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 12449 break; 12450 12451 // We have an out-of-line definition of a static data member 12452 // that has an in-class initializer, so we type-check this like 12453 // a declaration. 12454 // 12455 LLVM_FALLTHROUGH; 12456 12457 case VarDecl::DeclarationOnly: 12458 // It's only a declaration. 12459 12460 // Block scope. C99 6.7p7: If an identifier for an object is 12461 // declared with no linkage (C99 6.2.2p6), the type for the 12462 // object shall be complete. 12463 if (!Type->isDependentType() && Var->isLocalVarDecl() && 12464 !Var->hasLinkage() && !Var->isInvalidDecl() && 12465 RequireCompleteType(Var->getLocation(), Type, 12466 diag::err_typecheck_decl_incomplete_type)) 12467 Var->setInvalidDecl(); 12468 12469 // Make sure that the type is not abstract. 12470 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12471 RequireNonAbstractType(Var->getLocation(), Type, 12472 diag::err_abstract_type_in_decl, 12473 AbstractVariableType)) 12474 Var->setInvalidDecl(); 12475 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12476 Var->getStorageClass() == SC_PrivateExtern) { 12477 Diag(Var->getLocation(), diag::warn_private_extern); 12478 Diag(Var->getLocation(), diag::note_private_extern); 12479 } 12480 12481 if (Context.getTargetInfo().allowDebugInfoForExternalVar() && 12482 !Var->isInvalidDecl() && !getLangOpts().CPlusPlus) 12483 ExternalDeclarations.push_back(Var); 12484 12485 return; 12486 12487 case VarDecl::TentativeDefinition: 12488 // File scope. C99 6.9.2p2: A declaration of an identifier for an 12489 // object that has file scope without an initializer, and without a 12490 // storage-class specifier or with the storage-class specifier "static", 12491 // constitutes a tentative definition. Note: A tentative definition with 12492 // external linkage is valid (C99 6.2.2p5). 12493 if (!Var->isInvalidDecl()) { 12494 if (const IncompleteArrayType *ArrayT 12495 = Context.getAsIncompleteArrayType(Type)) { 12496 if (RequireCompleteSizedType( 12497 Var->getLocation(), ArrayT->getElementType(), 12498 diag::err_array_incomplete_or_sizeless_type)) 12499 Var->setInvalidDecl(); 12500 } else if (Var->getStorageClass() == SC_Static) { 12501 // C99 6.9.2p3: If the declaration of an identifier for an object is 12502 // a tentative definition and has internal linkage (C99 6.2.2p3), the 12503 // declared type shall not be an incomplete type. 12504 // NOTE: code such as the following 12505 // static struct s; 12506 // struct s { int a; }; 12507 // is accepted by gcc. Hence here we issue a warning instead of 12508 // an error and we do not invalidate the static declaration. 12509 // NOTE: to avoid multiple warnings, only check the first declaration. 12510 if (Var->isFirstDecl()) 12511 RequireCompleteType(Var->getLocation(), Type, 12512 diag::ext_typecheck_decl_incomplete_type); 12513 } 12514 } 12515 12516 // Record the tentative definition; we're done. 12517 if (!Var->isInvalidDecl()) 12518 TentativeDefinitions.push_back(Var); 12519 return; 12520 } 12521 12522 // Provide a specific diagnostic for uninitialized variable 12523 // definitions with incomplete array type. 12524 if (Type->isIncompleteArrayType()) { 12525 Diag(Var->getLocation(), 12526 diag::err_typecheck_incomplete_array_needs_initializer); 12527 Var->setInvalidDecl(); 12528 return; 12529 } 12530 12531 // Provide a specific diagnostic for uninitialized variable 12532 // definitions with reference type. 12533 if (Type->isReferenceType()) { 12534 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 12535 << Var->getDeclName() 12536 << SourceRange(Var->getLocation(), Var->getLocation()); 12537 Var->setInvalidDecl(); 12538 return; 12539 } 12540 12541 // Do not attempt to type-check the default initializer for a 12542 // variable with dependent type. 12543 if (Type->isDependentType()) 12544 return; 12545 12546 if (Var->isInvalidDecl()) 12547 return; 12548 12549 if (!Var->hasAttr<AliasAttr>()) { 12550 if (RequireCompleteType(Var->getLocation(), 12551 Context.getBaseElementType(Type), 12552 diag::err_typecheck_decl_incomplete_type)) { 12553 Var->setInvalidDecl(); 12554 return; 12555 } 12556 } else { 12557 return; 12558 } 12559 12560 // The variable can not have an abstract class type. 12561 if (RequireNonAbstractType(Var->getLocation(), Type, 12562 diag::err_abstract_type_in_decl, 12563 AbstractVariableType)) { 12564 Var->setInvalidDecl(); 12565 return; 12566 } 12567 12568 // Check for jumps past the implicit initializer. C++0x 12569 // clarifies that this applies to a "variable with automatic 12570 // storage duration", not a "local variable". 12571 // C++11 [stmt.dcl]p3 12572 // A program that jumps from a point where a variable with automatic 12573 // storage duration is not in scope to a point where it is in scope is 12574 // ill-formed unless the variable has scalar type, class type with a 12575 // trivial default constructor and a trivial destructor, a cv-qualified 12576 // version of one of these types, or an array of one of the preceding 12577 // types and is declared without an initializer. 12578 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 12579 if (const RecordType *Record 12580 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 12581 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 12582 // Mark the function (if we're in one) for further checking even if the 12583 // looser rules of C++11 do not require such checks, so that we can 12584 // diagnose incompatibilities with C++98. 12585 if (!CXXRecord->isPOD()) 12586 setFunctionHasBranchProtectedScope(); 12587 } 12588 } 12589 // In OpenCL, we can't initialize objects in the __local address space, 12590 // even implicitly, so don't synthesize an implicit initializer. 12591 if (getLangOpts().OpenCL && 12592 Var->getType().getAddressSpace() == LangAS::opencl_local) 12593 return; 12594 // C++03 [dcl.init]p9: 12595 // If no initializer is specified for an object, and the 12596 // object is of (possibly cv-qualified) non-POD class type (or 12597 // array thereof), the object shall be default-initialized; if 12598 // the object is of const-qualified type, the underlying class 12599 // type shall have a user-declared default 12600 // constructor. Otherwise, if no initializer is specified for 12601 // a non- static object, the object and its subobjects, if 12602 // any, have an indeterminate initial value); if the object 12603 // or any of its subobjects are of const-qualified type, the 12604 // program is ill-formed. 12605 // C++0x [dcl.init]p11: 12606 // If no initializer is specified for an object, the object is 12607 // default-initialized; [...]. 12608 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 12609 InitializationKind Kind 12610 = InitializationKind::CreateDefault(Var->getLocation()); 12611 12612 InitializationSequence InitSeq(*this, Entity, Kind, None); 12613 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 12614 12615 if (Init.get()) { 12616 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 12617 // This is important for template substitution. 12618 Var->setInitStyle(VarDecl::CallInit); 12619 } else if (Init.isInvalid()) { 12620 // If default-init fails, attach a recovery-expr initializer to track 12621 // that initialization was attempted and failed. 12622 auto RecoveryExpr = 12623 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {}); 12624 if (RecoveryExpr.get()) 12625 Var->setInit(RecoveryExpr.get()); 12626 } 12627 12628 CheckCompleteVariableDeclaration(Var); 12629 } 12630 } 12631 12632 void Sema::ActOnCXXForRangeDecl(Decl *D) { 12633 // If there is no declaration, there was an error parsing it. Ignore it. 12634 if (!D) 12635 return; 12636 12637 VarDecl *VD = dyn_cast<VarDecl>(D); 12638 if (!VD) { 12639 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 12640 D->setInvalidDecl(); 12641 return; 12642 } 12643 12644 VD->setCXXForRangeDecl(true); 12645 12646 // for-range-declaration cannot be given a storage class specifier. 12647 int Error = -1; 12648 switch (VD->getStorageClass()) { 12649 case SC_None: 12650 break; 12651 case SC_Extern: 12652 Error = 0; 12653 break; 12654 case SC_Static: 12655 Error = 1; 12656 break; 12657 case SC_PrivateExtern: 12658 Error = 2; 12659 break; 12660 case SC_Auto: 12661 Error = 3; 12662 break; 12663 case SC_Register: 12664 Error = 4; 12665 break; 12666 } 12667 if (Error != -1) { 12668 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 12669 << VD->getDeclName() << Error; 12670 D->setInvalidDecl(); 12671 } 12672 } 12673 12674 StmtResult 12675 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 12676 IdentifierInfo *Ident, 12677 ParsedAttributes &Attrs, 12678 SourceLocation AttrEnd) { 12679 // C++1y [stmt.iter]p1: 12680 // A range-based for statement of the form 12681 // for ( for-range-identifier : for-range-initializer ) statement 12682 // is equivalent to 12683 // for ( auto&& for-range-identifier : for-range-initializer ) statement 12684 DeclSpec DS(Attrs.getPool().getFactory()); 12685 12686 const char *PrevSpec; 12687 unsigned DiagID; 12688 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 12689 getPrintingPolicy()); 12690 12691 Declarator D(DS, DeclaratorContext::ForContext); 12692 D.SetIdentifier(Ident, IdentLoc); 12693 D.takeAttributes(Attrs, AttrEnd); 12694 12695 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false), 12696 IdentLoc); 12697 Decl *Var = ActOnDeclarator(S, D); 12698 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 12699 FinalizeDeclaration(Var); 12700 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 12701 AttrEnd.isValid() ? AttrEnd : IdentLoc); 12702 } 12703 12704 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 12705 if (var->isInvalidDecl()) return; 12706 12707 if (getLangOpts().OpenCL) { 12708 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 12709 // initialiser 12710 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 12711 !var->hasInit()) { 12712 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 12713 << 1 /*Init*/; 12714 var->setInvalidDecl(); 12715 return; 12716 } 12717 } 12718 12719 // In Objective-C, don't allow jumps past the implicit initialization of a 12720 // local retaining variable. 12721 if (getLangOpts().ObjC && 12722 var->hasLocalStorage()) { 12723 switch (var->getType().getObjCLifetime()) { 12724 case Qualifiers::OCL_None: 12725 case Qualifiers::OCL_ExplicitNone: 12726 case Qualifiers::OCL_Autoreleasing: 12727 break; 12728 12729 case Qualifiers::OCL_Weak: 12730 case Qualifiers::OCL_Strong: 12731 setFunctionHasBranchProtectedScope(); 12732 break; 12733 } 12734 } 12735 12736 if (var->hasLocalStorage() && 12737 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 12738 setFunctionHasBranchProtectedScope(); 12739 12740 // Warn about externally-visible variables being defined without a 12741 // prior declaration. We only want to do this for global 12742 // declarations, but we also specifically need to avoid doing it for 12743 // class members because the linkage of an anonymous class can 12744 // change if it's later given a typedef name. 12745 if (var->isThisDeclarationADefinition() && 12746 var->getDeclContext()->getRedeclContext()->isFileContext() && 12747 var->isExternallyVisible() && var->hasLinkage() && 12748 !var->isInline() && !var->getDescribedVarTemplate() && 12749 !isa<VarTemplatePartialSpecializationDecl>(var) && 12750 !isTemplateInstantiation(var->getTemplateSpecializationKind()) && 12751 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 12752 var->getLocation())) { 12753 // Find a previous declaration that's not a definition. 12754 VarDecl *prev = var->getPreviousDecl(); 12755 while (prev && prev->isThisDeclarationADefinition()) 12756 prev = prev->getPreviousDecl(); 12757 12758 if (!prev) { 12759 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 12760 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 12761 << /* variable */ 0; 12762 } 12763 } 12764 12765 // Cache the result of checking for constant initialization. 12766 Optional<bool> CacheHasConstInit; 12767 const Expr *CacheCulprit = nullptr; 12768 auto checkConstInit = [&]() mutable { 12769 if (!CacheHasConstInit) 12770 CacheHasConstInit = var->getInit()->isConstantInitializer( 12771 Context, var->getType()->isReferenceType(), &CacheCulprit); 12772 return *CacheHasConstInit; 12773 }; 12774 12775 if (var->getTLSKind() == VarDecl::TLS_Static) { 12776 if (var->getType().isDestructedType()) { 12777 // GNU C++98 edits for __thread, [basic.start.term]p3: 12778 // The type of an object with thread storage duration shall not 12779 // have a non-trivial destructor. 12780 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 12781 if (getLangOpts().CPlusPlus11) 12782 Diag(var->getLocation(), diag::note_use_thread_local); 12783 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 12784 if (!checkConstInit()) { 12785 // GNU C++98 edits for __thread, [basic.start.init]p4: 12786 // An object of thread storage duration shall not require dynamic 12787 // initialization. 12788 // FIXME: Need strict checking here. 12789 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 12790 << CacheCulprit->getSourceRange(); 12791 if (getLangOpts().CPlusPlus11) 12792 Diag(var->getLocation(), diag::note_use_thread_local); 12793 } 12794 } 12795 } 12796 12797 // Apply section attributes and pragmas to global variables. 12798 bool GlobalStorage = var->hasGlobalStorage(); 12799 if (GlobalStorage && var->isThisDeclarationADefinition() && 12800 !inTemplateInstantiation()) { 12801 PragmaStack<StringLiteral *> *Stack = nullptr; 12802 int SectionFlags = ASTContext::PSF_Read; 12803 if (var->getType().isConstQualified()) 12804 Stack = &ConstSegStack; 12805 else if (!var->getInit()) { 12806 Stack = &BSSSegStack; 12807 SectionFlags |= ASTContext::PSF_Write; 12808 } else { 12809 Stack = &DataSegStack; 12810 SectionFlags |= ASTContext::PSF_Write; 12811 } 12812 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) { 12813 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec) 12814 SectionFlags |= ASTContext::PSF_Implicit; 12815 UnifySection(SA->getName(), SectionFlags, var); 12816 } else if (Stack->CurrentValue) { 12817 SectionFlags |= ASTContext::PSF_Implicit; 12818 auto SectionName = Stack->CurrentValue->getString(); 12819 var->addAttr(SectionAttr::CreateImplicit( 12820 Context, SectionName, Stack->CurrentPragmaLocation, 12821 AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate)); 12822 if (UnifySection(SectionName, SectionFlags, var)) 12823 var->dropAttr<SectionAttr>(); 12824 } 12825 12826 // Apply the init_seg attribute if this has an initializer. If the 12827 // initializer turns out to not be dynamic, we'll end up ignoring this 12828 // attribute. 12829 if (CurInitSeg && var->getInit()) 12830 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 12831 CurInitSegLoc, 12832 AttributeCommonInfo::AS_Pragma)); 12833 } 12834 12835 // All the following checks are C++ only. 12836 if (!getLangOpts().CPlusPlus) { 12837 // If this variable must be emitted, add it as an initializer for the 12838 // current module. 12839 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 12840 Context.addModuleInitializer(ModuleScopes.back().Module, var); 12841 return; 12842 } 12843 12844 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 12845 CheckCompleteDecompositionDeclaration(DD); 12846 12847 QualType type = var->getType(); 12848 if (type->isDependentType()) return; 12849 12850 if (var->hasAttr<BlocksAttr>()) 12851 getCurFunction()->addByrefBlockVar(var); 12852 12853 Expr *Init = var->getInit(); 12854 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 12855 QualType baseType = Context.getBaseElementType(type); 12856 12857 if (Init && !Init->isValueDependent()) { 12858 if (var->isConstexpr()) { 12859 SmallVector<PartialDiagnosticAt, 8> Notes; 12860 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 12861 SourceLocation DiagLoc = var->getLocation(); 12862 // If the note doesn't add any useful information other than a source 12863 // location, fold it into the primary diagnostic. 12864 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 12865 diag::note_invalid_subexpr_in_const_expr) { 12866 DiagLoc = Notes[0].first; 12867 Notes.clear(); 12868 } 12869 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 12870 << var << Init->getSourceRange(); 12871 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 12872 Diag(Notes[I].first, Notes[I].second); 12873 } 12874 } else if (var->mightBeUsableInConstantExpressions(Context)) { 12875 // Check whether the initializer of a const variable of integral or 12876 // enumeration type is an ICE now, since we can't tell whether it was 12877 // initialized by a constant expression if we check later. 12878 var->checkInitIsICE(); 12879 } 12880 12881 // Don't emit further diagnostics about constexpr globals since they 12882 // were just diagnosed. 12883 if (!var->isConstexpr() && GlobalStorage && var->hasAttr<ConstInitAttr>()) { 12884 // FIXME: Need strict checking in C++03 here. 12885 bool DiagErr = getLangOpts().CPlusPlus11 12886 ? !var->checkInitIsICE() : !checkConstInit(); 12887 if (DiagErr) { 12888 auto *Attr = var->getAttr<ConstInitAttr>(); 12889 Diag(var->getLocation(), diag::err_require_constant_init_failed) 12890 << Init->getSourceRange(); 12891 Diag(Attr->getLocation(), 12892 diag::note_declared_required_constant_init_here) 12893 << Attr->getRange() << Attr->isConstinit(); 12894 if (getLangOpts().CPlusPlus11) { 12895 APValue Value; 12896 SmallVector<PartialDiagnosticAt, 8> Notes; 12897 Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes); 12898 for (auto &it : Notes) 12899 Diag(it.first, it.second); 12900 } else { 12901 Diag(CacheCulprit->getExprLoc(), 12902 diag::note_invalid_subexpr_in_const_expr) 12903 << CacheCulprit->getSourceRange(); 12904 } 12905 } 12906 } 12907 else if (!var->isConstexpr() && IsGlobal && 12908 !getDiagnostics().isIgnored(diag::warn_global_constructor, 12909 var->getLocation())) { 12910 // Warn about globals which don't have a constant initializer. Don't 12911 // warn about globals with a non-trivial destructor because we already 12912 // warned about them. 12913 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 12914 if (!(RD && !RD->hasTrivialDestructor())) { 12915 if (!checkConstInit()) 12916 Diag(var->getLocation(), diag::warn_global_constructor) 12917 << Init->getSourceRange(); 12918 } 12919 } 12920 } 12921 12922 // Require the destructor. 12923 if (const RecordType *recordType = baseType->getAs<RecordType>()) 12924 FinalizeVarWithDestructor(var, recordType); 12925 12926 // If this variable must be emitted, add it as an initializer for the current 12927 // module. 12928 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 12929 Context.addModuleInitializer(ModuleScopes.back().Module, var); 12930 } 12931 12932 /// Determines if a variable's alignment is dependent. 12933 static bool hasDependentAlignment(VarDecl *VD) { 12934 if (VD->getType()->isDependentType()) 12935 return true; 12936 for (auto *I : VD->specific_attrs<AlignedAttr>()) 12937 if (I->isAlignmentDependent()) 12938 return true; 12939 return false; 12940 } 12941 12942 /// Check if VD needs to be dllexport/dllimport due to being in a 12943 /// dllexport/import function. 12944 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) { 12945 assert(VD->isStaticLocal()); 12946 12947 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 12948 12949 // Find outermost function when VD is in lambda function. 12950 while (FD && !getDLLAttr(FD) && 12951 !FD->hasAttr<DLLExportStaticLocalAttr>() && 12952 !FD->hasAttr<DLLImportStaticLocalAttr>()) { 12953 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod()); 12954 } 12955 12956 if (!FD) 12957 return; 12958 12959 // Static locals inherit dll attributes from their function. 12960 if (Attr *A = getDLLAttr(FD)) { 12961 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 12962 NewAttr->setInherited(true); 12963 VD->addAttr(NewAttr); 12964 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) { 12965 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A); 12966 NewAttr->setInherited(true); 12967 VD->addAttr(NewAttr); 12968 12969 // Export this function to enforce exporting this static variable even 12970 // if it is not used in this compilation unit. 12971 if (!FD->hasAttr<DLLExportAttr>()) 12972 FD->addAttr(NewAttr); 12973 12974 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) { 12975 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A); 12976 NewAttr->setInherited(true); 12977 VD->addAttr(NewAttr); 12978 } 12979 } 12980 12981 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 12982 /// any semantic actions necessary after any initializer has been attached. 12983 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 12984 // Note that we are no longer parsing the initializer for this declaration. 12985 ParsingInitForAutoVars.erase(ThisDecl); 12986 12987 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 12988 if (!VD) 12989 return; 12990 12991 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active 12992 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && 12993 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { 12994 if (PragmaClangBSSSection.Valid) 12995 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit( 12996 Context, PragmaClangBSSSection.SectionName, 12997 PragmaClangBSSSection.PragmaLocation, 12998 AttributeCommonInfo::AS_Pragma)); 12999 if (PragmaClangDataSection.Valid) 13000 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit( 13001 Context, PragmaClangDataSection.SectionName, 13002 PragmaClangDataSection.PragmaLocation, 13003 AttributeCommonInfo::AS_Pragma)); 13004 if (PragmaClangRodataSection.Valid) 13005 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit( 13006 Context, PragmaClangRodataSection.SectionName, 13007 PragmaClangRodataSection.PragmaLocation, 13008 AttributeCommonInfo::AS_Pragma)); 13009 if (PragmaClangRelroSection.Valid) 13010 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit( 13011 Context, PragmaClangRelroSection.SectionName, 13012 PragmaClangRelroSection.PragmaLocation, 13013 AttributeCommonInfo::AS_Pragma)); 13014 } 13015 13016 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 13017 for (auto *BD : DD->bindings()) { 13018 FinalizeDeclaration(BD); 13019 } 13020 } 13021 13022 checkAttributesAfterMerging(*this, *VD); 13023 13024 // Perform TLS alignment check here after attributes attached to the variable 13025 // which may affect the alignment have been processed. Only perform the check 13026 // if the target has a maximum TLS alignment (zero means no constraints). 13027 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 13028 // Protect the check so that it's not performed on dependent types and 13029 // dependent alignments (we can't determine the alignment in that case). 13030 if (VD->getTLSKind() && !hasDependentAlignment(VD) && 13031 !VD->isInvalidDecl()) { 13032 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 13033 if (Context.getDeclAlign(VD) > MaxAlignChars) { 13034 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 13035 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 13036 << (unsigned)MaxAlignChars.getQuantity(); 13037 } 13038 } 13039 } 13040 13041 if (VD->isStaticLocal()) { 13042 CheckStaticLocalForDllExport(VD); 13043 13044 if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { 13045 // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__ 13046 // function, only __shared__ variables or variables without any device 13047 // memory qualifiers may be declared with static storage class. 13048 // Note: It is unclear how a function-scope non-const static variable 13049 // without device memory qualifier is implemented, therefore only static 13050 // const variable without device memory qualifier is allowed. 13051 [&]() { 13052 if (!getLangOpts().CUDA) 13053 return; 13054 if (VD->hasAttr<CUDASharedAttr>()) 13055 return; 13056 if (VD->getType().isConstQualified() && 13057 !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>())) 13058 return; 13059 if (CUDADiagIfDeviceCode(VD->getLocation(), 13060 diag::err_device_static_local_var) 13061 << CurrentCUDATarget()) 13062 VD->setInvalidDecl(); 13063 }(); 13064 } 13065 } 13066 13067 // Perform check for initializers of device-side global variables. 13068 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 13069 // 7.5). We must also apply the same checks to all __shared__ 13070 // variables whether they are local or not. CUDA also allows 13071 // constant initializers for __constant__ and __device__ variables. 13072 if (getLangOpts().CUDA) 13073 checkAllowedCUDAInitializer(VD); 13074 13075 // Grab the dllimport or dllexport attribute off of the VarDecl. 13076 const InheritableAttr *DLLAttr = getDLLAttr(VD); 13077 13078 // Imported static data members cannot be defined out-of-line. 13079 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 13080 if (VD->isStaticDataMember() && VD->isOutOfLine() && 13081 VD->isThisDeclarationADefinition()) { 13082 // We allow definitions of dllimport class template static data members 13083 // with a warning. 13084 CXXRecordDecl *Context = 13085 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 13086 bool IsClassTemplateMember = 13087 isa<ClassTemplatePartialSpecializationDecl>(Context) || 13088 Context->getDescribedClassTemplate(); 13089 13090 Diag(VD->getLocation(), 13091 IsClassTemplateMember 13092 ? diag::warn_attribute_dllimport_static_field_definition 13093 : diag::err_attribute_dllimport_static_field_definition); 13094 Diag(IA->getLocation(), diag::note_attribute); 13095 if (!IsClassTemplateMember) 13096 VD->setInvalidDecl(); 13097 } 13098 } 13099 13100 // dllimport/dllexport variables cannot be thread local, their TLS index 13101 // isn't exported with the variable. 13102 if (DLLAttr && VD->getTLSKind()) { 13103 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 13104 if (F && getDLLAttr(F)) { 13105 assert(VD->isStaticLocal()); 13106 // But if this is a static local in a dlimport/dllexport function, the 13107 // function will never be inlined, which means the var would never be 13108 // imported, so having it marked import/export is safe. 13109 } else { 13110 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 13111 << DLLAttr; 13112 VD->setInvalidDecl(); 13113 } 13114 } 13115 13116 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 13117 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 13118 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 13119 VD->dropAttr<UsedAttr>(); 13120 } 13121 } 13122 13123 const DeclContext *DC = VD->getDeclContext(); 13124 // If there's a #pragma GCC visibility in scope, and this isn't a class 13125 // member, set the visibility of this variable. 13126 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 13127 AddPushedVisibilityAttribute(VD); 13128 13129 // FIXME: Warn on unused var template partial specializations. 13130 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 13131 MarkUnusedFileScopedDecl(VD); 13132 13133 // Now we have parsed the initializer and can update the table of magic 13134 // tag values. 13135 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 13136 !VD->getType()->isIntegralOrEnumerationType()) 13137 return; 13138 13139 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 13140 const Expr *MagicValueExpr = VD->getInit(); 13141 if (!MagicValueExpr) { 13142 continue; 13143 } 13144 llvm::APSInt MagicValueInt; 13145 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 13146 Diag(I->getRange().getBegin(), 13147 diag::err_type_tag_for_datatype_not_ice) 13148 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13149 continue; 13150 } 13151 if (MagicValueInt.getActiveBits() > 64) { 13152 Diag(I->getRange().getBegin(), 13153 diag::err_type_tag_for_datatype_too_large) 13154 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13155 continue; 13156 } 13157 uint64_t MagicValue = MagicValueInt.getZExtValue(); 13158 RegisterTypeTagForDatatype(I->getArgumentKind(), 13159 MagicValue, 13160 I->getMatchingCType(), 13161 I->getLayoutCompatible(), 13162 I->getMustBeNull()); 13163 } 13164 } 13165 13166 static bool hasDeducedAuto(DeclaratorDecl *DD) { 13167 auto *VD = dyn_cast<VarDecl>(DD); 13168 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 13169 } 13170 13171 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 13172 ArrayRef<Decl *> Group) { 13173 SmallVector<Decl*, 8> Decls; 13174 13175 if (DS.isTypeSpecOwned()) 13176 Decls.push_back(DS.getRepAsDecl()); 13177 13178 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 13179 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 13180 bool DiagnosedMultipleDecomps = false; 13181 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 13182 bool DiagnosedNonDeducedAuto = false; 13183 13184 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13185 if (Decl *D = Group[i]) { 13186 // For declarators, there are some additional syntactic-ish checks we need 13187 // to perform. 13188 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 13189 if (!FirstDeclaratorInGroup) 13190 FirstDeclaratorInGroup = DD; 13191 if (!FirstDecompDeclaratorInGroup) 13192 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 13193 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 13194 !hasDeducedAuto(DD)) 13195 FirstNonDeducedAutoInGroup = DD; 13196 13197 if (FirstDeclaratorInGroup != DD) { 13198 // A decomposition declaration cannot be combined with any other 13199 // declaration in the same group. 13200 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 13201 Diag(FirstDecompDeclaratorInGroup->getLocation(), 13202 diag::err_decomp_decl_not_alone) 13203 << FirstDeclaratorInGroup->getSourceRange() 13204 << DD->getSourceRange(); 13205 DiagnosedMultipleDecomps = true; 13206 } 13207 13208 // A declarator that uses 'auto' in any way other than to declare a 13209 // variable with a deduced type cannot be combined with any other 13210 // declarator in the same group. 13211 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 13212 Diag(FirstNonDeducedAutoInGroup->getLocation(), 13213 diag::err_auto_non_deduced_not_alone) 13214 << FirstNonDeducedAutoInGroup->getType() 13215 ->hasAutoForTrailingReturnType() 13216 << FirstDeclaratorInGroup->getSourceRange() 13217 << DD->getSourceRange(); 13218 DiagnosedNonDeducedAuto = true; 13219 } 13220 } 13221 } 13222 13223 Decls.push_back(D); 13224 } 13225 } 13226 13227 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 13228 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 13229 handleTagNumbering(Tag, S); 13230 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 13231 getLangOpts().CPlusPlus) 13232 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 13233 } 13234 } 13235 13236 return BuildDeclaratorGroup(Decls); 13237 } 13238 13239 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 13240 /// group, performing any necessary semantic checking. 13241 Sema::DeclGroupPtrTy 13242 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 13243 // C++14 [dcl.spec.auto]p7: (DR1347) 13244 // If the type that replaces the placeholder type is not the same in each 13245 // deduction, the program is ill-formed. 13246 if (Group.size() > 1) { 13247 QualType Deduced; 13248 VarDecl *DeducedDecl = nullptr; 13249 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13250 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 13251 if (!D || D->isInvalidDecl()) 13252 break; 13253 DeducedType *DT = D->getType()->getContainedDeducedType(); 13254 if (!DT || DT->getDeducedType().isNull()) 13255 continue; 13256 if (Deduced.isNull()) { 13257 Deduced = DT->getDeducedType(); 13258 DeducedDecl = D; 13259 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 13260 auto *AT = dyn_cast<AutoType>(DT); 13261 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 13262 diag::err_auto_different_deductions) 13263 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced 13264 << DeducedDecl->getDeclName() << DT->getDeducedType() 13265 << D->getDeclName(); 13266 if (DeducedDecl->hasInit()) 13267 Dia << DeducedDecl->getInit()->getSourceRange(); 13268 if (D->getInit()) 13269 Dia << D->getInit()->getSourceRange(); 13270 D->setInvalidDecl(); 13271 break; 13272 } 13273 } 13274 } 13275 13276 ActOnDocumentableDecls(Group); 13277 13278 return DeclGroupPtrTy::make( 13279 DeclGroupRef::Create(Context, Group.data(), Group.size())); 13280 } 13281 13282 void Sema::ActOnDocumentableDecl(Decl *D) { 13283 ActOnDocumentableDecls(D); 13284 } 13285 13286 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 13287 // Don't parse the comment if Doxygen diagnostics are ignored. 13288 if (Group.empty() || !Group[0]) 13289 return; 13290 13291 if (Diags.isIgnored(diag::warn_doc_param_not_found, 13292 Group[0]->getLocation()) && 13293 Diags.isIgnored(diag::warn_unknown_comment_command_name, 13294 Group[0]->getLocation())) 13295 return; 13296 13297 if (Group.size() >= 2) { 13298 // This is a decl group. Normally it will contain only declarations 13299 // produced from declarator list. But in case we have any definitions or 13300 // additional declaration references: 13301 // 'typedef struct S {} S;' 13302 // 'typedef struct S *S;' 13303 // 'struct S *pS;' 13304 // FinalizeDeclaratorGroup adds these as separate declarations. 13305 Decl *MaybeTagDecl = Group[0]; 13306 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 13307 Group = Group.slice(1); 13308 } 13309 } 13310 13311 // FIMXE: We assume every Decl in the group is in the same file. 13312 // This is false when preprocessor constructs the group from decls in 13313 // different files (e. g. macros or #include). 13314 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor()); 13315 } 13316 13317 /// Common checks for a parameter-declaration that should apply to both function 13318 /// parameters and non-type template parameters. 13319 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) { 13320 // Check that there are no default arguments inside the type of this 13321 // parameter. 13322 if (getLangOpts().CPlusPlus) 13323 CheckExtraCXXDefaultArguments(D); 13324 13325 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 13326 if (D.getCXXScopeSpec().isSet()) { 13327 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 13328 << D.getCXXScopeSpec().getRange(); 13329 } 13330 13331 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a 13332 // simple identifier except [...irrelevant cases...]. 13333 switch (D.getName().getKind()) { 13334 case UnqualifiedIdKind::IK_Identifier: 13335 break; 13336 13337 case UnqualifiedIdKind::IK_OperatorFunctionId: 13338 case UnqualifiedIdKind::IK_ConversionFunctionId: 13339 case UnqualifiedIdKind::IK_LiteralOperatorId: 13340 case UnqualifiedIdKind::IK_ConstructorName: 13341 case UnqualifiedIdKind::IK_DestructorName: 13342 case UnqualifiedIdKind::IK_ImplicitSelfParam: 13343 case UnqualifiedIdKind::IK_DeductionGuideName: 13344 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 13345 << GetNameForDeclarator(D).getName(); 13346 break; 13347 13348 case UnqualifiedIdKind::IK_TemplateId: 13349 case UnqualifiedIdKind::IK_ConstructorTemplateId: 13350 // GetNameForDeclarator would not produce a useful name in this case. 13351 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id); 13352 break; 13353 } 13354 } 13355 13356 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 13357 /// to introduce parameters into function prototype scope. 13358 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 13359 const DeclSpec &DS = D.getDeclSpec(); 13360 13361 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 13362 13363 // C++03 [dcl.stc]p2 also permits 'auto'. 13364 StorageClass SC = SC_None; 13365 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 13366 SC = SC_Register; 13367 // In C++11, the 'register' storage class specifier is deprecated. 13368 // In C++17, it is not allowed, but we tolerate it as an extension. 13369 if (getLangOpts().CPlusPlus11) { 13370 Diag(DS.getStorageClassSpecLoc(), 13371 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 13372 : diag::warn_deprecated_register) 13373 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 13374 } 13375 } else if (getLangOpts().CPlusPlus && 13376 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 13377 SC = SC_Auto; 13378 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 13379 Diag(DS.getStorageClassSpecLoc(), 13380 diag::err_invalid_storage_class_in_func_decl); 13381 D.getMutableDeclSpec().ClearStorageClassSpecs(); 13382 } 13383 13384 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 13385 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 13386 << DeclSpec::getSpecifierName(TSCS); 13387 if (DS.isInlineSpecified()) 13388 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 13389 << getLangOpts().CPlusPlus17; 13390 if (DS.hasConstexprSpecifier()) 13391 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 13392 << 0 << D.getDeclSpec().getConstexprSpecifier(); 13393 13394 DiagnoseFunctionSpecifiers(DS); 13395 13396 CheckFunctionOrTemplateParamDeclarator(S, D); 13397 13398 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13399 QualType parmDeclType = TInfo->getType(); 13400 13401 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 13402 IdentifierInfo *II = D.getIdentifier(); 13403 if (II) { 13404 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 13405 ForVisibleRedeclaration); 13406 LookupName(R, S); 13407 if (R.isSingleResult()) { 13408 NamedDecl *PrevDecl = R.getFoundDecl(); 13409 if (PrevDecl->isTemplateParameter()) { 13410 // Maybe we will complain about the shadowed template parameter. 13411 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13412 // Just pretend that we didn't see the previous declaration. 13413 PrevDecl = nullptr; 13414 } else if (S->isDeclScope(PrevDecl)) { 13415 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 13416 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 13417 13418 // Recover by removing the name 13419 II = nullptr; 13420 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 13421 D.setInvalidType(true); 13422 } 13423 } 13424 } 13425 13426 // Temporarily put parameter variables in the translation unit, not 13427 // the enclosing context. This prevents them from accidentally 13428 // looking like class members in C++. 13429 ParmVarDecl *New = 13430 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(), 13431 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC); 13432 13433 if (D.isInvalidType()) 13434 New->setInvalidDecl(); 13435 13436 assert(S->isFunctionPrototypeScope()); 13437 assert(S->getFunctionPrototypeDepth() >= 1); 13438 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 13439 S->getNextFunctionPrototypeIndex()); 13440 13441 // Add the parameter declaration into this scope. 13442 S->AddDecl(New); 13443 if (II) 13444 IdResolver.AddDecl(New); 13445 13446 ProcessDeclAttributes(S, New, D); 13447 13448 if (D.getDeclSpec().isModulePrivateSpecified()) 13449 Diag(New->getLocation(), diag::err_module_private_local) 13450 << 1 << New->getDeclName() 13451 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 13452 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 13453 13454 if (New->hasAttr<BlocksAttr>()) { 13455 Diag(New->getLocation(), diag::err_block_on_nonlocal); 13456 } 13457 13458 if (getLangOpts().OpenCL) 13459 deduceOpenCLAddressSpace(New); 13460 13461 return New; 13462 } 13463 13464 /// Synthesizes a variable for a parameter arising from a 13465 /// typedef. 13466 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 13467 SourceLocation Loc, 13468 QualType T) { 13469 /* FIXME: setting StartLoc == Loc. 13470 Would it be worth to modify callers so as to provide proper source 13471 location for the unnamed parameters, embedding the parameter's type? */ 13472 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 13473 T, Context.getTrivialTypeSourceInfo(T, Loc), 13474 SC_None, nullptr); 13475 Param->setImplicit(); 13476 return Param; 13477 } 13478 13479 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 13480 // Don't diagnose unused-parameter errors in template instantiations; we 13481 // will already have done so in the template itself. 13482 if (inTemplateInstantiation()) 13483 return; 13484 13485 for (const ParmVarDecl *Parameter : Parameters) { 13486 if (!Parameter->isReferenced() && Parameter->getDeclName() && 13487 !Parameter->hasAttr<UnusedAttr>()) { 13488 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 13489 << Parameter->getDeclName(); 13490 } 13491 } 13492 } 13493 13494 void Sema::DiagnoseSizeOfParametersAndReturnValue( 13495 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 13496 if (LangOpts.NumLargeByValueCopy == 0) // No check. 13497 return; 13498 13499 // Warn if the return value is pass-by-value and larger than the specified 13500 // threshold. 13501 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 13502 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 13503 if (Size > LangOpts.NumLargeByValueCopy) 13504 Diag(D->getLocation(), diag::warn_return_value_size) 13505 << D->getDeclName() << Size; 13506 } 13507 13508 // Warn if any parameter is pass-by-value and larger than the specified 13509 // threshold. 13510 for (const ParmVarDecl *Parameter : Parameters) { 13511 QualType T = Parameter->getType(); 13512 if (T->isDependentType() || !T.isPODType(Context)) 13513 continue; 13514 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 13515 if (Size > LangOpts.NumLargeByValueCopy) 13516 Diag(Parameter->getLocation(), diag::warn_parameter_size) 13517 << Parameter->getDeclName() << Size; 13518 } 13519 } 13520 13521 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 13522 SourceLocation NameLoc, IdentifierInfo *Name, 13523 QualType T, TypeSourceInfo *TSInfo, 13524 StorageClass SC) { 13525 // In ARC, infer a lifetime qualifier for appropriate parameter types. 13526 if (getLangOpts().ObjCAutoRefCount && 13527 T.getObjCLifetime() == Qualifiers::OCL_None && 13528 T->isObjCLifetimeType()) { 13529 13530 Qualifiers::ObjCLifetime lifetime; 13531 13532 // Special cases for arrays: 13533 // - if it's const, use __unsafe_unretained 13534 // - otherwise, it's an error 13535 if (T->isArrayType()) { 13536 if (!T.isConstQualified()) { 13537 if (DelayedDiagnostics.shouldDelayDiagnostics()) 13538 DelayedDiagnostics.add( 13539 sema::DelayedDiagnostic::makeForbiddenType( 13540 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 13541 else 13542 Diag(NameLoc, diag::err_arc_array_param_no_ownership) 13543 << TSInfo->getTypeLoc().getSourceRange(); 13544 } 13545 lifetime = Qualifiers::OCL_ExplicitNone; 13546 } else { 13547 lifetime = T->getObjCARCImplicitLifetime(); 13548 } 13549 T = Context.getLifetimeQualifiedType(T, lifetime); 13550 } 13551 13552 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 13553 Context.getAdjustedParameterType(T), 13554 TSInfo, SC, nullptr); 13555 13556 // Make a note if we created a new pack in the scope of a lambda, so that 13557 // we know that references to that pack must also be expanded within the 13558 // lambda scope. 13559 if (New->isParameterPack()) 13560 if (auto *LSI = getEnclosingLambda()) 13561 LSI->LocalPacks.push_back(New); 13562 13563 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() || 13564 New->getType().hasNonTrivialToPrimitiveCopyCUnion()) 13565 checkNonTrivialCUnion(New->getType(), New->getLocation(), 13566 NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy); 13567 13568 // Parameters can not be abstract class types. 13569 // For record types, this is done by the AbstractClassUsageDiagnoser once 13570 // the class has been completely parsed. 13571 if (!CurContext->isRecord() && 13572 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 13573 AbstractParamType)) 13574 New->setInvalidDecl(); 13575 13576 // Parameter declarators cannot be interface types. All ObjC objects are 13577 // passed by reference. 13578 if (T->isObjCObjectType()) { 13579 SourceLocation TypeEndLoc = 13580 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc()); 13581 Diag(NameLoc, 13582 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 13583 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 13584 T = Context.getObjCObjectPointerType(T); 13585 New->setType(T); 13586 } 13587 13588 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 13589 // duration shall not be qualified by an address-space qualifier." 13590 // Since all parameters have automatic store duration, they can not have 13591 // an address space. 13592 if (T.getAddressSpace() != LangAS::Default && 13593 // OpenCL allows function arguments declared to be an array of a type 13594 // to be qualified with an address space. 13595 !(getLangOpts().OpenCL && 13596 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) { 13597 Diag(NameLoc, diag::err_arg_with_address_space); 13598 New->setInvalidDecl(); 13599 } 13600 13601 return New; 13602 } 13603 13604 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 13605 SourceLocation LocAfterDecls) { 13606 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 13607 13608 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 13609 // for a K&R function. 13610 if (!FTI.hasPrototype) { 13611 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 13612 --i; 13613 if (FTI.Params[i].Param == nullptr) { 13614 SmallString<256> Code; 13615 llvm::raw_svector_ostream(Code) 13616 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 13617 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 13618 << FTI.Params[i].Ident 13619 << FixItHint::CreateInsertion(LocAfterDecls, Code); 13620 13621 // Implicitly declare the argument as type 'int' for lack of a better 13622 // type. 13623 AttributeFactory attrs; 13624 DeclSpec DS(attrs); 13625 const char* PrevSpec; // unused 13626 unsigned DiagID; // unused 13627 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 13628 DiagID, Context.getPrintingPolicy()); 13629 // Use the identifier location for the type source range. 13630 DS.SetRangeStart(FTI.Params[i].IdentLoc); 13631 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 13632 Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext); 13633 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 13634 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 13635 } 13636 } 13637 } 13638 } 13639 13640 Decl * 13641 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 13642 MultiTemplateParamsArg TemplateParameterLists, 13643 SkipBodyInfo *SkipBody) { 13644 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 13645 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 13646 Scope *ParentScope = FnBodyScope->getParent(); 13647 13648 // Check if we are in an `omp begin/end declare variant` scope. If we are, and 13649 // we define a non-templated function definition, we will create a declaration 13650 // instead (=BaseFD), and emit the definition with a mangled name afterwards. 13651 // The base function declaration will have the equivalent of an `omp declare 13652 // variant` annotation which specifies the mangled definition as a 13653 // specialization function under the OpenMP context defined as part of the 13654 // `omp begin declare variant`. 13655 FunctionDecl *BaseFD = nullptr; 13656 if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope() && 13657 TemplateParameterLists.empty()) 13658 BaseFD = ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( 13659 ParentScope, D); 13660 13661 D.setFunctionDefinitionKind(FDK_Definition); 13662 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 13663 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 13664 13665 if (BaseFD) 13666 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope( 13667 cast<FunctionDecl>(Dcl), BaseFD); 13668 13669 return Dcl; 13670 } 13671 13672 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 13673 Consumer.HandleInlineFunctionDefinition(D); 13674 } 13675 13676 static bool 13677 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 13678 const FunctionDecl *&PossiblePrototype) { 13679 // Don't warn about invalid declarations. 13680 if (FD->isInvalidDecl()) 13681 return false; 13682 13683 // Or declarations that aren't global. 13684 if (!FD->isGlobal()) 13685 return false; 13686 13687 // Don't warn about C++ member functions. 13688 if (isa<CXXMethodDecl>(FD)) 13689 return false; 13690 13691 // Don't warn about 'main'. 13692 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext())) 13693 if (IdentifierInfo *II = FD->getIdentifier()) 13694 if (II->isStr("main")) 13695 return false; 13696 13697 // Don't warn about inline functions. 13698 if (FD->isInlined()) 13699 return false; 13700 13701 // Don't warn about function templates. 13702 if (FD->getDescribedFunctionTemplate()) 13703 return false; 13704 13705 // Don't warn about function template specializations. 13706 if (FD->isFunctionTemplateSpecialization()) 13707 return false; 13708 13709 // Don't warn for OpenCL kernels. 13710 if (FD->hasAttr<OpenCLKernelAttr>()) 13711 return false; 13712 13713 // Don't warn on explicitly deleted functions. 13714 if (FD->isDeleted()) 13715 return false; 13716 13717 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 13718 Prev; Prev = Prev->getPreviousDecl()) { 13719 // Ignore any declarations that occur in function or method 13720 // scope, because they aren't visible from the header. 13721 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 13722 continue; 13723 13724 PossiblePrototype = Prev; 13725 return Prev->getType()->isFunctionNoProtoType(); 13726 } 13727 13728 return true; 13729 } 13730 13731 void 13732 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 13733 const FunctionDecl *EffectiveDefinition, 13734 SkipBodyInfo *SkipBody) { 13735 const FunctionDecl *Definition = EffectiveDefinition; 13736 if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) { 13737 // If this is a friend function defined in a class template, it does not 13738 // have a body until it is used, nevertheless it is a definition, see 13739 // [temp.inst]p2: 13740 // 13741 // ... for the purpose of determining whether an instantiated redeclaration 13742 // is valid according to [basic.def.odr] and [class.mem], a declaration that 13743 // corresponds to a definition in the template is considered to be a 13744 // definition. 13745 // 13746 // The following code must produce redefinition error: 13747 // 13748 // template<typename T> struct C20 { friend void func_20() {} }; 13749 // C20<int> c20i; 13750 // void func_20() {} 13751 // 13752 for (auto I : FD->redecls()) { 13753 if (I != FD && !I->isInvalidDecl() && 13754 I->getFriendObjectKind() != Decl::FOK_None) { 13755 if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) { 13756 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { 13757 // A merged copy of the same function, instantiated as a member of 13758 // the same class, is OK. 13759 if (declaresSameEntity(OrigFD, Original) && 13760 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()), 13761 cast<Decl>(FD->getLexicalDeclContext()))) 13762 continue; 13763 } 13764 13765 if (Original->isThisDeclarationADefinition()) { 13766 Definition = I; 13767 break; 13768 } 13769 } 13770 } 13771 } 13772 } 13773 13774 if (!Definition) 13775 // Similar to friend functions a friend function template may be a 13776 // definition and do not have a body if it is instantiated in a class 13777 // template. 13778 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) { 13779 for (auto I : FTD->redecls()) { 13780 auto D = cast<FunctionTemplateDecl>(I); 13781 if (D != FTD) { 13782 assert(!D->isThisDeclarationADefinition() && 13783 "More than one definition in redeclaration chain"); 13784 if (D->getFriendObjectKind() != Decl::FOK_None) 13785 if (FunctionTemplateDecl *FT = 13786 D->getInstantiatedFromMemberTemplate()) { 13787 if (FT->isThisDeclarationADefinition()) { 13788 Definition = D->getTemplatedDecl(); 13789 break; 13790 } 13791 } 13792 } 13793 } 13794 } 13795 13796 if (!Definition) 13797 return; 13798 13799 if (canRedefineFunction(Definition, getLangOpts())) 13800 return; 13801 13802 // Don't emit an error when this is redefinition of a typo-corrected 13803 // definition. 13804 if (TypoCorrectedFunctionDefinitions.count(Definition)) 13805 return; 13806 13807 // If we don't have a visible definition of the function, and it's inline or 13808 // a template, skip the new definition. 13809 if (SkipBody && !hasVisibleDefinition(Definition) && 13810 (Definition->getFormalLinkage() == InternalLinkage || 13811 Definition->isInlined() || 13812 Definition->getDescribedFunctionTemplate() || 13813 Definition->getNumTemplateParameterLists())) { 13814 SkipBody->ShouldSkip = true; 13815 SkipBody->Previous = const_cast<FunctionDecl*>(Definition); 13816 if (auto *TD = Definition->getDescribedFunctionTemplate()) 13817 makeMergedDefinitionVisible(TD); 13818 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 13819 return; 13820 } 13821 13822 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 13823 Definition->getStorageClass() == SC_Extern) 13824 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 13825 << FD->getDeclName() << getLangOpts().CPlusPlus; 13826 else 13827 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 13828 13829 Diag(Definition->getLocation(), diag::note_previous_definition); 13830 FD->setInvalidDecl(); 13831 } 13832 13833 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 13834 Sema &S) { 13835 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 13836 13837 LambdaScopeInfo *LSI = S.PushLambdaScope(); 13838 LSI->CallOperator = CallOperator; 13839 LSI->Lambda = LambdaClass; 13840 LSI->ReturnType = CallOperator->getReturnType(); 13841 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 13842 13843 if (LCD == LCD_None) 13844 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 13845 else if (LCD == LCD_ByCopy) 13846 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 13847 else if (LCD == LCD_ByRef) 13848 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 13849 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 13850 13851 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 13852 LSI->Mutable = !CallOperator->isConst(); 13853 13854 // Add the captures to the LSI so they can be noted as already 13855 // captured within tryCaptureVar. 13856 auto I = LambdaClass->field_begin(); 13857 for (const auto &C : LambdaClass->captures()) { 13858 if (C.capturesVariable()) { 13859 VarDecl *VD = C.getCapturedVar(); 13860 if (VD->isInitCapture()) 13861 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 13862 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 13863 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 13864 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 13865 /*EllipsisLoc*/C.isPackExpansion() 13866 ? C.getEllipsisLoc() : SourceLocation(), 13867 I->getType(), /*Invalid*/false); 13868 13869 } else if (C.capturesThis()) { 13870 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(), 13871 C.getCaptureKind() == LCK_StarThis); 13872 } else { 13873 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(), 13874 I->getType()); 13875 } 13876 ++I; 13877 } 13878 } 13879 13880 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 13881 SkipBodyInfo *SkipBody) { 13882 if (!D) { 13883 // Parsing the function declaration failed in some way. Push on a fake scope 13884 // anyway so we can try to parse the function body. 13885 PushFunctionScope(); 13886 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 13887 return D; 13888 } 13889 13890 FunctionDecl *FD = nullptr; 13891 13892 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 13893 FD = FunTmpl->getTemplatedDecl(); 13894 else 13895 FD = cast<FunctionDecl>(D); 13896 13897 // Do not push if it is a lambda because one is already pushed when building 13898 // the lambda in ActOnStartOfLambdaDefinition(). 13899 if (!isLambdaCallOperator(FD)) 13900 PushExpressionEvaluationContext( 13901 FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated 13902 : ExprEvalContexts.back().Context); 13903 13904 // Check for defining attributes before the check for redefinition. 13905 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 13906 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 13907 FD->dropAttr<AliasAttr>(); 13908 FD->setInvalidDecl(); 13909 } 13910 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 13911 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 13912 FD->dropAttr<IFuncAttr>(); 13913 FD->setInvalidDecl(); 13914 } 13915 13916 // See if this is a redefinition. If 'will have body' is already set, then 13917 // these checks were already performed when it was set. 13918 if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) { 13919 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 13920 13921 // If we're skipping the body, we're done. Don't enter the scope. 13922 if (SkipBody && SkipBody->ShouldSkip) 13923 return D; 13924 } 13925 13926 // Mark this function as "will have a body eventually". This lets users to 13927 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 13928 // this function. 13929 FD->setWillHaveBody(); 13930 13931 // If we are instantiating a generic lambda call operator, push 13932 // a LambdaScopeInfo onto the function stack. But use the information 13933 // that's already been calculated (ActOnLambdaExpr) to prime the current 13934 // LambdaScopeInfo. 13935 // When the template operator is being specialized, the LambdaScopeInfo, 13936 // has to be properly restored so that tryCaptureVariable doesn't try 13937 // and capture any new variables. In addition when calculating potential 13938 // captures during transformation of nested lambdas, it is necessary to 13939 // have the LSI properly restored. 13940 if (isGenericLambdaCallOperatorSpecialization(FD)) { 13941 assert(inTemplateInstantiation() && 13942 "There should be an active template instantiation on the stack " 13943 "when instantiating a generic lambda!"); 13944 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 13945 } else { 13946 // Enter a new function scope 13947 PushFunctionScope(); 13948 } 13949 13950 // Builtin functions cannot be defined. 13951 if (unsigned BuiltinID = FD->getBuiltinID()) { 13952 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 13953 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 13954 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 13955 FD->setInvalidDecl(); 13956 } 13957 } 13958 13959 // The return type of a function definition must be complete 13960 // (C99 6.9.1p3, C++ [dcl.fct]p6). 13961 QualType ResultType = FD->getReturnType(); 13962 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 13963 !FD->isInvalidDecl() && 13964 RequireCompleteType(FD->getLocation(), ResultType, 13965 diag::err_func_def_incomplete_result)) 13966 FD->setInvalidDecl(); 13967 13968 if (FnBodyScope) 13969 PushDeclContext(FnBodyScope, FD); 13970 13971 // Check the validity of our function parameters 13972 CheckParmsForFunctionDef(FD->parameters(), 13973 /*CheckParameterNames=*/true); 13974 13975 // Add non-parameter declarations already in the function to the current 13976 // scope. 13977 if (FnBodyScope) { 13978 for (Decl *NPD : FD->decls()) { 13979 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 13980 if (!NonParmDecl) 13981 continue; 13982 assert(!isa<ParmVarDecl>(NonParmDecl) && 13983 "parameters should not be in newly created FD yet"); 13984 13985 // If the decl has a name, make it accessible in the current scope. 13986 if (NonParmDecl->getDeclName()) 13987 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 13988 13989 // Similarly, dive into enums and fish their constants out, making them 13990 // accessible in this scope. 13991 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 13992 for (auto *EI : ED->enumerators()) 13993 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 13994 } 13995 } 13996 } 13997 13998 // Introduce our parameters into the function scope 13999 for (auto Param : FD->parameters()) { 14000 Param->setOwningFunction(FD); 14001 14002 // If this has an identifier, add it to the scope stack. 14003 if (Param->getIdentifier() && FnBodyScope) { 14004 CheckShadow(FnBodyScope, Param); 14005 14006 PushOnScopeChains(Param, FnBodyScope); 14007 } 14008 } 14009 14010 // Ensure that the function's exception specification is instantiated. 14011 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 14012 ResolveExceptionSpec(D->getLocation(), FPT); 14013 14014 // dllimport cannot be applied to non-inline function definitions. 14015 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 14016 !FD->isTemplateInstantiation()) { 14017 assert(!FD->hasAttr<DLLExportAttr>()); 14018 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 14019 FD->setInvalidDecl(); 14020 return D; 14021 } 14022 // We want to attach documentation to original Decl (which might be 14023 // a function template). 14024 ActOnDocumentableDecl(D); 14025 if (getCurLexicalContext()->isObjCContainer() && 14026 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 14027 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 14028 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 14029 14030 return D; 14031 } 14032 14033 /// Given the set of return statements within a function body, 14034 /// compute the variables that are subject to the named return value 14035 /// optimization. 14036 /// 14037 /// Each of the variables that is subject to the named return value 14038 /// optimization will be marked as NRVO variables in the AST, and any 14039 /// return statement that has a marked NRVO variable as its NRVO candidate can 14040 /// use the named return value optimization. 14041 /// 14042 /// This function applies a very simplistic algorithm for NRVO: if every return 14043 /// statement in the scope of a variable has the same NRVO candidate, that 14044 /// candidate is an NRVO variable. 14045 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 14046 ReturnStmt **Returns = Scope->Returns.data(); 14047 14048 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 14049 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 14050 if (!NRVOCandidate->isNRVOVariable()) 14051 Returns[I]->setNRVOCandidate(nullptr); 14052 } 14053 } 14054 } 14055 14056 bool Sema::canDelayFunctionBody(const Declarator &D) { 14057 // We can't delay parsing the body of a constexpr function template (yet). 14058 if (D.getDeclSpec().hasConstexprSpecifier()) 14059 return false; 14060 14061 // We can't delay parsing the body of a function template with a deduced 14062 // return type (yet). 14063 if (D.getDeclSpec().hasAutoTypeSpec()) { 14064 // If the placeholder introduces a non-deduced trailing return type, 14065 // we can still delay parsing it. 14066 if (D.getNumTypeObjects()) { 14067 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 14068 if (Outer.Kind == DeclaratorChunk::Function && 14069 Outer.Fun.hasTrailingReturnType()) { 14070 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 14071 return Ty.isNull() || !Ty->isUndeducedType(); 14072 } 14073 } 14074 return false; 14075 } 14076 14077 return true; 14078 } 14079 14080 bool Sema::canSkipFunctionBody(Decl *D) { 14081 // We cannot skip the body of a function (or function template) which is 14082 // constexpr, since we may need to evaluate its body in order to parse the 14083 // rest of the file. 14084 // We cannot skip the body of a function with an undeduced return type, 14085 // because any callers of that function need to know the type. 14086 if (const FunctionDecl *FD = D->getAsFunction()) { 14087 if (FD->isConstexpr()) 14088 return false; 14089 // We can't simply call Type::isUndeducedType here, because inside template 14090 // auto can be deduced to a dependent type, which is not considered 14091 // "undeduced". 14092 if (FD->getReturnType()->getContainedDeducedType()) 14093 return false; 14094 } 14095 return Consumer.shouldSkipFunctionBody(D); 14096 } 14097 14098 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 14099 if (!Decl) 14100 return nullptr; 14101 if (FunctionDecl *FD = Decl->getAsFunction()) 14102 FD->setHasSkippedBody(); 14103 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) 14104 MD->setHasSkippedBody(); 14105 return Decl; 14106 } 14107 14108 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 14109 return ActOnFinishFunctionBody(D, BodyArg, false); 14110 } 14111 14112 /// RAII object that pops an ExpressionEvaluationContext when exiting a function 14113 /// body. 14114 class ExitFunctionBodyRAII { 14115 public: 14116 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {} 14117 ~ExitFunctionBodyRAII() { 14118 if (!IsLambda) 14119 S.PopExpressionEvaluationContext(); 14120 } 14121 14122 private: 14123 Sema &S; 14124 bool IsLambda = false; 14125 }; 14126 14127 static void diagnoseImplicitlyRetainedSelf(Sema &S) { 14128 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo; 14129 14130 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) { 14131 if (EscapeInfo.count(BD)) 14132 return EscapeInfo[BD]; 14133 14134 bool R = false; 14135 const BlockDecl *CurBD = BD; 14136 14137 do { 14138 R = !CurBD->doesNotEscape(); 14139 if (R) 14140 break; 14141 CurBD = CurBD->getParent()->getInnermostBlockDecl(); 14142 } while (CurBD); 14143 14144 return EscapeInfo[BD] = R; 14145 }; 14146 14147 // If the location where 'self' is implicitly retained is inside a escaping 14148 // block, emit a diagnostic. 14149 for (const std::pair<SourceLocation, const BlockDecl *> &P : 14150 S.ImplicitlyRetainedSelfLocs) 14151 if (IsOrNestedInEscapingBlock(P.second)) 14152 S.Diag(P.first, diag::warn_implicitly_retains_self) 14153 << FixItHint::CreateInsertion(P.first, "self->"); 14154 } 14155 14156 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 14157 bool IsInstantiation) { 14158 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 14159 14160 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 14161 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 14162 14163 if (getLangOpts().Coroutines && getCurFunction()->isCoroutine()) 14164 CheckCompletedCoroutineBody(FD, Body); 14165 14166 // Do not call PopExpressionEvaluationContext() if it is a lambda because one 14167 // is already popped when finishing the lambda in BuildLambdaExpr(). This is 14168 // meant to pop the context added in ActOnStartOfFunctionDef(). 14169 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD)); 14170 14171 if (FD) { 14172 FD->setBody(Body); 14173 FD->setWillHaveBody(false); 14174 14175 if (getLangOpts().CPlusPlus14) { 14176 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 14177 FD->getReturnType()->isUndeducedType()) { 14178 // If the function has a deduced result type but contains no 'return' 14179 // statements, the result type as written must be exactly 'auto', and 14180 // the deduced result type is 'void'. 14181 if (!FD->getReturnType()->getAs<AutoType>()) { 14182 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 14183 << FD->getReturnType(); 14184 FD->setInvalidDecl(); 14185 } else { 14186 // Substitute 'void' for the 'auto' in the type. 14187 TypeLoc ResultType = getReturnTypeLoc(FD); 14188 Context.adjustDeducedFunctionResultType( 14189 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 14190 } 14191 } 14192 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 14193 // In C++11, we don't use 'auto' deduction rules for lambda call 14194 // operators because we don't support return type deduction. 14195 auto *LSI = getCurLambda(); 14196 if (LSI->HasImplicitReturnType) { 14197 deduceClosureReturnType(*LSI); 14198 14199 // C++11 [expr.prim.lambda]p4: 14200 // [...] if there are no return statements in the compound-statement 14201 // [the deduced type is] the type void 14202 QualType RetType = 14203 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 14204 14205 // Update the return type to the deduced type. 14206 const auto *Proto = FD->getType()->castAs<FunctionProtoType>(); 14207 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 14208 Proto->getExtProtoInfo())); 14209 } 14210 } 14211 14212 // If the function implicitly returns zero (like 'main') or is naked, 14213 // don't complain about missing return statements. 14214 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 14215 WP.disableCheckFallThrough(); 14216 14217 // MSVC permits the use of pure specifier (=0) on function definition, 14218 // defined at class scope, warn about this non-standard construct. 14219 if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine()) 14220 Diag(FD->getLocation(), diag::ext_pure_function_definition); 14221 14222 if (!FD->isInvalidDecl()) { 14223 // Don't diagnose unused parameters of defaulted or deleted functions. 14224 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody()) 14225 DiagnoseUnusedParameters(FD->parameters()); 14226 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 14227 FD->getReturnType(), FD); 14228 14229 // If this is a structor, we need a vtable. 14230 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 14231 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 14232 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 14233 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 14234 14235 // Try to apply the named return value optimization. We have to check 14236 // if we can do this here because lambdas keep return statements around 14237 // to deduce an implicit return type. 14238 if (FD->getReturnType()->isRecordType() && 14239 (!getLangOpts().CPlusPlus || !FD->isDependentContext())) 14240 computeNRVO(Body, getCurFunction()); 14241 } 14242 14243 // GNU warning -Wmissing-prototypes: 14244 // Warn if a global function is defined without a previous 14245 // prototype declaration. This warning is issued even if the 14246 // definition itself provides a prototype. The aim is to detect 14247 // global functions that fail to be declared in header files. 14248 const FunctionDecl *PossiblePrototype = nullptr; 14249 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) { 14250 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 14251 14252 if (PossiblePrototype) { 14253 // We found a declaration that is not a prototype, 14254 // but that could be a zero-parameter prototype 14255 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) { 14256 TypeLoc TL = TI->getTypeLoc(); 14257 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 14258 Diag(PossiblePrototype->getLocation(), 14259 diag::note_declaration_not_a_prototype) 14260 << (FD->getNumParams() != 0) 14261 << (FD->getNumParams() == 0 14262 ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void") 14263 : FixItHint{}); 14264 } 14265 } else { 14266 // Returns true if the token beginning at this Loc is `const`. 14267 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM, 14268 const LangOptions &LangOpts) { 14269 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); 14270 if (LocInfo.first.isInvalid()) 14271 return false; 14272 14273 bool Invalid = false; 14274 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid); 14275 if (Invalid) 14276 return false; 14277 14278 if (LocInfo.second > Buffer.size()) 14279 return false; 14280 14281 const char *LexStart = Buffer.data() + LocInfo.second; 14282 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second); 14283 14284 return StartTok.consume_front("const") && 14285 (StartTok.empty() || isWhitespace(StartTok[0]) || 14286 StartTok.startswith("/*") || StartTok.startswith("//")); 14287 }; 14288 14289 auto findBeginLoc = [&]() { 14290 // If the return type has `const` qualifier, we want to insert 14291 // `static` before `const` (and not before the typename). 14292 if ((FD->getReturnType()->isAnyPointerType() && 14293 FD->getReturnType()->getPointeeType().isConstQualified()) || 14294 FD->getReturnType().isConstQualified()) { 14295 // But only do this if we can determine where the `const` is. 14296 14297 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(), 14298 getLangOpts())) 14299 14300 return FD->getBeginLoc(); 14301 } 14302 return FD->getTypeSpecStartLoc(); 14303 }; 14304 Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 14305 << /* function */ 1 14306 << (FD->getStorageClass() == SC_None 14307 ? FixItHint::CreateInsertion(findBeginLoc(), "static ") 14308 : FixItHint{}); 14309 } 14310 14311 // GNU warning -Wstrict-prototypes 14312 // Warn if K&R function is defined without a previous declaration. 14313 // This warning is issued only if the definition itself does not provide 14314 // a prototype. Only K&R definitions do not provide a prototype. 14315 if (!FD->hasWrittenPrototype()) { 14316 TypeSourceInfo *TI = FD->getTypeSourceInfo(); 14317 TypeLoc TL = TI->getTypeLoc(); 14318 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); 14319 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2; 14320 } 14321 } 14322 14323 // Warn on CPUDispatch with an actual body. 14324 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body) 14325 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body)) 14326 if (!CmpndBody->body_empty()) 14327 Diag(CmpndBody->body_front()->getBeginLoc(), 14328 diag::warn_dispatch_body_ignored); 14329 14330 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 14331 const CXXMethodDecl *KeyFunction; 14332 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 14333 MD->isVirtual() && 14334 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 14335 MD == KeyFunction->getCanonicalDecl()) { 14336 // Update the key-function state if necessary for this ABI. 14337 if (FD->isInlined() && 14338 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 14339 Context.setNonKeyFunction(MD); 14340 14341 // If the newly-chosen key function is already defined, then we 14342 // need to mark the vtable as used retroactively. 14343 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 14344 const FunctionDecl *Definition; 14345 if (KeyFunction && KeyFunction->isDefined(Definition)) 14346 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 14347 } else { 14348 // We just defined they key function; mark the vtable as used. 14349 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 14350 } 14351 } 14352 } 14353 14354 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 14355 "Function parsing confused"); 14356 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 14357 assert(MD == getCurMethodDecl() && "Method parsing confused"); 14358 MD->setBody(Body); 14359 if (!MD->isInvalidDecl()) { 14360 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 14361 MD->getReturnType(), MD); 14362 14363 if (Body) 14364 computeNRVO(Body, getCurFunction()); 14365 } 14366 if (getCurFunction()->ObjCShouldCallSuper) { 14367 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call) 14368 << MD->getSelector().getAsString(); 14369 getCurFunction()->ObjCShouldCallSuper = false; 14370 } 14371 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 14372 const ObjCMethodDecl *InitMethod = nullptr; 14373 bool isDesignated = 14374 MD->isDesignatedInitializerForTheInterface(&InitMethod); 14375 assert(isDesignated && InitMethod); 14376 (void)isDesignated; 14377 14378 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 14379 auto IFace = MD->getClassInterface(); 14380 if (!IFace) 14381 return false; 14382 auto SuperD = IFace->getSuperClass(); 14383 if (!SuperD) 14384 return false; 14385 return SuperD->getIdentifier() == 14386 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 14387 }; 14388 // Don't issue this warning for unavailable inits or direct subclasses 14389 // of NSObject. 14390 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 14391 Diag(MD->getLocation(), 14392 diag::warn_objc_designated_init_missing_super_call); 14393 Diag(InitMethod->getLocation(), 14394 diag::note_objc_designated_init_marked_here); 14395 } 14396 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 14397 } 14398 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 14399 // Don't issue this warning for unavaialable inits. 14400 if (!MD->isUnavailable()) 14401 Diag(MD->getLocation(), 14402 diag::warn_objc_secondary_init_missing_init_call); 14403 getCurFunction()->ObjCWarnForNoInitDelegation = false; 14404 } 14405 14406 diagnoseImplicitlyRetainedSelf(*this); 14407 } else { 14408 // Parsing the function declaration failed in some way. Pop the fake scope 14409 // we pushed on. 14410 PopFunctionScopeInfo(ActivePolicy, dcl); 14411 return nullptr; 14412 } 14413 14414 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 14415 DiagnoseUnguardedAvailabilityViolations(dcl); 14416 14417 assert(!getCurFunction()->ObjCShouldCallSuper && 14418 "This should only be set for ObjC methods, which should have been " 14419 "handled in the block above."); 14420 14421 // Verify and clean out per-function state. 14422 if (Body && (!FD || !FD->isDefaulted())) { 14423 // C++ constructors that have function-try-blocks can't have return 14424 // statements in the handlers of that block. (C++ [except.handle]p14) 14425 // Verify this. 14426 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 14427 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 14428 14429 // Verify that gotos and switch cases don't jump into scopes illegally. 14430 if (getCurFunction()->NeedsScopeChecking() && 14431 !PP.isCodeCompletionEnabled()) 14432 DiagnoseInvalidJumps(Body); 14433 14434 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 14435 if (!Destructor->getParent()->isDependentType()) 14436 CheckDestructor(Destructor); 14437 14438 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 14439 Destructor->getParent()); 14440 } 14441 14442 // If any errors have occurred, clear out any temporaries that may have 14443 // been leftover. This ensures that these temporaries won't be picked up for 14444 // deletion in some later function. 14445 if (getDiagnostics().hasUncompilableErrorOccurred() || 14446 getDiagnostics().getSuppressAllDiagnostics()) { 14447 DiscardCleanupsInEvaluationContext(); 14448 } 14449 if (!getDiagnostics().hasUncompilableErrorOccurred() && 14450 !isa<FunctionTemplateDecl>(dcl)) { 14451 // Since the body is valid, issue any analysis-based warnings that are 14452 // enabled. 14453 ActivePolicy = &WP; 14454 } 14455 14456 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 14457 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose)) 14458 FD->setInvalidDecl(); 14459 14460 if (FD && FD->hasAttr<NakedAttr>()) { 14461 for (const Stmt *S : Body->children()) { 14462 // Allow local register variables without initializer as they don't 14463 // require prologue. 14464 bool RegisterVariables = false; 14465 if (auto *DS = dyn_cast<DeclStmt>(S)) { 14466 for (const auto *Decl : DS->decls()) { 14467 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 14468 RegisterVariables = 14469 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 14470 if (!RegisterVariables) 14471 break; 14472 } 14473 } 14474 } 14475 if (RegisterVariables) 14476 continue; 14477 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 14478 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function); 14479 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 14480 FD->setInvalidDecl(); 14481 break; 14482 } 14483 } 14484 } 14485 14486 assert(ExprCleanupObjects.size() == 14487 ExprEvalContexts.back().NumCleanupObjects && 14488 "Leftover temporaries in function"); 14489 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function"); 14490 assert(MaybeODRUseExprs.empty() && 14491 "Leftover expressions for odr-use checking"); 14492 } 14493 14494 if (!IsInstantiation) 14495 PopDeclContext(); 14496 14497 PopFunctionScopeInfo(ActivePolicy, dcl); 14498 // If any errors have occurred, clear out any temporaries that may have 14499 // been leftover. This ensures that these temporaries won't be picked up for 14500 // deletion in some later function. 14501 if (getDiagnostics().hasUncompilableErrorOccurred()) { 14502 DiscardCleanupsInEvaluationContext(); 14503 } 14504 14505 if (LangOpts.OpenMP || LangOpts.CUDA || LangOpts.SYCLIsDevice) { 14506 auto ES = getEmissionStatus(FD); 14507 if (ES == Sema::FunctionEmissionStatus::Emitted || 14508 ES == Sema::FunctionEmissionStatus::Unknown) 14509 DeclsToCheckForDeferredDiags.push_back(FD); 14510 } 14511 14512 return dcl; 14513 } 14514 14515 /// When we finish delayed parsing of an attribute, we must attach it to the 14516 /// relevant Decl. 14517 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 14518 ParsedAttributes &Attrs) { 14519 // Always attach attributes to the underlying decl. 14520 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 14521 D = TD->getTemplatedDecl(); 14522 ProcessDeclAttributeList(S, D, Attrs); 14523 14524 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 14525 if (Method->isStatic()) 14526 checkThisInStaticMemberFunctionAttributes(Method); 14527 } 14528 14529 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 14530 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 14531 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 14532 IdentifierInfo &II, Scope *S) { 14533 // Find the scope in which the identifier is injected and the corresponding 14534 // DeclContext. 14535 // FIXME: C89 does not say what happens if there is no enclosing block scope. 14536 // In that case, we inject the declaration into the translation unit scope 14537 // instead. 14538 Scope *BlockScope = S; 14539 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) 14540 BlockScope = BlockScope->getParent(); 14541 14542 Scope *ContextScope = BlockScope; 14543 while (!ContextScope->getEntity()) 14544 ContextScope = ContextScope->getParent(); 14545 ContextRAII SavedContext(*this, ContextScope->getEntity()); 14546 14547 // Before we produce a declaration for an implicitly defined 14548 // function, see whether there was a locally-scoped declaration of 14549 // this name as a function or variable. If so, use that 14550 // (non-visible) declaration, and complain about it. 14551 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); 14552 if (ExternCPrev) { 14553 // We still need to inject the function into the enclosing block scope so 14554 // that later (non-call) uses can see it. 14555 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); 14556 14557 // C89 footnote 38: 14558 // If in fact it is not defined as having type "function returning int", 14559 // the behavior is undefined. 14560 if (!isa<FunctionDecl>(ExternCPrev) || 14561 !Context.typesAreCompatible( 14562 cast<FunctionDecl>(ExternCPrev)->getType(), 14563 Context.getFunctionNoProtoType(Context.IntTy))) { 14564 Diag(Loc, diag::ext_use_out_of_scope_declaration) 14565 << ExternCPrev << !getLangOpts().C99; 14566 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 14567 return ExternCPrev; 14568 } 14569 } 14570 14571 // Extension in C99. Legal in C90, but warn about it. 14572 unsigned diag_id; 14573 if (II.getName().startswith("__builtin_")) 14574 diag_id = diag::warn_builtin_unknown; 14575 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. 14576 else if (getLangOpts().OpenCL) 14577 diag_id = diag::err_opencl_implicit_function_decl; 14578 else if (getLangOpts().C99) 14579 diag_id = diag::ext_implicit_function_decl; 14580 else 14581 diag_id = diag::warn_implicit_function_decl; 14582 Diag(Loc, diag_id) << &II; 14583 14584 // If we found a prior declaration of this function, don't bother building 14585 // another one. We've already pushed that one into scope, so there's nothing 14586 // more to do. 14587 if (ExternCPrev) 14588 return ExternCPrev; 14589 14590 // Because typo correction is expensive, only do it if the implicit 14591 // function declaration is going to be treated as an error. 14592 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 14593 TypoCorrection Corrected; 14594 DeclFilterCCC<FunctionDecl> CCC{}; 14595 if (S && (Corrected = 14596 CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName, 14597 S, nullptr, CCC, CTK_NonError))) 14598 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 14599 /*ErrorRecovery*/false); 14600 } 14601 14602 // Set a Declarator for the implicit definition: int foo(); 14603 const char *Dummy; 14604 AttributeFactory attrFactory; 14605 DeclSpec DS(attrFactory); 14606 unsigned DiagID; 14607 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 14608 Context.getPrintingPolicy()); 14609 (void)Error; // Silence warning. 14610 assert(!Error && "Error setting up implicit decl!"); 14611 SourceLocation NoLoc; 14612 Declarator D(DS, DeclaratorContext::BlockContext); 14613 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 14614 /*IsAmbiguous=*/false, 14615 /*LParenLoc=*/NoLoc, 14616 /*Params=*/nullptr, 14617 /*NumParams=*/0, 14618 /*EllipsisLoc=*/NoLoc, 14619 /*RParenLoc=*/NoLoc, 14620 /*RefQualifierIsLvalueRef=*/true, 14621 /*RefQualifierLoc=*/NoLoc, 14622 /*MutableLoc=*/NoLoc, EST_None, 14623 /*ESpecRange=*/SourceRange(), 14624 /*Exceptions=*/nullptr, 14625 /*ExceptionRanges=*/nullptr, 14626 /*NumExceptions=*/0, 14627 /*NoexceptExpr=*/nullptr, 14628 /*ExceptionSpecTokens=*/nullptr, 14629 /*DeclsInPrototype=*/None, Loc, 14630 Loc, D), 14631 std::move(DS.getAttributes()), SourceLocation()); 14632 D.SetIdentifier(&II, Loc); 14633 14634 // Insert this function into the enclosing block scope. 14635 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); 14636 FD->setImplicit(); 14637 14638 AddKnownFunctionAttributes(FD); 14639 14640 return FD; 14641 } 14642 14643 /// If this function is a C++ replaceable global allocation function 14644 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]), 14645 /// adds any function attributes that we know a priori based on the standard. 14646 /// 14647 /// We need to check for duplicate attributes both here and where user-written 14648 /// attributes are applied to declarations. 14649 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction( 14650 FunctionDecl *FD) { 14651 if (FD->isInvalidDecl()) 14652 return; 14653 14654 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New && 14655 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New) 14656 return; 14657 14658 Optional<unsigned> AlignmentParam; 14659 bool IsNothrow = false; 14660 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow)) 14661 return; 14662 14663 // C++2a [basic.stc.dynamic.allocation]p4: 14664 // An allocation function that has a non-throwing exception specification 14665 // indicates failure by returning a null pointer value. Any other allocation 14666 // function never returns a null pointer value and indicates failure only by 14667 // throwing an exception [...] 14668 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>()) 14669 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation())); 14670 14671 // C++2a [basic.stc.dynamic.allocation]p2: 14672 // An allocation function attempts to allocate the requested amount of 14673 // storage. [...] If the request succeeds, the value returned by a 14674 // replaceable allocation function is a [...] pointer value p0 different 14675 // from any previously returned value p1 [...] 14676 // 14677 // However, this particular information is being added in codegen, 14678 // because there is an opt-out switch for it (-fno-assume-sane-operator-new) 14679 14680 // C++2a [basic.stc.dynamic.allocation]p2: 14681 // An allocation function attempts to allocate the requested amount of 14682 // storage. If it is successful, it returns the address of the start of a 14683 // block of storage whose length in bytes is at least as large as the 14684 // requested size. 14685 if (!FD->hasAttr<AllocSizeAttr>()) { 14686 FD->addAttr(AllocSizeAttr::CreateImplicit( 14687 Context, /*ElemSizeParam=*/ParamIdx(1, FD), 14688 /*NumElemsParam=*/ParamIdx(), FD->getLocation())); 14689 } 14690 14691 // C++2a [basic.stc.dynamic.allocation]p3: 14692 // For an allocation function [...], the pointer returned on a successful 14693 // call shall represent the address of storage that is aligned as follows: 14694 // (3.1) If the allocation function takes an argument of type 14695 // std::align_val_t, the storage will have the alignment 14696 // specified by the value of this argument. 14697 if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) { 14698 FD->addAttr(AllocAlignAttr::CreateImplicit( 14699 Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation())); 14700 } 14701 14702 // FIXME: 14703 // C++2a [basic.stc.dynamic.allocation]p3: 14704 // For an allocation function [...], the pointer returned on a successful 14705 // call shall represent the address of storage that is aligned as follows: 14706 // (3.2) Otherwise, if the allocation function is named operator new[], 14707 // the storage is aligned for any object that does not have 14708 // new-extended alignment ([basic.align]) and is no larger than the 14709 // requested size. 14710 // (3.3) Otherwise, the storage is aligned for any object that does not 14711 // have new-extended alignment and is of the requested size. 14712 } 14713 14714 /// Adds any function attributes that we know a priori based on 14715 /// the declaration of this function. 14716 /// 14717 /// These attributes can apply both to implicitly-declared builtins 14718 /// (like __builtin___printf_chk) or to library-declared functions 14719 /// like NSLog or printf. 14720 /// 14721 /// We need to check for duplicate attributes both here and where user-written 14722 /// attributes are applied to declarations. 14723 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 14724 if (FD->isInvalidDecl()) 14725 return; 14726 14727 // If this is a built-in function, map its builtin attributes to 14728 // actual attributes. 14729 if (unsigned BuiltinID = FD->getBuiltinID()) { 14730 // Handle printf-formatting attributes. 14731 unsigned FormatIdx; 14732 bool HasVAListArg; 14733 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 14734 if (!FD->hasAttr<FormatAttr>()) { 14735 const char *fmt = "printf"; 14736 unsigned int NumParams = FD->getNumParams(); 14737 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 14738 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 14739 fmt = "NSString"; 14740 FD->addAttr(FormatAttr::CreateImplicit(Context, 14741 &Context.Idents.get(fmt), 14742 FormatIdx+1, 14743 HasVAListArg ? 0 : FormatIdx+2, 14744 FD->getLocation())); 14745 } 14746 } 14747 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 14748 HasVAListArg)) { 14749 if (!FD->hasAttr<FormatAttr>()) 14750 FD->addAttr(FormatAttr::CreateImplicit(Context, 14751 &Context.Idents.get("scanf"), 14752 FormatIdx+1, 14753 HasVAListArg ? 0 : FormatIdx+2, 14754 FD->getLocation())); 14755 } 14756 14757 // Handle automatically recognized callbacks. 14758 SmallVector<int, 4> Encoding; 14759 if (!FD->hasAttr<CallbackAttr>() && 14760 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding)) 14761 FD->addAttr(CallbackAttr::CreateImplicit( 14762 Context, Encoding.data(), Encoding.size(), FD->getLocation())); 14763 14764 // Mark const if we don't care about errno and that is the only thing 14765 // preventing the function from being const. This allows IRgen to use LLVM 14766 // intrinsics for such functions. 14767 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() && 14768 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) 14769 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14770 14771 // We make "fma" on some platforms const because we know it does not set 14772 // errno in those environments even though it could set errno based on the 14773 // C standard. 14774 const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); 14775 if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) && 14776 !FD->hasAttr<ConstAttr>()) { 14777 switch (BuiltinID) { 14778 case Builtin::BI__builtin_fma: 14779 case Builtin::BI__builtin_fmaf: 14780 case Builtin::BI__builtin_fmal: 14781 case Builtin::BIfma: 14782 case Builtin::BIfmaf: 14783 case Builtin::BIfmal: 14784 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14785 break; 14786 default: 14787 break; 14788 } 14789 } 14790 14791 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 14792 !FD->hasAttr<ReturnsTwiceAttr>()) 14793 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 14794 FD->getLocation())); 14795 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 14796 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 14797 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 14798 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 14799 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 14800 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14801 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 14802 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 14803 // Add the appropriate attribute, depending on the CUDA compilation mode 14804 // and which target the builtin belongs to. For example, during host 14805 // compilation, aux builtins are __device__, while the rest are __host__. 14806 if (getLangOpts().CUDAIsDevice != 14807 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 14808 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 14809 else 14810 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 14811 } 14812 } 14813 14814 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD); 14815 14816 // If C++ exceptions are enabled but we are told extern "C" functions cannot 14817 // throw, add an implicit nothrow attribute to any extern "C" function we come 14818 // across. 14819 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 14820 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 14821 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 14822 if (!FPT || FPT->getExceptionSpecType() == EST_None) 14823 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 14824 } 14825 14826 IdentifierInfo *Name = FD->getIdentifier(); 14827 if (!Name) 14828 return; 14829 if ((!getLangOpts().CPlusPlus && 14830 FD->getDeclContext()->isTranslationUnit()) || 14831 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 14832 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 14833 LinkageSpecDecl::lang_c)) { 14834 // Okay: this could be a libc/libm/Objective-C function we know 14835 // about. 14836 } else 14837 return; 14838 14839 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 14840 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 14841 // target-specific builtins, perhaps? 14842 if (!FD->hasAttr<FormatAttr>()) 14843 FD->addAttr(FormatAttr::CreateImplicit(Context, 14844 &Context.Idents.get("printf"), 2, 14845 Name->isStr("vasprintf") ? 0 : 3, 14846 FD->getLocation())); 14847 } 14848 14849 if (Name->isStr("__CFStringMakeConstantString")) { 14850 // We already have a __builtin___CFStringMakeConstantString, 14851 // but builds that use -fno-constant-cfstrings don't go through that. 14852 if (!FD->hasAttr<FormatArgAttr>()) 14853 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), 14854 FD->getLocation())); 14855 } 14856 } 14857 14858 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 14859 TypeSourceInfo *TInfo) { 14860 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 14861 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 14862 14863 if (!TInfo) { 14864 assert(D.isInvalidType() && "no declarator info for valid type"); 14865 TInfo = Context.getTrivialTypeSourceInfo(T); 14866 } 14867 14868 // Scope manipulation handled by caller. 14869 TypedefDecl *NewTD = 14870 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(), 14871 D.getIdentifierLoc(), D.getIdentifier(), TInfo); 14872 14873 // Bail out immediately if we have an invalid declaration. 14874 if (D.isInvalidType()) { 14875 NewTD->setInvalidDecl(); 14876 return NewTD; 14877 } 14878 14879 if (D.getDeclSpec().isModulePrivateSpecified()) { 14880 if (CurContext->isFunctionOrMethod()) 14881 Diag(NewTD->getLocation(), diag::err_module_private_local) 14882 << 2 << NewTD->getDeclName() 14883 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 14884 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 14885 else 14886 NewTD->setModulePrivate(); 14887 } 14888 14889 // C++ [dcl.typedef]p8: 14890 // If the typedef declaration defines an unnamed class (or 14891 // enum), the first typedef-name declared by the declaration 14892 // to be that class type (or enum type) is used to denote the 14893 // class type (or enum type) for linkage purposes only. 14894 // We need to check whether the type was declared in the declaration. 14895 switch (D.getDeclSpec().getTypeSpecType()) { 14896 case TST_enum: 14897 case TST_struct: 14898 case TST_interface: 14899 case TST_union: 14900 case TST_class: { 14901 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 14902 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 14903 break; 14904 } 14905 14906 default: 14907 break; 14908 } 14909 14910 return NewTD; 14911 } 14912 14913 /// Check that this is a valid underlying type for an enum declaration. 14914 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 14915 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 14916 QualType T = TI->getType(); 14917 14918 if (T->isDependentType()) 14919 return false; 14920 14921 // This doesn't use 'isIntegralType' despite the error message mentioning 14922 // integral type because isIntegralType would also allow enum types in C. 14923 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 14924 if (BT->isInteger()) 14925 return false; 14926 14927 if (T->isExtIntType()) 14928 return false; 14929 14930 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 14931 } 14932 14933 /// Check whether this is a valid redeclaration of a previous enumeration. 14934 /// \return true if the redeclaration was invalid. 14935 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 14936 QualType EnumUnderlyingTy, bool IsFixed, 14937 const EnumDecl *Prev) { 14938 if (IsScoped != Prev->isScoped()) { 14939 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 14940 << Prev->isScoped(); 14941 Diag(Prev->getLocation(), diag::note_previous_declaration); 14942 return true; 14943 } 14944 14945 if (IsFixed && Prev->isFixed()) { 14946 if (!EnumUnderlyingTy->isDependentType() && 14947 !Prev->getIntegerType()->isDependentType() && 14948 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 14949 Prev->getIntegerType())) { 14950 // TODO: Highlight the underlying type of the redeclaration. 14951 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 14952 << EnumUnderlyingTy << Prev->getIntegerType(); 14953 Diag(Prev->getLocation(), diag::note_previous_declaration) 14954 << Prev->getIntegerTypeRange(); 14955 return true; 14956 } 14957 } else if (IsFixed != Prev->isFixed()) { 14958 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 14959 << Prev->isFixed(); 14960 Diag(Prev->getLocation(), diag::note_previous_declaration); 14961 return true; 14962 } 14963 14964 return false; 14965 } 14966 14967 /// Get diagnostic %select index for tag kind for 14968 /// redeclaration diagnostic message. 14969 /// WARNING: Indexes apply to particular diagnostics only! 14970 /// 14971 /// \returns diagnostic %select index. 14972 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 14973 switch (Tag) { 14974 case TTK_Struct: return 0; 14975 case TTK_Interface: return 1; 14976 case TTK_Class: return 2; 14977 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 14978 } 14979 } 14980 14981 /// Determine if tag kind is a class-key compatible with 14982 /// class for redeclaration (class, struct, or __interface). 14983 /// 14984 /// \returns true iff the tag kind is compatible. 14985 static bool isClassCompatTagKind(TagTypeKind Tag) 14986 { 14987 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 14988 } 14989 14990 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 14991 TagTypeKind TTK) { 14992 if (isa<TypedefDecl>(PrevDecl)) 14993 return NTK_Typedef; 14994 else if (isa<TypeAliasDecl>(PrevDecl)) 14995 return NTK_TypeAlias; 14996 else if (isa<ClassTemplateDecl>(PrevDecl)) 14997 return NTK_Template; 14998 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 14999 return NTK_TypeAliasTemplate; 15000 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 15001 return NTK_TemplateTemplateArgument; 15002 switch (TTK) { 15003 case TTK_Struct: 15004 case TTK_Interface: 15005 case TTK_Class: 15006 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 15007 case TTK_Union: 15008 return NTK_NonUnion; 15009 case TTK_Enum: 15010 return NTK_NonEnum; 15011 } 15012 llvm_unreachable("invalid TTK"); 15013 } 15014 15015 /// Determine whether a tag with a given kind is acceptable 15016 /// as a redeclaration of the given tag declaration. 15017 /// 15018 /// \returns true if the new tag kind is acceptable, false otherwise. 15019 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 15020 TagTypeKind NewTag, bool isDefinition, 15021 SourceLocation NewTagLoc, 15022 const IdentifierInfo *Name) { 15023 // C++ [dcl.type.elab]p3: 15024 // The class-key or enum keyword present in the 15025 // elaborated-type-specifier shall agree in kind with the 15026 // declaration to which the name in the elaborated-type-specifier 15027 // refers. This rule also applies to the form of 15028 // elaborated-type-specifier that declares a class-name or 15029 // friend class since it can be construed as referring to the 15030 // definition of the class. Thus, in any 15031 // elaborated-type-specifier, the enum keyword shall be used to 15032 // refer to an enumeration (7.2), the union class-key shall be 15033 // used to refer to a union (clause 9), and either the class or 15034 // struct class-key shall be used to refer to a class (clause 9) 15035 // declared using the class or struct class-key. 15036 TagTypeKind OldTag = Previous->getTagKind(); 15037 if (OldTag != NewTag && 15038 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag))) 15039 return false; 15040 15041 // Tags are compatible, but we might still want to warn on mismatched tags. 15042 // Non-class tags can't be mismatched at this point. 15043 if (!isClassCompatTagKind(NewTag)) 15044 return true; 15045 15046 // Declarations for which -Wmismatched-tags is disabled are entirely ignored 15047 // by our warning analysis. We don't want to warn about mismatches with (eg) 15048 // declarations in system headers that are designed to be specialized, but if 15049 // a user asks us to warn, we should warn if their code contains mismatched 15050 // declarations. 15051 auto IsIgnoredLoc = [&](SourceLocation Loc) { 15052 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch, 15053 Loc); 15054 }; 15055 if (IsIgnoredLoc(NewTagLoc)) 15056 return true; 15057 15058 auto IsIgnored = [&](const TagDecl *Tag) { 15059 return IsIgnoredLoc(Tag->getLocation()); 15060 }; 15061 while (IsIgnored(Previous)) { 15062 Previous = Previous->getPreviousDecl(); 15063 if (!Previous) 15064 return true; 15065 OldTag = Previous->getTagKind(); 15066 } 15067 15068 bool isTemplate = false; 15069 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 15070 isTemplate = Record->getDescribedClassTemplate(); 15071 15072 if (inTemplateInstantiation()) { 15073 if (OldTag != NewTag) { 15074 // In a template instantiation, do not offer fix-its for tag mismatches 15075 // since they usually mess up the template instead of fixing the problem. 15076 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15077 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15078 << getRedeclDiagFromTagKind(OldTag); 15079 // FIXME: Note previous location? 15080 } 15081 return true; 15082 } 15083 15084 if (isDefinition) { 15085 // On definitions, check all previous tags and issue a fix-it for each 15086 // one that doesn't match the current tag. 15087 if (Previous->getDefinition()) { 15088 // Don't suggest fix-its for redefinitions. 15089 return true; 15090 } 15091 15092 bool previousMismatch = false; 15093 for (const TagDecl *I : Previous->redecls()) { 15094 if (I->getTagKind() != NewTag) { 15095 // Ignore previous declarations for which the warning was disabled. 15096 if (IsIgnored(I)) 15097 continue; 15098 15099 if (!previousMismatch) { 15100 previousMismatch = true; 15101 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 15102 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15103 << getRedeclDiagFromTagKind(I->getTagKind()); 15104 } 15105 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 15106 << getRedeclDiagFromTagKind(NewTag) 15107 << FixItHint::CreateReplacement(I->getInnerLocStart(), 15108 TypeWithKeyword::getTagTypeKindName(NewTag)); 15109 } 15110 } 15111 return true; 15112 } 15113 15114 // Identify the prevailing tag kind: this is the kind of the definition (if 15115 // there is a non-ignored definition), or otherwise the kind of the prior 15116 // (non-ignored) declaration. 15117 const TagDecl *PrevDef = Previous->getDefinition(); 15118 if (PrevDef && IsIgnored(PrevDef)) 15119 PrevDef = nullptr; 15120 const TagDecl *Redecl = PrevDef ? PrevDef : Previous; 15121 if (Redecl->getTagKind() != NewTag) { 15122 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15123 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15124 << getRedeclDiagFromTagKind(OldTag); 15125 Diag(Redecl->getLocation(), diag::note_previous_use); 15126 15127 // If there is a previous definition, suggest a fix-it. 15128 if (PrevDef) { 15129 Diag(NewTagLoc, diag::note_struct_class_suggestion) 15130 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 15131 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 15132 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 15133 } 15134 } 15135 15136 return true; 15137 } 15138 15139 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 15140 /// from an outer enclosing namespace or file scope inside a friend declaration. 15141 /// This should provide the commented out code in the following snippet: 15142 /// namespace N { 15143 /// struct X; 15144 /// namespace M { 15145 /// struct Y { friend struct /*N::*/ X; }; 15146 /// } 15147 /// } 15148 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 15149 SourceLocation NameLoc) { 15150 // While the decl is in a namespace, do repeated lookup of that name and see 15151 // if we get the same namespace back. If we do not, continue until 15152 // translation unit scope, at which point we have a fully qualified NNS. 15153 SmallVector<IdentifierInfo *, 4> Namespaces; 15154 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15155 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 15156 // This tag should be declared in a namespace, which can only be enclosed by 15157 // other namespaces. Bail if there's an anonymous namespace in the chain. 15158 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 15159 if (!Namespace || Namespace->isAnonymousNamespace()) 15160 return FixItHint(); 15161 IdentifierInfo *II = Namespace->getIdentifier(); 15162 Namespaces.push_back(II); 15163 NamedDecl *Lookup = SemaRef.LookupSingleName( 15164 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 15165 if (Lookup == Namespace) 15166 break; 15167 } 15168 15169 // Once we have all the namespaces, reverse them to go outermost first, and 15170 // build an NNS. 15171 SmallString<64> Insertion; 15172 llvm::raw_svector_ostream OS(Insertion); 15173 if (DC->isTranslationUnit()) 15174 OS << "::"; 15175 std::reverse(Namespaces.begin(), Namespaces.end()); 15176 for (auto *II : Namespaces) 15177 OS << II->getName() << "::"; 15178 return FixItHint::CreateInsertion(NameLoc, Insertion); 15179 } 15180 15181 /// Determine whether a tag originally declared in context \p OldDC can 15182 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup 15183 /// found a declaration in \p OldDC as a previous decl, perhaps through a 15184 /// using-declaration). 15185 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 15186 DeclContext *NewDC) { 15187 OldDC = OldDC->getRedeclContext(); 15188 NewDC = NewDC->getRedeclContext(); 15189 15190 if (OldDC->Equals(NewDC)) 15191 return true; 15192 15193 // In MSVC mode, we allow a redeclaration if the contexts are related (either 15194 // encloses the other). 15195 if (S.getLangOpts().MSVCCompat && 15196 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 15197 return true; 15198 15199 return false; 15200 } 15201 15202 /// This is invoked when we see 'struct foo' or 'struct {'. In the 15203 /// former case, Name will be non-null. In the later case, Name will be null. 15204 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 15205 /// reference/declaration/definition of a tag. 15206 /// 15207 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 15208 /// trailing-type-specifier) other than one in an alias-declaration. 15209 /// 15210 /// \param SkipBody If non-null, will be set to indicate if the caller should 15211 /// skip the definition of this tag and treat it as if it were a declaration. 15212 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 15213 SourceLocation KWLoc, CXXScopeSpec &SS, 15214 IdentifierInfo *Name, SourceLocation NameLoc, 15215 const ParsedAttributesView &Attrs, AccessSpecifier AS, 15216 SourceLocation ModulePrivateLoc, 15217 MultiTemplateParamsArg TemplateParameterLists, 15218 bool &OwnedDecl, bool &IsDependent, 15219 SourceLocation ScopedEnumKWLoc, 15220 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, 15221 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 15222 SkipBodyInfo *SkipBody) { 15223 // If this is not a definition, it must have a name. 15224 IdentifierInfo *OrigName = Name; 15225 assert((Name != nullptr || TUK == TUK_Definition) && 15226 "Nameless record must be a definition!"); 15227 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 15228 15229 OwnedDecl = false; 15230 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 15231 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 15232 15233 // FIXME: Check member specializations more carefully. 15234 bool isMemberSpecialization = false; 15235 bool Invalid = false; 15236 15237 // We only need to do this matching if we have template parameters 15238 // or a scope specifier, which also conveniently avoids this work 15239 // for non-C++ cases. 15240 if (TemplateParameterLists.size() > 0 || 15241 (SS.isNotEmpty() && TUK != TUK_Reference)) { 15242 if (TemplateParameterList *TemplateParams = 15243 MatchTemplateParametersToScopeSpecifier( 15244 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 15245 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 15246 if (Kind == TTK_Enum) { 15247 Diag(KWLoc, diag::err_enum_template); 15248 return nullptr; 15249 } 15250 15251 if (TemplateParams->size() > 0) { 15252 // This is a declaration or definition of a class template (which may 15253 // be a member of another template). 15254 15255 if (Invalid) 15256 return nullptr; 15257 15258 OwnedDecl = false; 15259 DeclResult Result = CheckClassTemplate( 15260 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams, 15261 AS, ModulePrivateLoc, 15262 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1, 15263 TemplateParameterLists.data(), SkipBody); 15264 return Result.get(); 15265 } else { 15266 // The "template<>" header is extraneous. 15267 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 15268 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 15269 isMemberSpecialization = true; 15270 } 15271 } 15272 } 15273 15274 // Figure out the underlying type if this a enum declaration. We need to do 15275 // this early, because it's needed to detect if this is an incompatible 15276 // redeclaration. 15277 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 15278 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; 15279 15280 if (Kind == TTK_Enum) { 15281 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { 15282 // No underlying type explicitly specified, or we failed to parse the 15283 // type, default to int. 15284 EnumUnderlying = Context.IntTy.getTypePtr(); 15285 } else if (UnderlyingType.get()) { 15286 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 15287 // integral type; any cv-qualification is ignored. 15288 TypeSourceInfo *TI = nullptr; 15289 GetTypeFromParser(UnderlyingType.get(), &TI); 15290 EnumUnderlying = TI; 15291 15292 if (CheckEnumUnderlyingType(TI)) 15293 // Recover by falling back to int. 15294 EnumUnderlying = Context.IntTy.getTypePtr(); 15295 15296 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 15297 UPPC_FixedUnderlyingType)) 15298 EnumUnderlying = Context.IntTy.getTypePtr(); 15299 15300 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) { 15301 // For MSVC ABI compatibility, unfixed enums must use an underlying type 15302 // of 'int'. However, if this is an unfixed forward declaration, don't set 15303 // the underlying type unless the user enables -fms-compatibility. This 15304 // makes unfixed forward declared enums incomplete and is more conforming. 15305 if (TUK == TUK_Definition || getLangOpts().MSVCCompat) 15306 EnumUnderlying = Context.IntTy.getTypePtr(); 15307 } 15308 } 15309 15310 DeclContext *SearchDC = CurContext; 15311 DeclContext *DC = CurContext; 15312 bool isStdBadAlloc = false; 15313 bool isStdAlignValT = false; 15314 15315 RedeclarationKind Redecl = forRedeclarationInCurContext(); 15316 if (TUK == TUK_Friend || TUK == TUK_Reference) 15317 Redecl = NotForRedeclaration; 15318 15319 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C 15320 /// implemented asks for structural equivalence checking, the returned decl 15321 /// here is passed back to the parser, allowing the tag body to be parsed. 15322 auto createTagFromNewDecl = [&]() -> TagDecl * { 15323 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage"); 15324 // If there is an identifier, use the location of the identifier as the 15325 // location of the decl, otherwise use the location of the struct/union 15326 // keyword. 15327 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 15328 TagDecl *New = nullptr; 15329 15330 if (Kind == TTK_Enum) { 15331 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, 15332 ScopedEnum, ScopedEnumUsesClassTag, IsFixed); 15333 // If this is an undefined enum, bail. 15334 if (TUK != TUK_Definition && !Invalid) 15335 return nullptr; 15336 if (EnumUnderlying) { 15337 EnumDecl *ED = cast<EnumDecl>(New); 15338 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) 15339 ED->setIntegerTypeSourceInfo(TI); 15340 else 15341 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); 15342 ED->setPromotionType(ED->getIntegerType()); 15343 } 15344 } else { // struct/union 15345 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 15346 nullptr); 15347 } 15348 15349 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 15350 // Add alignment attributes if necessary; these attributes are checked 15351 // when the ASTContext lays out the structure. 15352 // 15353 // It is important for implementing the correct semantics that this 15354 // happen here (in ActOnTag). The #pragma pack stack is 15355 // maintained as a result of parser callbacks which can occur at 15356 // many points during the parsing of a struct declaration (because 15357 // the #pragma tokens are effectively skipped over during the 15358 // parsing of the struct). 15359 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 15360 AddAlignmentAttributesForRecord(RD); 15361 AddMsStructLayoutForRecord(RD); 15362 } 15363 } 15364 New->setLexicalDeclContext(CurContext); 15365 return New; 15366 }; 15367 15368 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 15369 if (Name && SS.isNotEmpty()) { 15370 // We have a nested-name tag ('struct foo::bar'). 15371 15372 // Check for invalid 'foo::'. 15373 if (SS.isInvalid()) { 15374 Name = nullptr; 15375 goto CreateNewDecl; 15376 } 15377 15378 // If this is a friend or a reference to a class in a dependent 15379 // context, don't try to make a decl for it. 15380 if (TUK == TUK_Friend || TUK == TUK_Reference) { 15381 DC = computeDeclContext(SS, false); 15382 if (!DC) { 15383 IsDependent = true; 15384 return nullptr; 15385 } 15386 } else { 15387 DC = computeDeclContext(SS, true); 15388 if (!DC) { 15389 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 15390 << SS.getRange(); 15391 return nullptr; 15392 } 15393 } 15394 15395 if (RequireCompleteDeclContext(SS, DC)) 15396 return nullptr; 15397 15398 SearchDC = DC; 15399 // Look-up name inside 'foo::'. 15400 LookupQualifiedName(Previous, DC); 15401 15402 if (Previous.isAmbiguous()) 15403 return nullptr; 15404 15405 if (Previous.empty()) { 15406 // Name lookup did not find anything. However, if the 15407 // nested-name-specifier refers to the current instantiation, 15408 // and that current instantiation has any dependent base 15409 // classes, we might find something at instantiation time: treat 15410 // this as a dependent elaborated-type-specifier. 15411 // But this only makes any sense for reference-like lookups. 15412 if (Previous.wasNotFoundInCurrentInstantiation() && 15413 (TUK == TUK_Reference || TUK == TUK_Friend)) { 15414 IsDependent = true; 15415 return nullptr; 15416 } 15417 15418 // A tag 'foo::bar' must already exist. 15419 Diag(NameLoc, diag::err_not_tag_in_scope) 15420 << Kind << Name << DC << SS.getRange(); 15421 Name = nullptr; 15422 Invalid = true; 15423 goto CreateNewDecl; 15424 } 15425 } else if (Name) { 15426 // C++14 [class.mem]p14: 15427 // If T is the name of a class, then each of the following shall have a 15428 // name different from T: 15429 // -- every member of class T that is itself a type 15430 if (TUK != TUK_Reference && TUK != TUK_Friend && 15431 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 15432 return nullptr; 15433 15434 // If this is a named struct, check to see if there was a previous forward 15435 // declaration or definition. 15436 // FIXME: We're looking into outer scopes here, even when we 15437 // shouldn't be. Doing so can result in ambiguities that we 15438 // shouldn't be diagnosing. 15439 LookupName(Previous, S); 15440 15441 // When declaring or defining a tag, ignore ambiguities introduced 15442 // by types using'ed into this scope. 15443 if (Previous.isAmbiguous() && 15444 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 15445 LookupResult::Filter F = Previous.makeFilter(); 15446 while (F.hasNext()) { 15447 NamedDecl *ND = F.next(); 15448 if (!ND->getDeclContext()->getRedeclContext()->Equals( 15449 SearchDC->getRedeclContext())) 15450 F.erase(); 15451 } 15452 F.done(); 15453 } 15454 15455 // C++11 [namespace.memdef]p3: 15456 // If the name in a friend declaration is neither qualified nor 15457 // a template-id and the declaration is a function or an 15458 // elaborated-type-specifier, the lookup to determine whether 15459 // the entity has been previously declared shall not consider 15460 // any scopes outside the innermost enclosing namespace. 15461 // 15462 // MSVC doesn't implement the above rule for types, so a friend tag 15463 // declaration may be a redeclaration of a type declared in an enclosing 15464 // scope. They do implement this rule for friend functions. 15465 // 15466 // Does it matter that this should be by scope instead of by 15467 // semantic context? 15468 if (!Previous.empty() && TUK == TUK_Friend) { 15469 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 15470 LookupResult::Filter F = Previous.makeFilter(); 15471 bool FriendSawTagOutsideEnclosingNamespace = false; 15472 while (F.hasNext()) { 15473 NamedDecl *ND = F.next(); 15474 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15475 if (DC->isFileContext() && 15476 !EnclosingNS->Encloses(ND->getDeclContext())) { 15477 if (getLangOpts().MSVCCompat) 15478 FriendSawTagOutsideEnclosingNamespace = true; 15479 else 15480 F.erase(); 15481 } 15482 } 15483 F.done(); 15484 15485 // Diagnose this MSVC extension in the easy case where lookup would have 15486 // unambiguously found something outside the enclosing namespace. 15487 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 15488 NamedDecl *ND = Previous.getFoundDecl(); 15489 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 15490 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 15491 } 15492 } 15493 15494 // Note: there used to be some attempt at recovery here. 15495 if (Previous.isAmbiguous()) 15496 return nullptr; 15497 15498 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 15499 // FIXME: This makes sure that we ignore the contexts associated 15500 // with C structs, unions, and enums when looking for a matching 15501 // tag declaration or definition. See the similar lookup tweak 15502 // in Sema::LookupName; is there a better way to deal with this? 15503 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 15504 SearchDC = SearchDC->getParent(); 15505 } 15506 } 15507 15508 if (Previous.isSingleResult() && 15509 Previous.getFoundDecl()->isTemplateParameter()) { 15510 // Maybe we will complain about the shadowed template parameter. 15511 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 15512 // Just pretend that we didn't see the previous declaration. 15513 Previous.clear(); 15514 } 15515 15516 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 15517 DC->Equals(getStdNamespace())) { 15518 if (Name->isStr("bad_alloc")) { 15519 // This is a declaration of or a reference to "std::bad_alloc". 15520 isStdBadAlloc = true; 15521 15522 // If std::bad_alloc has been implicitly declared (but made invisible to 15523 // name lookup), fill in this implicit declaration as the previous 15524 // declaration, so that the declarations get chained appropriately. 15525 if (Previous.empty() && StdBadAlloc) 15526 Previous.addDecl(getStdBadAlloc()); 15527 } else if (Name->isStr("align_val_t")) { 15528 isStdAlignValT = true; 15529 if (Previous.empty() && StdAlignValT) 15530 Previous.addDecl(getStdAlignValT()); 15531 } 15532 } 15533 15534 // If we didn't find a previous declaration, and this is a reference 15535 // (or friend reference), move to the correct scope. In C++, we 15536 // also need to do a redeclaration lookup there, just in case 15537 // there's a shadow friend decl. 15538 if (Name && Previous.empty() && 15539 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { 15540 if (Invalid) goto CreateNewDecl; 15541 assert(SS.isEmpty()); 15542 15543 if (TUK == TUK_Reference || IsTemplateParamOrArg) { 15544 // C++ [basic.scope.pdecl]p5: 15545 // -- for an elaborated-type-specifier of the form 15546 // 15547 // class-key identifier 15548 // 15549 // if the elaborated-type-specifier is used in the 15550 // decl-specifier-seq or parameter-declaration-clause of a 15551 // function defined in namespace scope, the identifier is 15552 // declared as a class-name in the namespace that contains 15553 // the declaration; otherwise, except as a friend 15554 // declaration, the identifier is declared in the smallest 15555 // non-class, non-function-prototype scope that contains the 15556 // declaration. 15557 // 15558 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 15559 // C structs and unions. 15560 // 15561 // It is an error in C++ to declare (rather than define) an enum 15562 // type, including via an elaborated type specifier. We'll 15563 // diagnose that later; for now, declare the enum in the same 15564 // scope as we would have picked for any other tag type. 15565 // 15566 // GNU C also supports this behavior as part of its incomplete 15567 // enum types extension, while GNU C++ does not. 15568 // 15569 // Find the context where we'll be declaring the tag. 15570 // FIXME: We would like to maintain the current DeclContext as the 15571 // lexical context, 15572 SearchDC = getTagInjectionContext(SearchDC); 15573 15574 // Find the scope where we'll be declaring the tag. 15575 S = getTagInjectionScope(S, getLangOpts()); 15576 } else { 15577 assert(TUK == TUK_Friend); 15578 // C++ [namespace.memdef]p3: 15579 // If a friend declaration in a non-local class first declares a 15580 // class or function, the friend class or function is a member of 15581 // the innermost enclosing namespace. 15582 SearchDC = SearchDC->getEnclosingNamespaceContext(); 15583 } 15584 15585 // In C++, we need to do a redeclaration lookup to properly 15586 // diagnose some problems. 15587 // FIXME: redeclaration lookup is also used (with and without C++) to find a 15588 // hidden declaration so that we don't get ambiguity errors when using a 15589 // type declared by an elaborated-type-specifier. In C that is not correct 15590 // and we should instead merge compatible types found by lookup. 15591 if (getLangOpts().CPlusPlus) { 15592 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 15593 LookupQualifiedName(Previous, SearchDC); 15594 } else { 15595 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 15596 LookupName(Previous, S); 15597 } 15598 } 15599 15600 // If we have a known previous declaration to use, then use it. 15601 if (Previous.empty() && SkipBody && SkipBody->Previous) 15602 Previous.addDecl(SkipBody->Previous); 15603 15604 if (!Previous.empty()) { 15605 NamedDecl *PrevDecl = Previous.getFoundDecl(); 15606 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 15607 15608 // It's okay to have a tag decl in the same scope as a typedef 15609 // which hides a tag decl in the same scope. Finding this 15610 // insanity with a redeclaration lookup can only actually happen 15611 // in C++. 15612 // 15613 // This is also okay for elaborated-type-specifiers, which is 15614 // technically forbidden by the current standard but which is 15615 // okay according to the likely resolution of an open issue; 15616 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 15617 if (getLangOpts().CPlusPlus) { 15618 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 15619 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 15620 TagDecl *Tag = TT->getDecl(); 15621 if (Tag->getDeclName() == Name && 15622 Tag->getDeclContext()->getRedeclContext() 15623 ->Equals(TD->getDeclContext()->getRedeclContext())) { 15624 PrevDecl = Tag; 15625 Previous.clear(); 15626 Previous.addDecl(Tag); 15627 Previous.resolveKind(); 15628 } 15629 } 15630 } 15631 } 15632 15633 // If this is a redeclaration of a using shadow declaration, it must 15634 // declare a tag in the same context. In MSVC mode, we allow a 15635 // redefinition if either context is within the other. 15636 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 15637 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 15638 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 15639 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 15640 !(OldTag && isAcceptableTagRedeclContext( 15641 *this, OldTag->getDeclContext(), SearchDC))) { 15642 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 15643 Diag(Shadow->getTargetDecl()->getLocation(), 15644 diag::note_using_decl_target); 15645 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) 15646 << 0; 15647 // Recover by ignoring the old declaration. 15648 Previous.clear(); 15649 goto CreateNewDecl; 15650 } 15651 } 15652 15653 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 15654 // If this is a use of a previous tag, or if the tag is already declared 15655 // in the same scope (so that the definition/declaration completes or 15656 // rementions the tag), reuse the decl. 15657 if (TUK == TUK_Reference || TUK == TUK_Friend || 15658 isDeclInScope(DirectPrevDecl, SearchDC, S, 15659 SS.isNotEmpty() || isMemberSpecialization)) { 15660 // Make sure that this wasn't declared as an enum and now used as a 15661 // struct or something similar. 15662 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 15663 TUK == TUK_Definition, KWLoc, 15664 Name)) { 15665 bool SafeToContinue 15666 = (PrevTagDecl->getTagKind() != TTK_Enum && 15667 Kind != TTK_Enum); 15668 if (SafeToContinue) 15669 Diag(KWLoc, diag::err_use_with_wrong_tag) 15670 << Name 15671 << FixItHint::CreateReplacement(SourceRange(KWLoc), 15672 PrevTagDecl->getKindName()); 15673 else 15674 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 15675 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 15676 15677 if (SafeToContinue) 15678 Kind = PrevTagDecl->getTagKind(); 15679 else { 15680 // Recover by making this an anonymous redefinition. 15681 Name = nullptr; 15682 Previous.clear(); 15683 Invalid = true; 15684 } 15685 } 15686 15687 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 15688 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 15689 if (TUK == TUK_Reference || TUK == TUK_Friend) 15690 return PrevTagDecl; 15691 15692 QualType EnumUnderlyingTy; 15693 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 15694 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 15695 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 15696 EnumUnderlyingTy = QualType(T, 0); 15697 15698 // All conflicts with previous declarations are recovered by 15699 // returning the previous declaration, unless this is a definition, 15700 // in which case we want the caller to bail out. 15701 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 15702 ScopedEnum, EnumUnderlyingTy, 15703 IsFixed, PrevEnum)) 15704 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 15705 } 15706 15707 // C++11 [class.mem]p1: 15708 // A member shall not be declared twice in the member-specification, 15709 // except that a nested class or member class template can be declared 15710 // and then later defined. 15711 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 15712 S->isDeclScope(PrevDecl)) { 15713 Diag(NameLoc, diag::ext_member_redeclared); 15714 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 15715 } 15716 15717 if (!Invalid) { 15718 // If this is a use, just return the declaration we found, unless 15719 // we have attributes. 15720 if (TUK == TUK_Reference || TUK == TUK_Friend) { 15721 if (!Attrs.empty()) { 15722 // FIXME: Diagnose these attributes. For now, we create a new 15723 // declaration to hold them. 15724 } else if (TUK == TUK_Reference && 15725 (PrevTagDecl->getFriendObjectKind() == 15726 Decl::FOK_Undeclared || 15727 PrevDecl->getOwningModule() != getCurrentModule()) && 15728 SS.isEmpty()) { 15729 // This declaration is a reference to an existing entity, but 15730 // has different visibility from that entity: it either makes 15731 // a friend visible or it makes a type visible in a new module. 15732 // In either case, create a new declaration. We only do this if 15733 // the declaration would have meant the same thing if no prior 15734 // declaration were found, that is, if it was found in the same 15735 // scope where we would have injected a declaration. 15736 if (!getTagInjectionContext(CurContext)->getRedeclContext() 15737 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 15738 return PrevTagDecl; 15739 // This is in the injected scope, create a new declaration in 15740 // that scope. 15741 S = getTagInjectionScope(S, getLangOpts()); 15742 } else { 15743 return PrevTagDecl; 15744 } 15745 } 15746 15747 // Diagnose attempts to redefine a tag. 15748 if (TUK == TUK_Definition) { 15749 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 15750 // If we're defining a specialization and the previous definition 15751 // is from an implicit instantiation, don't emit an error 15752 // here; we'll catch this in the general case below. 15753 bool IsExplicitSpecializationAfterInstantiation = false; 15754 if (isMemberSpecialization) { 15755 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 15756 IsExplicitSpecializationAfterInstantiation = 15757 RD->getTemplateSpecializationKind() != 15758 TSK_ExplicitSpecialization; 15759 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 15760 IsExplicitSpecializationAfterInstantiation = 15761 ED->getTemplateSpecializationKind() != 15762 TSK_ExplicitSpecialization; 15763 } 15764 15765 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do 15766 // not keep more that one definition around (merge them). However, 15767 // ensure the decl passes the structural compatibility check in 15768 // C11 6.2.7/1 (or 6.1.2.6/1 in C89). 15769 NamedDecl *Hidden = nullptr; 15770 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 15771 // There is a definition of this tag, but it is not visible. We 15772 // explicitly make use of C++'s one definition rule here, and 15773 // assume that this definition is identical to the hidden one 15774 // we already have. Make the existing definition visible and 15775 // use it in place of this one. 15776 if (!getLangOpts().CPlusPlus) { 15777 // Postpone making the old definition visible until after we 15778 // complete parsing the new one and do the structural 15779 // comparison. 15780 SkipBody->CheckSameAsPrevious = true; 15781 SkipBody->New = createTagFromNewDecl(); 15782 SkipBody->Previous = Def; 15783 return Def; 15784 } else { 15785 SkipBody->ShouldSkip = true; 15786 SkipBody->Previous = Def; 15787 makeMergedDefinitionVisible(Hidden); 15788 // Carry on and handle it like a normal definition. We'll 15789 // skip starting the definitiion later. 15790 } 15791 } else if (!IsExplicitSpecializationAfterInstantiation) { 15792 // A redeclaration in function prototype scope in C isn't 15793 // visible elsewhere, so merely issue a warning. 15794 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 15795 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 15796 else 15797 Diag(NameLoc, diag::err_redefinition) << Name; 15798 notePreviousDefinition(Def, 15799 NameLoc.isValid() ? NameLoc : KWLoc); 15800 // If this is a redefinition, recover by making this 15801 // struct be anonymous, which will make any later 15802 // references get the previous definition. 15803 Name = nullptr; 15804 Previous.clear(); 15805 Invalid = true; 15806 } 15807 } else { 15808 // If the type is currently being defined, complain 15809 // about a nested redefinition. 15810 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 15811 if (TD->isBeingDefined()) { 15812 Diag(NameLoc, diag::err_nested_redefinition) << Name; 15813 Diag(PrevTagDecl->getLocation(), 15814 diag::note_previous_definition); 15815 Name = nullptr; 15816 Previous.clear(); 15817 Invalid = true; 15818 } 15819 } 15820 15821 // Okay, this is definition of a previously declared or referenced 15822 // tag. We're going to create a new Decl for it. 15823 } 15824 15825 // Okay, we're going to make a redeclaration. If this is some kind 15826 // of reference, make sure we build the redeclaration in the same DC 15827 // as the original, and ignore the current access specifier. 15828 if (TUK == TUK_Friend || TUK == TUK_Reference) { 15829 SearchDC = PrevTagDecl->getDeclContext(); 15830 AS = AS_none; 15831 } 15832 } 15833 // If we get here we have (another) forward declaration or we 15834 // have a definition. Just create a new decl. 15835 15836 } else { 15837 // If we get here, this is a definition of a new tag type in a nested 15838 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 15839 // new decl/type. We set PrevDecl to NULL so that the entities 15840 // have distinct types. 15841 Previous.clear(); 15842 } 15843 // If we get here, we're going to create a new Decl. If PrevDecl 15844 // is non-NULL, it's a definition of the tag declared by 15845 // PrevDecl. If it's NULL, we have a new definition. 15846 15847 // Otherwise, PrevDecl is not a tag, but was found with tag 15848 // lookup. This is only actually possible in C++, where a few 15849 // things like templates still live in the tag namespace. 15850 } else { 15851 // Use a better diagnostic if an elaborated-type-specifier 15852 // found the wrong kind of type on the first 15853 // (non-redeclaration) lookup. 15854 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 15855 !Previous.isForRedeclaration()) { 15856 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 15857 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 15858 << Kind; 15859 Diag(PrevDecl->getLocation(), diag::note_declared_at); 15860 Invalid = true; 15861 15862 // Otherwise, only diagnose if the declaration is in scope. 15863 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 15864 SS.isNotEmpty() || isMemberSpecialization)) { 15865 // do nothing 15866 15867 // Diagnose implicit declarations introduced by elaborated types. 15868 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 15869 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 15870 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 15871 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 15872 Invalid = true; 15873 15874 // Otherwise it's a declaration. Call out a particularly common 15875 // case here. 15876 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 15877 unsigned Kind = 0; 15878 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 15879 Diag(NameLoc, diag::err_tag_definition_of_typedef) 15880 << Name << Kind << TND->getUnderlyingType(); 15881 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 15882 Invalid = true; 15883 15884 // Otherwise, diagnose. 15885 } else { 15886 // The tag name clashes with something else in the target scope, 15887 // issue an error and recover by making this tag be anonymous. 15888 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 15889 notePreviousDefinition(PrevDecl, NameLoc); 15890 Name = nullptr; 15891 Invalid = true; 15892 } 15893 15894 // The existing declaration isn't relevant to us; we're in a 15895 // new scope, so clear out the previous declaration. 15896 Previous.clear(); 15897 } 15898 } 15899 15900 CreateNewDecl: 15901 15902 TagDecl *PrevDecl = nullptr; 15903 if (Previous.isSingleResult()) 15904 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 15905 15906 // If there is an identifier, use the location of the identifier as the 15907 // location of the decl, otherwise use the location of the struct/union 15908 // keyword. 15909 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 15910 15911 // Otherwise, create a new declaration. If there is a previous 15912 // declaration of the same entity, the two will be linked via 15913 // PrevDecl. 15914 TagDecl *New; 15915 15916 if (Kind == TTK_Enum) { 15917 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 15918 // enum X { A, B, C } D; D should chain to X. 15919 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 15920 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 15921 ScopedEnumUsesClassTag, IsFixed); 15922 15923 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 15924 StdAlignValT = cast<EnumDecl>(New); 15925 15926 // If this is an undefined enum, warn. 15927 if (TUK != TUK_Definition && !Invalid) { 15928 TagDecl *Def; 15929 if (IsFixed && cast<EnumDecl>(New)->isFixed()) { 15930 // C++0x: 7.2p2: opaque-enum-declaration. 15931 // Conflicts are diagnosed above. Do nothing. 15932 } 15933 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 15934 Diag(Loc, diag::ext_forward_ref_enum_def) 15935 << New; 15936 Diag(Def->getLocation(), diag::note_previous_definition); 15937 } else { 15938 unsigned DiagID = diag::ext_forward_ref_enum; 15939 if (getLangOpts().MSVCCompat) 15940 DiagID = diag::ext_ms_forward_ref_enum; 15941 else if (getLangOpts().CPlusPlus) 15942 DiagID = diag::err_forward_ref_enum; 15943 Diag(Loc, DiagID); 15944 } 15945 } 15946 15947 if (EnumUnderlying) { 15948 EnumDecl *ED = cast<EnumDecl>(New); 15949 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 15950 ED->setIntegerTypeSourceInfo(TI); 15951 else 15952 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 15953 ED->setPromotionType(ED->getIntegerType()); 15954 assert(ED->isComplete() && "enum with type should be complete"); 15955 } 15956 } else { 15957 // struct/union/class 15958 15959 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 15960 // struct X { int A; } D; D should chain to X. 15961 if (getLangOpts().CPlusPlus) { 15962 // FIXME: Look for a way to use RecordDecl for simple structs. 15963 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 15964 cast_or_null<CXXRecordDecl>(PrevDecl)); 15965 15966 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 15967 StdBadAlloc = cast<CXXRecordDecl>(New); 15968 } else 15969 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 15970 cast_or_null<RecordDecl>(PrevDecl)); 15971 } 15972 15973 // C++11 [dcl.type]p3: 15974 // A type-specifier-seq shall not define a class or enumeration [...]. 15975 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && 15976 TUK == TUK_Definition) { 15977 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 15978 << Context.getTagDeclType(New); 15979 Invalid = true; 15980 } 15981 15982 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && 15983 DC->getDeclKind() == Decl::Enum) { 15984 Diag(New->getLocation(), diag::err_type_defined_in_enum) 15985 << Context.getTagDeclType(New); 15986 Invalid = true; 15987 } 15988 15989 // Maybe add qualifier info. 15990 if (SS.isNotEmpty()) { 15991 if (SS.isSet()) { 15992 // If this is either a declaration or a definition, check the 15993 // nested-name-specifier against the current context. 15994 if ((TUK == TUK_Definition || TUK == TUK_Declaration) && 15995 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, 15996 isMemberSpecialization)) 15997 Invalid = true; 15998 15999 New->setQualifierInfo(SS.getWithLocInContext(Context)); 16000 if (TemplateParameterLists.size() > 0) { 16001 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 16002 } 16003 } 16004 else 16005 Invalid = true; 16006 } 16007 16008 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 16009 // Add alignment attributes if necessary; these attributes are checked when 16010 // the ASTContext lays out the structure. 16011 // 16012 // It is important for implementing the correct semantics that this 16013 // happen here (in ActOnTag). The #pragma pack stack is 16014 // maintained as a result of parser callbacks which can occur at 16015 // many points during the parsing of a struct declaration (because 16016 // the #pragma tokens are effectively skipped over during the 16017 // parsing of the struct). 16018 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 16019 AddAlignmentAttributesForRecord(RD); 16020 AddMsStructLayoutForRecord(RD); 16021 } 16022 } 16023 16024 if (ModulePrivateLoc.isValid()) { 16025 if (isMemberSpecialization) 16026 Diag(New->getLocation(), diag::err_module_private_specialization) 16027 << 2 16028 << FixItHint::CreateRemoval(ModulePrivateLoc); 16029 // __module_private__ does not apply to local classes. However, we only 16030 // diagnose this as an error when the declaration specifiers are 16031 // freestanding. Here, we just ignore the __module_private__. 16032 else if (!SearchDC->isFunctionOrMethod()) 16033 New->setModulePrivate(); 16034 } 16035 16036 // If this is a specialization of a member class (of a class template), 16037 // check the specialization. 16038 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 16039 Invalid = true; 16040 16041 // If we're declaring or defining a tag in function prototype scope in C, 16042 // note that this type can only be used within the function and add it to 16043 // the list of decls to inject into the function definition scope. 16044 if ((Name || Kind == TTK_Enum) && 16045 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 16046 if (getLangOpts().CPlusPlus) { 16047 // C++ [dcl.fct]p6: 16048 // Types shall not be defined in return or parameter types. 16049 if (TUK == TUK_Definition && !IsTypeSpecifier) { 16050 Diag(Loc, diag::err_type_defined_in_param_type) 16051 << Name; 16052 Invalid = true; 16053 } 16054 } else if (!PrevDecl) { 16055 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 16056 } 16057 } 16058 16059 if (Invalid) 16060 New->setInvalidDecl(); 16061 16062 // Set the lexical context. If the tag has a C++ scope specifier, the 16063 // lexical context will be different from the semantic context. 16064 New->setLexicalDeclContext(CurContext); 16065 16066 // Mark this as a friend decl if applicable. 16067 // In Microsoft mode, a friend declaration also acts as a forward 16068 // declaration so we always pass true to setObjectOfFriendDecl to make 16069 // the tag name visible. 16070 if (TUK == TUK_Friend) 16071 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 16072 16073 // Set the access specifier. 16074 if (!Invalid && SearchDC->isRecord()) 16075 SetMemberAccessSpecifier(New, PrevDecl, AS); 16076 16077 if (PrevDecl) 16078 CheckRedeclarationModuleOwnership(New, PrevDecl); 16079 16080 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) 16081 New->startDefinition(); 16082 16083 ProcessDeclAttributeList(S, New, Attrs); 16084 AddPragmaAttributes(S, New); 16085 16086 // If this has an identifier, add it to the scope stack. 16087 if (TUK == TUK_Friend) { 16088 // We might be replacing an existing declaration in the lookup tables; 16089 // if so, borrow its access specifier. 16090 if (PrevDecl) 16091 New->setAccess(PrevDecl->getAccess()); 16092 16093 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 16094 DC->makeDeclVisibleInContext(New); 16095 if (Name) // can be null along some error paths 16096 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 16097 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 16098 } else if (Name) { 16099 S = getNonFieldDeclScope(S); 16100 PushOnScopeChains(New, S, true); 16101 } else { 16102 CurContext->addDecl(New); 16103 } 16104 16105 // If this is the C FILE type, notify the AST context. 16106 if (IdentifierInfo *II = New->getIdentifier()) 16107 if (!New->isInvalidDecl() && 16108 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 16109 II->isStr("FILE")) 16110 Context.setFILEDecl(New); 16111 16112 if (PrevDecl) 16113 mergeDeclAttributes(New, PrevDecl); 16114 16115 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) 16116 inferGslOwnerPointerAttribute(CXXRD); 16117 16118 // If there's a #pragma GCC visibility in scope, set the visibility of this 16119 // record. 16120 AddPushedVisibilityAttribute(New); 16121 16122 if (isMemberSpecialization && !New->isInvalidDecl()) 16123 CompleteMemberSpecialization(New, Previous); 16124 16125 OwnedDecl = true; 16126 // In C++, don't return an invalid declaration. We can't recover well from 16127 // the cases where we make the type anonymous. 16128 if (Invalid && getLangOpts().CPlusPlus) { 16129 if (New->isBeingDefined()) 16130 if (auto RD = dyn_cast<RecordDecl>(New)) 16131 RD->completeDefinition(); 16132 return nullptr; 16133 } else if (SkipBody && SkipBody->ShouldSkip) { 16134 return SkipBody->Previous; 16135 } else { 16136 return New; 16137 } 16138 } 16139 16140 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 16141 AdjustDeclIfTemplate(TagD); 16142 TagDecl *Tag = cast<TagDecl>(TagD); 16143 16144 // Enter the tag context. 16145 PushDeclContext(S, Tag); 16146 16147 ActOnDocumentableDecl(TagD); 16148 16149 // If there's a #pragma GCC visibility in scope, set the visibility of this 16150 // record. 16151 AddPushedVisibilityAttribute(Tag); 16152 } 16153 16154 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, 16155 SkipBodyInfo &SkipBody) { 16156 if (!hasStructuralCompatLayout(Prev, SkipBody.New)) 16157 return false; 16158 16159 // Make the previous decl visible. 16160 makeMergedDefinitionVisible(SkipBody.Previous); 16161 return true; 16162 } 16163 16164 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 16165 assert(isa<ObjCContainerDecl>(IDecl) && 16166 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 16167 DeclContext *OCD = cast<DeclContext>(IDecl); 16168 assert(OCD->getLexicalParent() == CurContext && 16169 "The next DeclContext should be lexically contained in the current one."); 16170 CurContext = OCD; 16171 return IDecl; 16172 } 16173 16174 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 16175 SourceLocation FinalLoc, 16176 bool IsFinalSpelledSealed, 16177 SourceLocation LBraceLoc) { 16178 AdjustDeclIfTemplate(TagD); 16179 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 16180 16181 FieldCollector->StartClass(); 16182 16183 if (!Record->getIdentifier()) 16184 return; 16185 16186 if (FinalLoc.isValid()) 16187 Record->addAttr(FinalAttr::Create( 16188 Context, FinalLoc, AttributeCommonInfo::AS_Keyword, 16189 static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed))); 16190 16191 // C++ [class]p2: 16192 // [...] The class-name is also inserted into the scope of the 16193 // class itself; this is known as the injected-class-name. For 16194 // purposes of access checking, the injected-class-name is treated 16195 // as if it were a public member name. 16196 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create( 16197 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(), 16198 Record->getLocation(), Record->getIdentifier(), 16199 /*PrevDecl=*/nullptr, 16200 /*DelayTypeCreation=*/true); 16201 Context.getTypeDeclType(InjectedClassName, Record); 16202 InjectedClassName->setImplicit(); 16203 InjectedClassName->setAccess(AS_public); 16204 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 16205 InjectedClassName->setDescribedClassTemplate(Template); 16206 PushOnScopeChains(InjectedClassName, S); 16207 assert(InjectedClassName->isInjectedClassName() && 16208 "Broken injected-class-name"); 16209 } 16210 16211 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 16212 SourceRange BraceRange) { 16213 AdjustDeclIfTemplate(TagD); 16214 TagDecl *Tag = cast<TagDecl>(TagD); 16215 Tag->setBraceRange(BraceRange); 16216 16217 // Make sure we "complete" the definition even it is invalid. 16218 if (Tag->isBeingDefined()) { 16219 assert(Tag->isInvalidDecl() && "We should already have completed it"); 16220 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16221 RD->completeDefinition(); 16222 } 16223 16224 if (isa<CXXRecordDecl>(Tag)) { 16225 FieldCollector->FinishClass(); 16226 } 16227 16228 // Exit this scope of this tag's definition. 16229 PopDeclContext(); 16230 16231 if (getCurLexicalContext()->isObjCContainer() && 16232 Tag->getDeclContext()->isFileContext()) 16233 Tag->setTopLevelDeclInObjCContainer(); 16234 16235 // Notify the consumer that we've defined a tag. 16236 if (!Tag->isInvalidDecl()) 16237 Consumer.HandleTagDeclDefinition(Tag); 16238 } 16239 16240 void Sema::ActOnObjCContainerFinishDefinition() { 16241 // Exit this scope of this interface definition. 16242 PopDeclContext(); 16243 } 16244 16245 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 16246 assert(DC == CurContext && "Mismatch of container contexts"); 16247 OriginalLexicalContext = DC; 16248 ActOnObjCContainerFinishDefinition(); 16249 } 16250 16251 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 16252 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 16253 OriginalLexicalContext = nullptr; 16254 } 16255 16256 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 16257 AdjustDeclIfTemplate(TagD); 16258 TagDecl *Tag = cast<TagDecl>(TagD); 16259 Tag->setInvalidDecl(); 16260 16261 // Make sure we "complete" the definition even it is invalid. 16262 if (Tag->isBeingDefined()) { 16263 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16264 RD->completeDefinition(); 16265 } 16266 16267 // We're undoing ActOnTagStartDefinition here, not 16268 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 16269 // the FieldCollector. 16270 16271 PopDeclContext(); 16272 } 16273 16274 // Note that FieldName may be null for anonymous bitfields. 16275 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 16276 IdentifierInfo *FieldName, 16277 QualType FieldTy, bool IsMsStruct, 16278 Expr *BitWidth, bool *ZeroWidth) { 16279 assert(BitWidth); 16280 if (BitWidth->containsErrors()) 16281 return ExprError(); 16282 16283 // Default to true; that shouldn't confuse checks for emptiness 16284 if (ZeroWidth) 16285 *ZeroWidth = true; 16286 16287 // C99 6.7.2.1p4 - verify the field type. 16288 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 16289 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 16290 // Handle incomplete and sizeless types with a specific error. 16291 if (RequireCompleteSizedType(FieldLoc, FieldTy, 16292 diag::err_field_incomplete_or_sizeless)) 16293 return ExprError(); 16294 if (FieldName) 16295 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 16296 << FieldName << FieldTy << BitWidth->getSourceRange(); 16297 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 16298 << FieldTy << BitWidth->getSourceRange(); 16299 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 16300 UPPC_BitFieldWidth)) 16301 return ExprError(); 16302 16303 // If the bit-width is type- or value-dependent, don't try to check 16304 // it now. 16305 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 16306 return BitWidth; 16307 16308 llvm::APSInt Value; 16309 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 16310 if (ICE.isInvalid()) 16311 return ICE; 16312 BitWidth = ICE.get(); 16313 16314 if (Value != 0 && ZeroWidth) 16315 *ZeroWidth = false; 16316 16317 // Zero-width bitfield is ok for anonymous field. 16318 if (Value == 0 && FieldName) 16319 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 16320 16321 if (Value.isSigned() && Value.isNegative()) { 16322 if (FieldName) 16323 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 16324 << FieldName << Value.toString(10); 16325 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 16326 << Value.toString(10); 16327 } 16328 16329 if (!FieldTy->isDependentType()) { 16330 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 16331 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 16332 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 16333 16334 // Over-wide bitfields are an error in C or when using the MSVC bitfield 16335 // ABI. 16336 bool CStdConstraintViolation = 16337 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 16338 bool MSBitfieldViolation = 16339 Value.ugt(TypeStorageSize) && 16340 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 16341 if (CStdConstraintViolation || MSBitfieldViolation) { 16342 unsigned DiagWidth = 16343 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 16344 if (FieldName) 16345 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 16346 << FieldName << (unsigned)Value.getZExtValue() 16347 << !CStdConstraintViolation << DiagWidth; 16348 16349 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) 16350 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation 16351 << DiagWidth; 16352 } 16353 16354 // Warn on types where the user might conceivably expect to get all 16355 // specified bits as value bits: that's all integral types other than 16356 // 'bool'. 16357 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) { 16358 if (FieldName) 16359 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 16360 << FieldName << (unsigned)Value.getZExtValue() 16361 << (unsigned)TypeWidth; 16362 else 16363 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width) 16364 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth; 16365 } 16366 } 16367 16368 return BitWidth; 16369 } 16370 16371 /// ActOnField - Each field of a C struct/union is passed into this in order 16372 /// to create a FieldDecl object for it. 16373 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 16374 Declarator &D, Expr *BitfieldWidth) { 16375 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 16376 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 16377 /*InitStyle=*/ICIS_NoInit, AS_public); 16378 return Res; 16379 } 16380 16381 /// HandleField - Analyze a field of a C struct or a C++ data member. 16382 /// 16383 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 16384 SourceLocation DeclStart, 16385 Declarator &D, Expr *BitWidth, 16386 InClassInitStyle InitStyle, 16387 AccessSpecifier AS) { 16388 if (D.isDecompositionDeclarator()) { 16389 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 16390 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 16391 << Decomp.getSourceRange(); 16392 return nullptr; 16393 } 16394 16395 IdentifierInfo *II = D.getIdentifier(); 16396 SourceLocation Loc = DeclStart; 16397 if (II) Loc = D.getIdentifierLoc(); 16398 16399 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16400 QualType T = TInfo->getType(); 16401 if (getLangOpts().CPlusPlus) { 16402 CheckExtraCXXDefaultArguments(D); 16403 16404 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 16405 UPPC_DataMemberType)) { 16406 D.setInvalidType(); 16407 T = Context.IntTy; 16408 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 16409 } 16410 } 16411 16412 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 16413 16414 if (D.getDeclSpec().isInlineSpecified()) 16415 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 16416 << getLangOpts().CPlusPlus17; 16417 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 16418 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 16419 diag::err_invalid_thread) 16420 << DeclSpec::getSpecifierName(TSCS); 16421 16422 // Check to see if this name was declared as a member previously 16423 NamedDecl *PrevDecl = nullptr; 16424 LookupResult Previous(*this, II, Loc, LookupMemberName, 16425 ForVisibleRedeclaration); 16426 LookupName(Previous, S); 16427 switch (Previous.getResultKind()) { 16428 case LookupResult::Found: 16429 case LookupResult::FoundUnresolvedValue: 16430 PrevDecl = Previous.getAsSingle<NamedDecl>(); 16431 break; 16432 16433 case LookupResult::FoundOverloaded: 16434 PrevDecl = Previous.getRepresentativeDecl(); 16435 break; 16436 16437 case LookupResult::NotFound: 16438 case LookupResult::NotFoundInCurrentInstantiation: 16439 case LookupResult::Ambiguous: 16440 break; 16441 } 16442 Previous.suppressDiagnostics(); 16443 16444 if (PrevDecl && PrevDecl->isTemplateParameter()) { 16445 // Maybe we will complain about the shadowed template parameter. 16446 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 16447 // Just pretend that we didn't see the previous declaration. 16448 PrevDecl = nullptr; 16449 } 16450 16451 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 16452 PrevDecl = nullptr; 16453 16454 bool Mutable 16455 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 16456 SourceLocation TSSL = D.getBeginLoc(); 16457 FieldDecl *NewFD 16458 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 16459 TSSL, AS, PrevDecl, &D); 16460 16461 if (NewFD->isInvalidDecl()) 16462 Record->setInvalidDecl(); 16463 16464 if (D.getDeclSpec().isModulePrivateSpecified()) 16465 NewFD->setModulePrivate(); 16466 16467 if (NewFD->isInvalidDecl() && PrevDecl) { 16468 // Don't introduce NewFD into scope; there's already something 16469 // with the same name in the same scope. 16470 } else if (II) { 16471 PushOnScopeChains(NewFD, S); 16472 } else 16473 Record->addDecl(NewFD); 16474 16475 return NewFD; 16476 } 16477 16478 /// Build a new FieldDecl and check its well-formedness. 16479 /// 16480 /// This routine builds a new FieldDecl given the fields name, type, 16481 /// record, etc. \p PrevDecl should refer to any previous declaration 16482 /// with the same name and in the same scope as the field to be 16483 /// created. 16484 /// 16485 /// \returns a new FieldDecl. 16486 /// 16487 /// \todo The Declarator argument is a hack. It will be removed once 16488 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 16489 TypeSourceInfo *TInfo, 16490 RecordDecl *Record, SourceLocation Loc, 16491 bool Mutable, Expr *BitWidth, 16492 InClassInitStyle InitStyle, 16493 SourceLocation TSSL, 16494 AccessSpecifier AS, NamedDecl *PrevDecl, 16495 Declarator *D) { 16496 IdentifierInfo *II = Name.getAsIdentifierInfo(); 16497 bool InvalidDecl = false; 16498 if (D) InvalidDecl = D->isInvalidType(); 16499 16500 // If we receive a broken type, recover by assuming 'int' and 16501 // marking this declaration as invalid. 16502 if (T.isNull() || T->containsErrors()) { 16503 InvalidDecl = true; 16504 T = Context.IntTy; 16505 } 16506 16507 QualType EltTy = Context.getBaseElementType(T); 16508 if (!EltTy->isDependentType() && !EltTy->containsErrors()) { 16509 if (RequireCompleteSizedType(Loc, EltTy, 16510 diag::err_field_incomplete_or_sizeless)) { 16511 // Fields of incomplete type force their record to be invalid. 16512 Record->setInvalidDecl(); 16513 InvalidDecl = true; 16514 } else { 16515 NamedDecl *Def; 16516 EltTy->isIncompleteType(&Def); 16517 if (Def && Def->isInvalidDecl()) { 16518 Record->setInvalidDecl(); 16519 InvalidDecl = true; 16520 } 16521 } 16522 } 16523 16524 // TR 18037 does not allow fields to be declared with address space 16525 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() || 16526 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { 16527 Diag(Loc, diag::err_field_with_address_space); 16528 Record->setInvalidDecl(); 16529 InvalidDecl = true; 16530 } 16531 16532 if (LangOpts.OpenCL) { 16533 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 16534 // used as structure or union field: image, sampler, event or block types. 16535 if (T->isEventT() || T->isImageType() || T->isSamplerT() || 16536 T->isBlockPointerType()) { 16537 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 16538 Record->setInvalidDecl(); 16539 InvalidDecl = true; 16540 } 16541 // OpenCL v1.2 s6.9.c: bitfields are not supported. 16542 if (BitWidth) { 16543 Diag(Loc, diag::err_opencl_bitfields); 16544 InvalidDecl = true; 16545 } 16546 } 16547 16548 // Anonymous bit-fields cannot be cv-qualified (CWG 2229). 16549 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && 16550 T.hasQualifiers()) { 16551 InvalidDecl = true; 16552 Diag(Loc, diag::err_anon_bitfield_qualifiers); 16553 } 16554 16555 // C99 6.7.2.1p8: A member of a structure or union may have any type other 16556 // than a variably modified type. 16557 if (!InvalidDecl && T->isVariablyModifiedType()) { 16558 bool SizeIsNegative; 16559 llvm::APSInt Oversized; 16560 16561 TypeSourceInfo *FixedTInfo = 16562 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 16563 SizeIsNegative, 16564 Oversized); 16565 if (FixedTInfo) { 16566 Diag(Loc, diag::warn_illegal_constant_array_size); 16567 TInfo = FixedTInfo; 16568 T = FixedTInfo->getType(); 16569 } else { 16570 if (SizeIsNegative) 16571 Diag(Loc, diag::err_typecheck_negative_array_size); 16572 else if (Oversized.getBoolValue()) 16573 Diag(Loc, diag::err_array_too_large) 16574 << Oversized.toString(10); 16575 else 16576 Diag(Loc, diag::err_typecheck_field_variable_size); 16577 InvalidDecl = true; 16578 } 16579 } 16580 16581 // Fields can not have abstract class types 16582 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 16583 diag::err_abstract_type_in_decl, 16584 AbstractFieldType)) 16585 InvalidDecl = true; 16586 16587 bool ZeroWidth = false; 16588 if (InvalidDecl) 16589 BitWidth = nullptr; 16590 // If this is declared as a bit-field, check the bit-field. 16591 if (BitWidth) { 16592 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 16593 &ZeroWidth).get(); 16594 if (!BitWidth) { 16595 InvalidDecl = true; 16596 BitWidth = nullptr; 16597 ZeroWidth = false; 16598 } 16599 16600 // Only data members can have in-class initializers. 16601 if (BitWidth && !II && InitStyle) { 16602 Diag(Loc, diag::err_anon_bitfield_init); 16603 InvalidDecl = true; 16604 BitWidth = nullptr; 16605 ZeroWidth = false; 16606 } 16607 } 16608 16609 // Check that 'mutable' is consistent with the type of the declaration. 16610 if (!InvalidDecl && Mutable) { 16611 unsigned DiagID = 0; 16612 if (T->isReferenceType()) 16613 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 16614 : diag::err_mutable_reference; 16615 else if (T.isConstQualified()) 16616 DiagID = diag::err_mutable_const; 16617 16618 if (DiagID) { 16619 SourceLocation ErrLoc = Loc; 16620 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 16621 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 16622 Diag(ErrLoc, DiagID); 16623 if (DiagID != diag::ext_mutable_reference) { 16624 Mutable = false; 16625 InvalidDecl = true; 16626 } 16627 } 16628 } 16629 16630 // C++11 [class.union]p8 (DR1460): 16631 // At most one variant member of a union may have a 16632 // brace-or-equal-initializer. 16633 if (InitStyle != ICIS_NoInit) 16634 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 16635 16636 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 16637 BitWidth, Mutable, InitStyle); 16638 if (InvalidDecl) 16639 NewFD->setInvalidDecl(); 16640 16641 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 16642 Diag(Loc, diag::err_duplicate_member) << II; 16643 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 16644 NewFD->setInvalidDecl(); 16645 } 16646 16647 if (!InvalidDecl && getLangOpts().CPlusPlus) { 16648 if (Record->isUnion()) { 16649 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 16650 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 16651 if (RDecl->getDefinition()) { 16652 // C++ [class.union]p1: An object of a class with a non-trivial 16653 // constructor, a non-trivial copy constructor, a non-trivial 16654 // destructor, or a non-trivial copy assignment operator 16655 // cannot be a member of a union, nor can an array of such 16656 // objects. 16657 if (CheckNontrivialField(NewFD)) 16658 NewFD->setInvalidDecl(); 16659 } 16660 } 16661 16662 // C++ [class.union]p1: If a union contains a member of reference type, 16663 // the program is ill-formed, except when compiling with MSVC extensions 16664 // enabled. 16665 if (EltTy->isReferenceType()) { 16666 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 16667 diag::ext_union_member_of_reference_type : 16668 diag::err_union_member_of_reference_type) 16669 << NewFD->getDeclName() << EltTy; 16670 if (!getLangOpts().MicrosoftExt) 16671 NewFD->setInvalidDecl(); 16672 } 16673 } 16674 } 16675 16676 // FIXME: We need to pass in the attributes given an AST 16677 // representation, not a parser representation. 16678 if (D) { 16679 // FIXME: The current scope is almost... but not entirely... correct here. 16680 ProcessDeclAttributes(getCurScope(), NewFD, *D); 16681 16682 if (NewFD->hasAttrs()) 16683 CheckAlignasUnderalignment(NewFD); 16684 } 16685 16686 // In auto-retain/release, infer strong retension for fields of 16687 // retainable type. 16688 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 16689 NewFD->setInvalidDecl(); 16690 16691 if (T.isObjCGCWeak()) 16692 Diag(Loc, diag::warn_attribute_weak_on_field); 16693 16694 NewFD->setAccess(AS); 16695 return NewFD; 16696 } 16697 16698 bool Sema::CheckNontrivialField(FieldDecl *FD) { 16699 assert(FD); 16700 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 16701 16702 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 16703 return false; 16704 16705 QualType EltTy = Context.getBaseElementType(FD->getType()); 16706 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 16707 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 16708 if (RDecl->getDefinition()) { 16709 // We check for copy constructors before constructors 16710 // because otherwise we'll never get complaints about 16711 // copy constructors. 16712 16713 CXXSpecialMember member = CXXInvalid; 16714 // We're required to check for any non-trivial constructors. Since the 16715 // implicit default constructor is suppressed if there are any 16716 // user-declared constructors, we just need to check that there is a 16717 // trivial default constructor and a trivial copy constructor. (We don't 16718 // worry about move constructors here, since this is a C++98 check.) 16719 if (RDecl->hasNonTrivialCopyConstructor()) 16720 member = CXXCopyConstructor; 16721 else if (!RDecl->hasTrivialDefaultConstructor()) 16722 member = CXXDefaultConstructor; 16723 else if (RDecl->hasNonTrivialCopyAssignment()) 16724 member = CXXCopyAssignment; 16725 else if (RDecl->hasNonTrivialDestructor()) 16726 member = CXXDestructor; 16727 16728 if (member != CXXInvalid) { 16729 if (!getLangOpts().CPlusPlus11 && 16730 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 16731 // Objective-C++ ARC: it is an error to have a non-trivial field of 16732 // a union. However, system headers in Objective-C programs 16733 // occasionally have Objective-C lifetime objects within unions, 16734 // and rather than cause the program to fail, we make those 16735 // members unavailable. 16736 SourceLocation Loc = FD->getLocation(); 16737 if (getSourceManager().isInSystemHeader(Loc)) { 16738 if (!FD->hasAttr<UnavailableAttr>()) 16739 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 16740 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 16741 return false; 16742 } 16743 } 16744 16745 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 16746 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 16747 diag::err_illegal_union_or_anon_struct_member) 16748 << FD->getParent()->isUnion() << FD->getDeclName() << member; 16749 DiagnoseNontrivial(RDecl, member); 16750 return !getLangOpts().CPlusPlus11; 16751 } 16752 } 16753 } 16754 16755 return false; 16756 } 16757 16758 /// TranslateIvarVisibility - Translate visibility from a token ID to an 16759 /// AST enum value. 16760 static ObjCIvarDecl::AccessControl 16761 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 16762 switch (ivarVisibility) { 16763 default: llvm_unreachable("Unknown visitibility kind"); 16764 case tok::objc_private: return ObjCIvarDecl::Private; 16765 case tok::objc_public: return ObjCIvarDecl::Public; 16766 case tok::objc_protected: return ObjCIvarDecl::Protected; 16767 case tok::objc_package: return ObjCIvarDecl::Package; 16768 } 16769 } 16770 16771 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 16772 /// in order to create an IvarDecl object for it. 16773 Decl *Sema::ActOnIvar(Scope *S, 16774 SourceLocation DeclStart, 16775 Declarator &D, Expr *BitfieldWidth, 16776 tok::ObjCKeywordKind Visibility) { 16777 16778 IdentifierInfo *II = D.getIdentifier(); 16779 Expr *BitWidth = (Expr*)BitfieldWidth; 16780 SourceLocation Loc = DeclStart; 16781 if (II) Loc = D.getIdentifierLoc(); 16782 16783 // FIXME: Unnamed fields can be handled in various different ways, for 16784 // example, unnamed unions inject all members into the struct namespace! 16785 16786 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16787 QualType T = TInfo->getType(); 16788 16789 if (BitWidth) { 16790 // 6.7.2.1p3, 6.7.2.1p4 16791 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 16792 if (!BitWidth) 16793 D.setInvalidType(); 16794 } else { 16795 // Not a bitfield. 16796 16797 // validate II. 16798 16799 } 16800 if (T->isReferenceType()) { 16801 Diag(Loc, diag::err_ivar_reference_type); 16802 D.setInvalidType(); 16803 } 16804 // C99 6.7.2.1p8: A member of a structure or union may have any type other 16805 // than a variably modified type. 16806 else if (T->isVariablyModifiedType()) { 16807 Diag(Loc, diag::err_typecheck_ivar_variable_size); 16808 D.setInvalidType(); 16809 } 16810 16811 // Get the visibility (access control) for this ivar. 16812 ObjCIvarDecl::AccessControl ac = 16813 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 16814 : ObjCIvarDecl::None; 16815 // Must set ivar's DeclContext to its enclosing interface. 16816 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 16817 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 16818 return nullptr; 16819 ObjCContainerDecl *EnclosingContext; 16820 if (ObjCImplementationDecl *IMPDecl = 16821 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 16822 if (LangOpts.ObjCRuntime.isFragile()) { 16823 // Case of ivar declared in an implementation. Context is that of its class. 16824 EnclosingContext = IMPDecl->getClassInterface(); 16825 assert(EnclosingContext && "Implementation has no class interface!"); 16826 } 16827 else 16828 EnclosingContext = EnclosingDecl; 16829 } else { 16830 if (ObjCCategoryDecl *CDecl = 16831 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 16832 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 16833 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 16834 return nullptr; 16835 } 16836 } 16837 EnclosingContext = EnclosingDecl; 16838 } 16839 16840 // Construct the decl. 16841 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 16842 DeclStart, Loc, II, T, 16843 TInfo, ac, (Expr *)BitfieldWidth); 16844 16845 if (II) { 16846 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 16847 ForVisibleRedeclaration); 16848 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 16849 && !isa<TagDecl>(PrevDecl)) { 16850 Diag(Loc, diag::err_duplicate_member) << II; 16851 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 16852 NewID->setInvalidDecl(); 16853 } 16854 } 16855 16856 // Process attributes attached to the ivar. 16857 ProcessDeclAttributes(S, NewID, D); 16858 16859 if (D.isInvalidType()) 16860 NewID->setInvalidDecl(); 16861 16862 // In ARC, infer 'retaining' for ivars of retainable type. 16863 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 16864 NewID->setInvalidDecl(); 16865 16866 if (D.getDeclSpec().isModulePrivateSpecified()) 16867 NewID->setModulePrivate(); 16868 16869 if (II) { 16870 // FIXME: When interfaces are DeclContexts, we'll need to add 16871 // these to the interface. 16872 S->AddDecl(NewID); 16873 IdResolver.AddDecl(NewID); 16874 } 16875 16876 if (LangOpts.ObjCRuntime.isNonFragile() && 16877 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 16878 Diag(Loc, diag::warn_ivars_in_interface); 16879 16880 return NewID; 16881 } 16882 16883 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 16884 /// class and class extensions. For every class \@interface and class 16885 /// extension \@interface, if the last ivar is a bitfield of any type, 16886 /// then add an implicit `char :0` ivar to the end of that interface. 16887 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 16888 SmallVectorImpl<Decl *> &AllIvarDecls) { 16889 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 16890 return; 16891 16892 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 16893 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 16894 16895 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) 16896 return; 16897 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 16898 if (!ID) { 16899 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 16900 if (!CD->IsClassExtension()) 16901 return; 16902 } 16903 // No need to add this to end of @implementation. 16904 else 16905 return; 16906 } 16907 // All conditions are met. Add a new bitfield to the tail end of ivars. 16908 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 16909 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 16910 16911 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 16912 DeclLoc, DeclLoc, nullptr, 16913 Context.CharTy, 16914 Context.getTrivialTypeSourceInfo(Context.CharTy, 16915 DeclLoc), 16916 ObjCIvarDecl::Private, BW, 16917 true); 16918 AllIvarDecls.push_back(Ivar); 16919 } 16920 16921 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 16922 ArrayRef<Decl *> Fields, SourceLocation LBrac, 16923 SourceLocation RBrac, 16924 const ParsedAttributesView &Attrs) { 16925 assert(EnclosingDecl && "missing record or interface decl"); 16926 16927 // If this is an Objective-C @implementation or category and we have 16928 // new fields here we should reset the layout of the interface since 16929 // it will now change. 16930 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 16931 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 16932 switch (DC->getKind()) { 16933 default: break; 16934 case Decl::ObjCCategory: 16935 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 16936 break; 16937 case Decl::ObjCImplementation: 16938 Context. 16939 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 16940 break; 16941 } 16942 } 16943 16944 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 16945 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl); 16946 16947 // Start counting up the number of named members; make sure to include 16948 // members of anonymous structs and unions in the total. 16949 unsigned NumNamedMembers = 0; 16950 if (Record) { 16951 for (const auto *I : Record->decls()) { 16952 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 16953 if (IFD->getDeclName()) 16954 ++NumNamedMembers; 16955 } 16956 } 16957 16958 // Verify that all the fields are okay. 16959 SmallVector<FieldDecl*, 32> RecFields; 16960 16961 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 16962 i != end; ++i) { 16963 FieldDecl *FD = cast<FieldDecl>(*i); 16964 16965 // Get the type for the field. 16966 const Type *FDTy = FD->getType().getTypePtr(); 16967 16968 if (!FD->isAnonymousStructOrUnion()) { 16969 // Remember all fields written by the user. 16970 RecFields.push_back(FD); 16971 } 16972 16973 // If the field is already invalid for some reason, don't emit more 16974 // diagnostics about it. 16975 if (FD->isInvalidDecl()) { 16976 EnclosingDecl->setInvalidDecl(); 16977 continue; 16978 } 16979 16980 // C99 6.7.2.1p2: 16981 // A structure or union shall not contain a member with 16982 // incomplete or function type (hence, a structure shall not 16983 // contain an instance of itself, but may contain a pointer to 16984 // an instance of itself), except that the last member of a 16985 // structure with more than one named member may have incomplete 16986 // array type; such a structure (and any union containing, 16987 // possibly recursively, a member that is such a structure) 16988 // shall not be a member of a structure or an element of an 16989 // array. 16990 bool IsLastField = (i + 1 == Fields.end()); 16991 if (FDTy->isFunctionType()) { 16992 // Field declared as a function. 16993 Diag(FD->getLocation(), diag::err_field_declared_as_function) 16994 << FD->getDeclName(); 16995 FD->setInvalidDecl(); 16996 EnclosingDecl->setInvalidDecl(); 16997 continue; 16998 } else if (FDTy->isIncompleteArrayType() && 16999 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { 17000 if (Record) { 17001 // Flexible array member. 17002 // Microsoft and g++ is more permissive regarding flexible array. 17003 // It will accept flexible array in union and also 17004 // as the sole element of a struct/class. 17005 unsigned DiagID = 0; 17006 if (!Record->isUnion() && !IsLastField) { 17007 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) 17008 << FD->getDeclName() << FD->getType() << Record->getTagKind(); 17009 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); 17010 FD->setInvalidDecl(); 17011 EnclosingDecl->setInvalidDecl(); 17012 continue; 17013 } else if (Record->isUnion()) 17014 DiagID = getLangOpts().MicrosoftExt 17015 ? diag::ext_flexible_array_union_ms 17016 : getLangOpts().CPlusPlus 17017 ? diag::ext_flexible_array_union_gnu 17018 : diag::err_flexible_array_union; 17019 else if (NumNamedMembers < 1) 17020 DiagID = getLangOpts().MicrosoftExt 17021 ? diag::ext_flexible_array_empty_aggregate_ms 17022 : getLangOpts().CPlusPlus 17023 ? diag::ext_flexible_array_empty_aggregate_gnu 17024 : diag::err_flexible_array_empty_aggregate; 17025 17026 if (DiagID) 17027 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 17028 << Record->getTagKind(); 17029 // While the layout of types that contain virtual bases is not specified 17030 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 17031 // virtual bases after the derived members. This would make a flexible 17032 // array member declared at the end of an object not adjacent to the end 17033 // of the type. 17034 if (CXXRecord && CXXRecord->getNumVBases() != 0) 17035 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 17036 << FD->getDeclName() << Record->getTagKind(); 17037 if (!getLangOpts().C99) 17038 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 17039 << FD->getDeclName() << Record->getTagKind(); 17040 17041 // If the element type has a non-trivial destructor, we would not 17042 // implicitly destroy the elements, so disallow it for now. 17043 // 17044 // FIXME: GCC allows this. We should probably either implicitly delete 17045 // the destructor of the containing class, or just allow this. 17046 QualType BaseElem = Context.getBaseElementType(FD->getType()); 17047 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 17048 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 17049 << FD->getDeclName() << FD->getType(); 17050 FD->setInvalidDecl(); 17051 EnclosingDecl->setInvalidDecl(); 17052 continue; 17053 } 17054 // Okay, we have a legal flexible array member at the end of the struct. 17055 Record->setHasFlexibleArrayMember(true); 17056 } else { 17057 // In ObjCContainerDecl ivars with incomplete array type are accepted, 17058 // unless they are followed by another ivar. That check is done 17059 // elsewhere, after synthesized ivars are known. 17060 } 17061 } else if (!FDTy->isDependentType() && 17062 RequireCompleteSizedType( 17063 FD->getLocation(), FD->getType(), 17064 diag::err_field_incomplete_or_sizeless)) { 17065 // Incomplete type 17066 FD->setInvalidDecl(); 17067 EnclosingDecl->setInvalidDecl(); 17068 continue; 17069 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 17070 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 17071 // A type which contains a flexible array member is considered to be a 17072 // flexible array member. 17073 Record->setHasFlexibleArrayMember(true); 17074 if (!Record->isUnion()) { 17075 // If this is a struct/class and this is not the last element, reject 17076 // it. Note that GCC supports variable sized arrays in the middle of 17077 // structures. 17078 if (!IsLastField) 17079 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 17080 << FD->getDeclName() << FD->getType(); 17081 else { 17082 // We support flexible arrays at the end of structs in 17083 // other structs as an extension. 17084 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 17085 << FD->getDeclName(); 17086 } 17087 } 17088 } 17089 if (isa<ObjCContainerDecl>(EnclosingDecl) && 17090 RequireNonAbstractType(FD->getLocation(), FD->getType(), 17091 diag::err_abstract_type_in_decl, 17092 AbstractIvarType)) { 17093 // Ivars can not have abstract class types 17094 FD->setInvalidDecl(); 17095 } 17096 if (Record && FDTTy->getDecl()->hasObjectMember()) 17097 Record->setHasObjectMember(true); 17098 if (Record && FDTTy->getDecl()->hasVolatileMember()) 17099 Record->setHasVolatileMember(true); 17100 } else if (FDTy->isObjCObjectType()) { 17101 /// A field cannot be an Objective-c object 17102 Diag(FD->getLocation(), diag::err_statically_allocated_object) 17103 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 17104 QualType T = Context.getObjCObjectPointerType(FD->getType()); 17105 FD->setType(T); 17106 } else if (Record && Record->isUnion() && 17107 FD->getType().hasNonTrivialObjCLifetime() && 17108 getSourceManager().isInSystemHeader(FD->getLocation()) && 17109 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() && 17110 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong || 17111 !Context.hasDirectOwnershipQualifier(FD->getType()))) { 17112 // For backward compatibility, fields of C unions declared in system 17113 // headers that have non-trivial ObjC ownership qualifications are marked 17114 // as unavailable unless the qualifier is explicit and __strong. This can 17115 // break ABI compatibility between programs compiled with ARC and MRR, but 17116 // is a better option than rejecting programs using those unions under 17117 // ARC. 17118 FD->addAttr(UnavailableAttr::CreateImplicit( 17119 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, 17120 FD->getLocation())); 17121 } else if (getLangOpts().ObjC && 17122 getLangOpts().getGC() != LangOptions::NonGC && Record && 17123 !Record->hasObjectMember()) { 17124 if (FD->getType()->isObjCObjectPointerType() || 17125 FD->getType().isObjCGCStrong()) 17126 Record->setHasObjectMember(true); 17127 else if (Context.getAsArrayType(FD->getType())) { 17128 QualType BaseType = Context.getBaseElementType(FD->getType()); 17129 if (BaseType->isRecordType() && 17130 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember()) 17131 Record->setHasObjectMember(true); 17132 else if (BaseType->isObjCObjectPointerType() || 17133 BaseType.isObjCGCStrong()) 17134 Record->setHasObjectMember(true); 17135 } 17136 } 17137 17138 if (Record && !getLangOpts().CPlusPlus && 17139 !shouldIgnoreForRecordTriviality(FD)) { 17140 QualType FT = FD->getType(); 17141 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) { 17142 Record->setNonTrivialToPrimitiveDefaultInitialize(true); 17143 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 17144 Record->isUnion()) 17145 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true); 17146 } 17147 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); 17148 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) { 17149 Record->setNonTrivialToPrimitiveCopy(true); 17150 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion()) 17151 Record->setHasNonTrivialToPrimitiveCopyCUnion(true); 17152 } 17153 if (FT.isDestructedType()) { 17154 Record->setNonTrivialToPrimitiveDestroy(true); 17155 Record->setParamDestroyedInCallee(true); 17156 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion()) 17157 Record->setHasNonTrivialToPrimitiveDestructCUnion(true); 17158 } 17159 17160 if (const auto *RT = FT->getAs<RecordType>()) { 17161 if (RT->getDecl()->getArgPassingRestrictions() == 17162 RecordDecl::APK_CanNeverPassInRegs) 17163 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17164 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) 17165 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17166 } 17167 17168 if (Record && FD->getType().isVolatileQualified()) 17169 Record->setHasVolatileMember(true); 17170 // Keep track of the number of named members. 17171 if (FD->getIdentifier()) 17172 ++NumNamedMembers; 17173 } 17174 17175 // Okay, we successfully defined 'Record'. 17176 if (Record) { 17177 bool Completed = false; 17178 if (CXXRecord) { 17179 if (!CXXRecord->isInvalidDecl()) { 17180 // Set access bits correctly on the directly-declared conversions. 17181 for (CXXRecordDecl::conversion_iterator 17182 I = CXXRecord->conversion_begin(), 17183 E = CXXRecord->conversion_end(); I != E; ++I) 17184 I.setAccess((*I)->getAccess()); 17185 } 17186 17187 // Add any implicitly-declared members to this class. 17188 AddImplicitlyDeclaredMembersToClass(CXXRecord); 17189 17190 if (!CXXRecord->isDependentType()) { 17191 if (!CXXRecord->isInvalidDecl()) { 17192 // If we have virtual base classes, we may end up finding multiple 17193 // final overriders for a given virtual function. Check for this 17194 // problem now. 17195 if (CXXRecord->getNumVBases()) { 17196 CXXFinalOverriderMap FinalOverriders; 17197 CXXRecord->getFinalOverriders(FinalOverriders); 17198 17199 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 17200 MEnd = FinalOverriders.end(); 17201 M != MEnd; ++M) { 17202 for (OverridingMethods::iterator SO = M->second.begin(), 17203 SOEnd = M->second.end(); 17204 SO != SOEnd; ++SO) { 17205 assert(SO->second.size() > 0 && 17206 "Virtual function without overriding functions?"); 17207 if (SO->second.size() == 1) 17208 continue; 17209 17210 // C++ [class.virtual]p2: 17211 // In a derived class, if a virtual member function of a base 17212 // class subobject has more than one final overrider the 17213 // program is ill-formed. 17214 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 17215 << (const NamedDecl *)M->first << Record; 17216 Diag(M->first->getLocation(), 17217 diag::note_overridden_virtual_function); 17218 for (OverridingMethods::overriding_iterator 17219 OM = SO->second.begin(), 17220 OMEnd = SO->second.end(); 17221 OM != OMEnd; ++OM) 17222 Diag(OM->Method->getLocation(), diag::note_final_overrider) 17223 << (const NamedDecl *)M->first << OM->Method->getParent(); 17224 17225 Record->setInvalidDecl(); 17226 } 17227 } 17228 CXXRecord->completeDefinition(&FinalOverriders); 17229 Completed = true; 17230 } 17231 } 17232 } 17233 } 17234 17235 if (!Completed) 17236 Record->completeDefinition(); 17237 17238 // Handle attributes before checking the layout. 17239 ProcessDeclAttributeList(S, Record, Attrs); 17240 17241 // We may have deferred checking for a deleted destructor. Check now. 17242 if (CXXRecord) { 17243 auto *Dtor = CXXRecord->getDestructor(); 17244 if (Dtor && Dtor->isImplicit() && 17245 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { 17246 CXXRecord->setImplicitDestructorIsDeleted(); 17247 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 17248 } 17249 } 17250 17251 if (Record->hasAttrs()) { 17252 CheckAlignasUnderalignment(Record); 17253 17254 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 17255 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 17256 IA->getRange(), IA->getBestCase(), 17257 IA->getInheritanceModel()); 17258 } 17259 17260 // Check if the structure/union declaration is a type that can have zero 17261 // size in C. For C this is a language extension, for C++ it may cause 17262 // compatibility problems. 17263 bool CheckForZeroSize; 17264 if (!getLangOpts().CPlusPlus) { 17265 CheckForZeroSize = true; 17266 } else { 17267 // For C++ filter out types that cannot be referenced in C code. 17268 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 17269 CheckForZeroSize = 17270 CXXRecord->getLexicalDeclContext()->isExternCContext() && 17271 !CXXRecord->isDependentType() && 17272 CXXRecord->isCLike(); 17273 } 17274 if (CheckForZeroSize) { 17275 bool ZeroSize = true; 17276 bool IsEmpty = true; 17277 unsigned NonBitFields = 0; 17278 for (RecordDecl::field_iterator I = Record->field_begin(), 17279 E = Record->field_end(); 17280 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 17281 IsEmpty = false; 17282 if (I->isUnnamedBitfield()) { 17283 if (!I->isZeroLengthBitField(Context)) 17284 ZeroSize = false; 17285 } else { 17286 ++NonBitFields; 17287 QualType FieldType = I->getType(); 17288 if (FieldType->isIncompleteType() || 17289 !Context.getTypeSizeInChars(FieldType).isZero()) 17290 ZeroSize = false; 17291 } 17292 } 17293 17294 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 17295 // allowed in C++, but warn if its declaration is inside 17296 // extern "C" block. 17297 if (ZeroSize) { 17298 Diag(RecLoc, getLangOpts().CPlusPlus ? 17299 diag::warn_zero_size_struct_union_in_extern_c : 17300 diag::warn_zero_size_struct_union_compat) 17301 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 17302 } 17303 17304 // Structs without named members are extension in C (C99 6.7.2.1p7), 17305 // but are accepted by GCC. 17306 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 17307 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 17308 diag::ext_no_named_members_in_struct_union) 17309 << Record->isUnion(); 17310 } 17311 } 17312 } else { 17313 ObjCIvarDecl **ClsFields = 17314 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 17315 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 17316 ID->setEndOfDefinitionLoc(RBrac); 17317 // Add ivar's to class's DeclContext. 17318 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17319 ClsFields[i]->setLexicalDeclContext(ID); 17320 ID->addDecl(ClsFields[i]); 17321 } 17322 // Must enforce the rule that ivars in the base classes may not be 17323 // duplicates. 17324 if (ID->getSuperClass()) 17325 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 17326 } else if (ObjCImplementationDecl *IMPDecl = 17327 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 17328 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 17329 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 17330 // Ivar declared in @implementation never belongs to the implementation. 17331 // Only it is in implementation's lexical context. 17332 ClsFields[I]->setLexicalDeclContext(IMPDecl); 17333 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 17334 IMPDecl->setIvarLBraceLoc(LBrac); 17335 IMPDecl->setIvarRBraceLoc(RBrac); 17336 } else if (ObjCCategoryDecl *CDecl = 17337 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 17338 // case of ivars in class extension; all other cases have been 17339 // reported as errors elsewhere. 17340 // FIXME. Class extension does not have a LocEnd field. 17341 // CDecl->setLocEnd(RBrac); 17342 // Add ivar's to class extension's DeclContext. 17343 // Diagnose redeclaration of private ivars. 17344 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 17345 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17346 if (IDecl) { 17347 if (const ObjCIvarDecl *ClsIvar = 17348 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 17349 Diag(ClsFields[i]->getLocation(), 17350 diag::err_duplicate_ivar_declaration); 17351 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 17352 continue; 17353 } 17354 for (const auto *Ext : IDecl->known_extensions()) { 17355 if (const ObjCIvarDecl *ClsExtIvar 17356 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 17357 Diag(ClsFields[i]->getLocation(), 17358 diag::err_duplicate_ivar_declaration); 17359 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 17360 continue; 17361 } 17362 } 17363 } 17364 ClsFields[i]->setLexicalDeclContext(CDecl); 17365 CDecl->addDecl(ClsFields[i]); 17366 } 17367 CDecl->setIvarLBraceLoc(LBrac); 17368 CDecl->setIvarRBraceLoc(RBrac); 17369 } 17370 } 17371 } 17372 17373 /// Determine whether the given integral value is representable within 17374 /// the given type T. 17375 static bool isRepresentableIntegerValue(ASTContext &Context, 17376 llvm::APSInt &Value, 17377 QualType T) { 17378 assert((T->isIntegralType(Context) || T->isEnumeralType()) && 17379 "Integral type required!"); 17380 unsigned BitWidth = Context.getIntWidth(T); 17381 17382 if (Value.isUnsigned() || Value.isNonNegative()) { 17383 if (T->isSignedIntegerOrEnumerationType()) 17384 --BitWidth; 17385 return Value.getActiveBits() <= BitWidth; 17386 } 17387 return Value.getMinSignedBits() <= BitWidth; 17388 } 17389 17390 // Given an integral type, return the next larger integral type 17391 // (or a NULL type of no such type exists). 17392 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 17393 // FIXME: Int128/UInt128 support, which also needs to be introduced into 17394 // enum checking below. 17395 assert((T->isIntegralType(Context) || 17396 T->isEnumeralType()) && "Integral type required!"); 17397 const unsigned NumTypes = 4; 17398 QualType SignedIntegralTypes[NumTypes] = { 17399 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 17400 }; 17401 QualType UnsignedIntegralTypes[NumTypes] = { 17402 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 17403 Context.UnsignedLongLongTy 17404 }; 17405 17406 unsigned BitWidth = Context.getTypeSize(T); 17407 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 17408 : UnsignedIntegralTypes; 17409 for (unsigned I = 0; I != NumTypes; ++I) 17410 if (Context.getTypeSize(Types[I]) > BitWidth) 17411 return Types[I]; 17412 17413 return QualType(); 17414 } 17415 17416 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 17417 EnumConstantDecl *LastEnumConst, 17418 SourceLocation IdLoc, 17419 IdentifierInfo *Id, 17420 Expr *Val) { 17421 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 17422 llvm::APSInt EnumVal(IntWidth); 17423 QualType EltTy; 17424 17425 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 17426 Val = nullptr; 17427 17428 if (Val) 17429 Val = DefaultLvalueConversion(Val).get(); 17430 17431 if (Val) { 17432 if (Enum->isDependentType() || Val->isTypeDependent()) 17433 EltTy = Context.DependentTy; 17434 else { 17435 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) { 17436 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 17437 // constant-expression in the enumerator-definition shall be a converted 17438 // constant expression of the underlying type. 17439 EltTy = Enum->getIntegerType(); 17440 ExprResult Converted = 17441 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 17442 CCEK_Enumerator); 17443 if (Converted.isInvalid()) 17444 Val = nullptr; 17445 else 17446 Val = Converted.get(); 17447 } else if (!Val->isValueDependent() && 17448 !(Val = VerifyIntegerConstantExpression(Val, 17449 &EnumVal).get())) { 17450 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 17451 } else { 17452 if (Enum->isComplete()) { 17453 EltTy = Enum->getIntegerType(); 17454 17455 // In Obj-C and Microsoft mode, require the enumeration value to be 17456 // representable in the underlying type of the enumeration. In C++11, 17457 // we perform a non-narrowing conversion as part of converted constant 17458 // expression checking. 17459 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 17460 if (Context.getTargetInfo() 17461 .getTriple() 17462 .isWindowsMSVCEnvironment()) { 17463 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 17464 } else { 17465 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 17466 } 17467 } 17468 17469 // Cast to the underlying type. 17470 Val = ImpCastExprToType(Val, EltTy, 17471 EltTy->isBooleanType() ? CK_IntegralToBoolean 17472 : CK_IntegralCast) 17473 .get(); 17474 } else if (getLangOpts().CPlusPlus) { 17475 // C++11 [dcl.enum]p5: 17476 // If the underlying type is not fixed, the type of each enumerator 17477 // is the type of its initializing value: 17478 // - If an initializer is specified for an enumerator, the 17479 // initializing value has the same type as the expression. 17480 EltTy = Val->getType(); 17481 } else { 17482 // C99 6.7.2.2p2: 17483 // The expression that defines the value of an enumeration constant 17484 // shall be an integer constant expression that has a value 17485 // representable as an int. 17486 17487 // Complain if the value is not representable in an int. 17488 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 17489 Diag(IdLoc, diag::ext_enum_value_not_int) 17490 << EnumVal.toString(10) << Val->getSourceRange() 17491 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 17492 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 17493 // Force the type of the expression to 'int'. 17494 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 17495 } 17496 EltTy = Val->getType(); 17497 } 17498 } 17499 } 17500 } 17501 17502 if (!Val) { 17503 if (Enum->isDependentType()) 17504 EltTy = Context.DependentTy; 17505 else if (!LastEnumConst) { 17506 // C++0x [dcl.enum]p5: 17507 // If the underlying type is not fixed, the type of each enumerator 17508 // is the type of its initializing value: 17509 // - If no initializer is specified for the first enumerator, the 17510 // initializing value has an unspecified integral type. 17511 // 17512 // GCC uses 'int' for its unspecified integral type, as does 17513 // C99 6.7.2.2p3. 17514 if (Enum->isFixed()) { 17515 EltTy = Enum->getIntegerType(); 17516 } 17517 else { 17518 EltTy = Context.IntTy; 17519 } 17520 } else { 17521 // Assign the last value + 1. 17522 EnumVal = LastEnumConst->getInitVal(); 17523 ++EnumVal; 17524 EltTy = LastEnumConst->getType(); 17525 17526 // Check for overflow on increment. 17527 if (EnumVal < LastEnumConst->getInitVal()) { 17528 // C++0x [dcl.enum]p5: 17529 // If the underlying type is not fixed, the type of each enumerator 17530 // is the type of its initializing value: 17531 // 17532 // - Otherwise the type of the initializing value is the same as 17533 // the type of the initializing value of the preceding enumerator 17534 // unless the incremented value is not representable in that type, 17535 // in which case the type is an unspecified integral type 17536 // sufficient to contain the incremented value. If no such type 17537 // exists, the program is ill-formed. 17538 QualType T = getNextLargerIntegralType(Context, EltTy); 17539 if (T.isNull() || Enum->isFixed()) { 17540 // There is no integral type larger enough to represent this 17541 // value. Complain, then allow the value to wrap around. 17542 EnumVal = LastEnumConst->getInitVal(); 17543 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 17544 ++EnumVal; 17545 if (Enum->isFixed()) 17546 // When the underlying type is fixed, this is ill-formed. 17547 Diag(IdLoc, diag::err_enumerator_wrapped) 17548 << EnumVal.toString(10) 17549 << EltTy; 17550 else 17551 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 17552 << EnumVal.toString(10); 17553 } else { 17554 EltTy = T; 17555 } 17556 17557 // Retrieve the last enumerator's value, extent that type to the 17558 // type that is supposed to be large enough to represent the incremented 17559 // value, then increment. 17560 EnumVal = LastEnumConst->getInitVal(); 17561 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 17562 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 17563 ++EnumVal; 17564 17565 // If we're not in C++, diagnose the overflow of enumerator values, 17566 // which in C99 means that the enumerator value is not representable in 17567 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 17568 // permits enumerator values that are representable in some larger 17569 // integral type. 17570 if (!getLangOpts().CPlusPlus && !T.isNull()) 17571 Diag(IdLoc, diag::warn_enum_value_overflow); 17572 } else if (!getLangOpts().CPlusPlus && 17573 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 17574 // Enforce C99 6.7.2.2p2 even when we compute the next value. 17575 Diag(IdLoc, diag::ext_enum_value_not_int) 17576 << EnumVal.toString(10) << 1; 17577 } 17578 } 17579 } 17580 17581 if (!EltTy->isDependentType()) { 17582 // Make the enumerator value match the signedness and size of the 17583 // enumerator's type. 17584 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 17585 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 17586 } 17587 17588 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 17589 Val, EnumVal); 17590 } 17591 17592 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 17593 SourceLocation IILoc) { 17594 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 17595 !getLangOpts().CPlusPlus) 17596 return SkipBodyInfo(); 17597 17598 // We have an anonymous enum definition. Look up the first enumerator to 17599 // determine if we should merge the definition with an existing one and 17600 // skip the body. 17601 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 17602 forRedeclarationInCurContext()); 17603 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 17604 if (!PrevECD) 17605 return SkipBodyInfo(); 17606 17607 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 17608 NamedDecl *Hidden; 17609 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 17610 SkipBodyInfo Skip; 17611 Skip.Previous = Hidden; 17612 return Skip; 17613 } 17614 17615 return SkipBodyInfo(); 17616 } 17617 17618 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 17619 SourceLocation IdLoc, IdentifierInfo *Id, 17620 const ParsedAttributesView &Attrs, 17621 SourceLocation EqualLoc, Expr *Val) { 17622 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 17623 EnumConstantDecl *LastEnumConst = 17624 cast_or_null<EnumConstantDecl>(lastEnumConst); 17625 17626 // The scope passed in may not be a decl scope. Zip up the scope tree until 17627 // we find one that is. 17628 S = getNonFieldDeclScope(S); 17629 17630 // Verify that there isn't already something declared with this name in this 17631 // scope. 17632 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration); 17633 LookupName(R, S); 17634 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>(); 17635 17636 if (PrevDecl && PrevDecl->isTemplateParameter()) { 17637 // Maybe we will complain about the shadowed template parameter. 17638 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 17639 // Just pretend that we didn't see the previous declaration. 17640 PrevDecl = nullptr; 17641 } 17642 17643 // C++ [class.mem]p15: 17644 // If T is the name of a class, then each of the following shall have a name 17645 // different from T: 17646 // - every enumerator of every member of class T that is an unscoped 17647 // enumerated type 17648 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) 17649 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 17650 DeclarationNameInfo(Id, IdLoc)); 17651 17652 EnumConstantDecl *New = 17653 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 17654 if (!New) 17655 return nullptr; 17656 17657 if (PrevDecl) { 17658 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) { 17659 // Check for other kinds of shadowing not already handled. 17660 CheckShadow(New, PrevDecl, R); 17661 } 17662 17663 // When in C++, we may get a TagDecl with the same name; in this case the 17664 // enum constant will 'hide' the tag. 17665 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 17666 "Received TagDecl when not in C++!"); 17667 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 17668 if (isa<EnumConstantDecl>(PrevDecl)) 17669 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 17670 else 17671 Diag(IdLoc, diag::err_redefinition) << Id; 17672 notePreviousDefinition(PrevDecl, IdLoc); 17673 return nullptr; 17674 } 17675 } 17676 17677 // Process attributes. 17678 ProcessDeclAttributeList(S, New, Attrs); 17679 AddPragmaAttributes(S, New); 17680 17681 // Register this decl in the current scope stack. 17682 New->setAccess(TheEnumDecl->getAccess()); 17683 PushOnScopeChains(New, S); 17684 17685 ActOnDocumentableDecl(New); 17686 17687 return New; 17688 } 17689 17690 // Returns true when the enum initial expression does not trigger the 17691 // duplicate enum warning. A few common cases are exempted as follows: 17692 // Element2 = Element1 17693 // Element2 = Element1 + 1 17694 // Element2 = Element1 - 1 17695 // Where Element2 and Element1 are from the same enum. 17696 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 17697 Expr *InitExpr = ECD->getInitExpr(); 17698 if (!InitExpr) 17699 return true; 17700 InitExpr = InitExpr->IgnoreImpCasts(); 17701 17702 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 17703 if (!BO->isAdditiveOp()) 17704 return true; 17705 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 17706 if (!IL) 17707 return true; 17708 if (IL->getValue() != 1) 17709 return true; 17710 17711 InitExpr = BO->getLHS(); 17712 } 17713 17714 // This checks if the elements are from the same enum. 17715 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 17716 if (!DRE) 17717 return true; 17718 17719 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 17720 if (!EnumConstant) 17721 return true; 17722 17723 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 17724 Enum) 17725 return true; 17726 17727 return false; 17728 } 17729 17730 // Emits a warning when an element is implicitly set a value that 17731 // a previous element has already been set to. 17732 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 17733 EnumDecl *Enum, QualType EnumType) { 17734 // Avoid anonymous enums 17735 if (!Enum->getIdentifier()) 17736 return; 17737 17738 // Only check for small enums. 17739 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 17740 return; 17741 17742 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 17743 return; 17744 17745 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 17746 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; 17747 17748 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 17749 17750 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map. 17751 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap; 17752 17753 // Use int64_t as a key to avoid needing special handling for map keys. 17754 auto EnumConstantToKey = [](const EnumConstantDecl *D) { 17755 llvm::APSInt Val = D->getInitVal(); 17756 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); 17757 }; 17758 17759 DuplicatesVector DupVector; 17760 ValueToVectorMap EnumMap; 17761 17762 // Populate the EnumMap with all values represented by enum constants without 17763 // an initializer. 17764 for (auto *Element : Elements) { 17765 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); 17766 17767 // Null EnumConstantDecl means a previous diagnostic has been emitted for 17768 // this constant. Skip this enum since it may be ill-formed. 17769 if (!ECD) { 17770 return; 17771 } 17772 17773 // Constants with initalizers are handled in the next loop. 17774 if (ECD->getInitExpr()) 17775 continue; 17776 17777 // Duplicate values are handled in the next loop. 17778 EnumMap.insert({EnumConstantToKey(ECD), ECD}); 17779 } 17780 17781 if (EnumMap.size() == 0) 17782 return; 17783 17784 // Create vectors for any values that has duplicates. 17785 for (auto *Element : Elements) { 17786 // The last loop returned if any constant was null. 17787 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); 17788 if (!ValidDuplicateEnum(ECD, Enum)) 17789 continue; 17790 17791 auto Iter = EnumMap.find(EnumConstantToKey(ECD)); 17792 if (Iter == EnumMap.end()) 17793 continue; 17794 17795 DeclOrVector& Entry = Iter->second; 17796 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 17797 // Ensure constants are different. 17798 if (D == ECD) 17799 continue; 17800 17801 // Create new vector and push values onto it. 17802 auto Vec = std::make_unique<ECDVector>(); 17803 Vec->push_back(D); 17804 Vec->push_back(ECD); 17805 17806 // Update entry to point to the duplicates vector. 17807 Entry = Vec.get(); 17808 17809 // Store the vector somewhere we can consult later for quick emission of 17810 // diagnostics. 17811 DupVector.emplace_back(std::move(Vec)); 17812 continue; 17813 } 17814 17815 ECDVector *Vec = Entry.get<ECDVector*>(); 17816 // Make sure constants are not added more than once. 17817 if (*Vec->begin() == ECD) 17818 continue; 17819 17820 Vec->push_back(ECD); 17821 } 17822 17823 // Emit diagnostics. 17824 for (const auto &Vec : DupVector) { 17825 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 17826 17827 // Emit warning for one enum constant. 17828 auto *FirstECD = Vec->front(); 17829 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) 17830 << FirstECD << FirstECD->getInitVal().toString(10) 17831 << FirstECD->getSourceRange(); 17832 17833 // Emit one note for each of the remaining enum constants with 17834 // the same value. 17835 for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end())) 17836 S.Diag(ECD->getLocation(), diag::note_duplicate_element) 17837 << ECD << ECD->getInitVal().toString(10) 17838 << ECD->getSourceRange(); 17839 } 17840 } 17841 17842 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 17843 bool AllowMask) const { 17844 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 17845 assert(ED->isCompleteDefinition() && "expected enum definition"); 17846 17847 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 17848 llvm::APInt &FlagBits = R.first->second; 17849 17850 if (R.second) { 17851 for (auto *E : ED->enumerators()) { 17852 const auto &EVal = E->getInitVal(); 17853 // Only single-bit enumerators introduce new flag values. 17854 if (EVal.isPowerOf2()) 17855 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 17856 } 17857 } 17858 17859 // A value is in a flag enum if either its bits are a subset of the enum's 17860 // flag bits (the first condition) or we are allowing masks and the same is 17861 // true of its complement (the second condition). When masks are allowed, we 17862 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 17863 // 17864 // While it's true that any value could be used as a mask, the assumption is 17865 // that a mask will have all of the insignificant bits set. Anything else is 17866 // likely a logic error. 17867 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 17868 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 17869 } 17870 17871 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 17872 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S, 17873 const ParsedAttributesView &Attrs) { 17874 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 17875 QualType EnumType = Context.getTypeDeclType(Enum); 17876 17877 ProcessDeclAttributeList(S, Enum, Attrs); 17878 17879 if (Enum->isDependentType()) { 17880 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 17881 EnumConstantDecl *ECD = 17882 cast_or_null<EnumConstantDecl>(Elements[i]); 17883 if (!ECD) continue; 17884 17885 ECD->setType(EnumType); 17886 } 17887 17888 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 17889 return; 17890 } 17891 17892 // TODO: If the result value doesn't fit in an int, it must be a long or long 17893 // long value. ISO C does not support this, but GCC does as an extension, 17894 // emit a warning. 17895 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 17896 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 17897 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 17898 17899 // Verify that all the values are okay, compute the size of the values, and 17900 // reverse the list. 17901 unsigned NumNegativeBits = 0; 17902 unsigned NumPositiveBits = 0; 17903 17904 // Keep track of whether all elements have type int. 17905 bool AllElementsInt = true; 17906 17907 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 17908 EnumConstantDecl *ECD = 17909 cast_or_null<EnumConstantDecl>(Elements[i]); 17910 if (!ECD) continue; // Already issued a diagnostic. 17911 17912 const llvm::APSInt &InitVal = ECD->getInitVal(); 17913 17914 // Keep track of the size of positive and negative values. 17915 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 17916 NumPositiveBits = std::max(NumPositiveBits, 17917 (unsigned)InitVal.getActiveBits()); 17918 else 17919 NumNegativeBits = std::max(NumNegativeBits, 17920 (unsigned)InitVal.getMinSignedBits()); 17921 17922 // Keep track of whether every enum element has type int (very common). 17923 if (AllElementsInt) 17924 AllElementsInt = ECD->getType() == Context.IntTy; 17925 } 17926 17927 // Figure out the type that should be used for this enum. 17928 QualType BestType; 17929 unsigned BestWidth; 17930 17931 // C++0x N3000 [conv.prom]p3: 17932 // An rvalue of an unscoped enumeration type whose underlying 17933 // type is not fixed can be converted to an rvalue of the first 17934 // of the following types that can represent all the values of 17935 // the enumeration: int, unsigned int, long int, unsigned long 17936 // int, long long int, or unsigned long long int. 17937 // C99 6.4.4.3p2: 17938 // An identifier declared as an enumeration constant has type int. 17939 // The C99 rule is modified by a gcc extension 17940 QualType BestPromotionType; 17941 17942 bool Packed = Enum->hasAttr<PackedAttr>(); 17943 // -fshort-enums is the equivalent to specifying the packed attribute on all 17944 // enum definitions. 17945 if (LangOpts.ShortEnums) 17946 Packed = true; 17947 17948 // If the enum already has a type because it is fixed or dictated by the 17949 // target, promote that type instead of analyzing the enumerators. 17950 if (Enum->isComplete()) { 17951 BestType = Enum->getIntegerType(); 17952 if (BestType->isPromotableIntegerType()) 17953 BestPromotionType = Context.getPromotedIntegerType(BestType); 17954 else 17955 BestPromotionType = BestType; 17956 17957 BestWidth = Context.getIntWidth(BestType); 17958 } 17959 else if (NumNegativeBits) { 17960 // If there is a negative value, figure out the smallest integer type (of 17961 // int/long/longlong) that fits. 17962 // If it's packed, check also if it fits a char or a short. 17963 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 17964 BestType = Context.SignedCharTy; 17965 BestWidth = CharWidth; 17966 } else if (Packed && NumNegativeBits <= ShortWidth && 17967 NumPositiveBits < ShortWidth) { 17968 BestType = Context.ShortTy; 17969 BestWidth = ShortWidth; 17970 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 17971 BestType = Context.IntTy; 17972 BestWidth = IntWidth; 17973 } else { 17974 BestWidth = Context.getTargetInfo().getLongWidth(); 17975 17976 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 17977 BestType = Context.LongTy; 17978 } else { 17979 BestWidth = Context.getTargetInfo().getLongLongWidth(); 17980 17981 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 17982 Diag(Enum->getLocation(), diag::ext_enum_too_large); 17983 BestType = Context.LongLongTy; 17984 } 17985 } 17986 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 17987 } else { 17988 // If there is no negative value, figure out the smallest type that fits 17989 // all of the enumerator values. 17990 // If it's packed, check also if it fits a char or a short. 17991 if (Packed && NumPositiveBits <= CharWidth) { 17992 BestType = Context.UnsignedCharTy; 17993 BestPromotionType = Context.IntTy; 17994 BestWidth = CharWidth; 17995 } else if (Packed && NumPositiveBits <= ShortWidth) { 17996 BestType = Context.UnsignedShortTy; 17997 BestPromotionType = Context.IntTy; 17998 BestWidth = ShortWidth; 17999 } else if (NumPositiveBits <= IntWidth) { 18000 BestType = Context.UnsignedIntTy; 18001 BestWidth = IntWidth; 18002 BestPromotionType 18003 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18004 ? Context.UnsignedIntTy : Context.IntTy; 18005 } else if (NumPositiveBits <= 18006 (BestWidth = Context.getTargetInfo().getLongWidth())) { 18007 BestType = Context.UnsignedLongTy; 18008 BestPromotionType 18009 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18010 ? Context.UnsignedLongTy : Context.LongTy; 18011 } else { 18012 BestWidth = Context.getTargetInfo().getLongLongWidth(); 18013 assert(NumPositiveBits <= BestWidth && 18014 "How could an initializer get larger than ULL?"); 18015 BestType = Context.UnsignedLongLongTy; 18016 BestPromotionType 18017 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18018 ? Context.UnsignedLongLongTy : Context.LongLongTy; 18019 } 18020 } 18021 18022 // Loop over all of the enumerator constants, changing their types to match 18023 // the type of the enum if needed. 18024 for (auto *D : Elements) { 18025 auto *ECD = cast_or_null<EnumConstantDecl>(D); 18026 if (!ECD) continue; // Already issued a diagnostic. 18027 18028 // Standard C says the enumerators have int type, but we allow, as an 18029 // extension, the enumerators to be larger than int size. If each 18030 // enumerator value fits in an int, type it as an int, otherwise type it the 18031 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 18032 // that X has type 'int', not 'unsigned'. 18033 18034 // Determine whether the value fits into an int. 18035 llvm::APSInt InitVal = ECD->getInitVal(); 18036 18037 // If it fits into an integer type, force it. Otherwise force it to match 18038 // the enum decl type. 18039 QualType NewTy; 18040 unsigned NewWidth; 18041 bool NewSign; 18042 if (!getLangOpts().CPlusPlus && 18043 !Enum->isFixed() && 18044 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 18045 NewTy = Context.IntTy; 18046 NewWidth = IntWidth; 18047 NewSign = true; 18048 } else if (ECD->getType() == BestType) { 18049 // Already the right type! 18050 if (getLangOpts().CPlusPlus) 18051 // C++ [dcl.enum]p4: Following the closing brace of an 18052 // enum-specifier, each enumerator has the type of its 18053 // enumeration. 18054 ECD->setType(EnumType); 18055 continue; 18056 } else { 18057 NewTy = BestType; 18058 NewWidth = BestWidth; 18059 NewSign = BestType->isSignedIntegerOrEnumerationType(); 18060 } 18061 18062 // Adjust the APSInt value. 18063 InitVal = InitVal.extOrTrunc(NewWidth); 18064 InitVal.setIsSigned(NewSign); 18065 ECD->setInitVal(InitVal); 18066 18067 // Adjust the Expr initializer and type. 18068 if (ECD->getInitExpr() && 18069 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 18070 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 18071 CK_IntegralCast, 18072 ECD->getInitExpr(), 18073 /*base paths*/ nullptr, 18074 VK_RValue)); 18075 if (getLangOpts().CPlusPlus) 18076 // C++ [dcl.enum]p4: Following the closing brace of an 18077 // enum-specifier, each enumerator has the type of its 18078 // enumeration. 18079 ECD->setType(EnumType); 18080 else 18081 ECD->setType(NewTy); 18082 } 18083 18084 Enum->completeDefinition(BestType, BestPromotionType, 18085 NumPositiveBits, NumNegativeBits); 18086 18087 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 18088 18089 if (Enum->isClosedFlag()) { 18090 for (Decl *D : Elements) { 18091 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 18092 if (!ECD) continue; // Already issued a diagnostic. 18093 18094 llvm::APSInt InitVal = ECD->getInitVal(); 18095 if (InitVal != 0 && !InitVal.isPowerOf2() && 18096 !IsValueInFlagEnum(Enum, InitVal, true)) 18097 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 18098 << ECD << Enum; 18099 } 18100 } 18101 18102 // Now that the enum type is defined, ensure it's not been underaligned. 18103 if (Enum->hasAttrs()) 18104 CheckAlignasUnderalignment(Enum); 18105 } 18106 18107 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 18108 SourceLocation StartLoc, 18109 SourceLocation EndLoc) { 18110 StringLiteral *AsmString = cast<StringLiteral>(expr); 18111 18112 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 18113 AsmString, StartLoc, 18114 EndLoc); 18115 CurContext->addDecl(New); 18116 return New; 18117 } 18118 18119 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 18120 IdentifierInfo* AliasName, 18121 SourceLocation PragmaLoc, 18122 SourceLocation NameLoc, 18123 SourceLocation AliasNameLoc) { 18124 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 18125 LookupOrdinaryName); 18126 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc), 18127 AttributeCommonInfo::AS_Pragma); 18128 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit( 18129 Context, AliasName->getName(), /*LiteralLabel=*/true, Info); 18130 18131 // If a declaration that: 18132 // 1) declares a function or a variable 18133 // 2) has external linkage 18134 // already exists, add a label attribute to it. 18135 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18136 if (isDeclExternC(PrevDecl)) 18137 PrevDecl->addAttr(Attr); 18138 else 18139 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 18140 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 18141 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 18142 } else 18143 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 18144 } 18145 18146 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 18147 SourceLocation PragmaLoc, 18148 SourceLocation NameLoc) { 18149 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 18150 18151 if (PrevDecl) { 18152 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma)); 18153 } else { 18154 (void)WeakUndeclaredIdentifiers.insert( 18155 std::pair<IdentifierInfo*,WeakInfo> 18156 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 18157 } 18158 } 18159 18160 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 18161 IdentifierInfo* AliasName, 18162 SourceLocation PragmaLoc, 18163 SourceLocation NameLoc, 18164 SourceLocation AliasNameLoc) { 18165 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 18166 LookupOrdinaryName); 18167 WeakInfo W = WeakInfo(Name, NameLoc); 18168 18169 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18170 if (!PrevDecl->hasAttr<AliasAttr>()) 18171 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 18172 DeclApplyPragmaWeak(TUScope, ND, W); 18173 } else { 18174 (void)WeakUndeclaredIdentifiers.insert( 18175 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 18176 } 18177 } 18178 18179 Decl *Sema::getObjCDeclContext() const { 18180 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 18181 } 18182 18183 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD, 18184 bool Final) { 18185 // SYCL functions can be template, so we check if they have appropriate 18186 // attribute prior to checking if it is a template. 18187 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>()) 18188 return FunctionEmissionStatus::Emitted; 18189 18190 // Templates are emitted when they're instantiated. 18191 if (FD->isDependentContext()) 18192 return FunctionEmissionStatus::TemplateDiscarded; 18193 18194 FunctionEmissionStatus OMPES = FunctionEmissionStatus::Unknown; 18195 if (LangOpts.OpenMPIsDevice) { 18196 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18197 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18198 if (DevTy.hasValue()) { 18199 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host) 18200 OMPES = FunctionEmissionStatus::OMPDiscarded; 18201 else if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost || 18202 *DevTy == OMPDeclareTargetDeclAttr::DT_Any) { 18203 OMPES = FunctionEmissionStatus::Emitted; 18204 } 18205 } 18206 } else if (LangOpts.OpenMP) { 18207 // In OpenMP 4.5 all the functions are host functions. 18208 if (LangOpts.OpenMP <= 45) { 18209 OMPES = FunctionEmissionStatus::Emitted; 18210 } else { 18211 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18212 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18213 // In OpenMP 5.0 or above, DevTy may be changed later by 18214 // #pragma omp declare target to(*) device_type(*). Therefore DevTy 18215 // having no value does not imply host. The emission status will be 18216 // checked again at the end of compilation unit. 18217 if (DevTy.hasValue()) { 18218 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) { 18219 OMPES = FunctionEmissionStatus::OMPDiscarded; 18220 } else if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host || 18221 *DevTy == OMPDeclareTargetDeclAttr::DT_Any) 18222 OMPES = FunctionEmissionStatus::Emitted; 18223 } else if (Final) 18224 OMPES = FunctionEmissionStatus::Emitted; 18225 } 18226 } 18227 if (OMPES == FunctionEmissionStatus::OMPDiscarded || 18228 (OMPES == FunctionEmissionStatus::Emitted && !LangOpts.CUDA)) 18229 return OMPES; 18230 18231 if (LangOpts.CUDA) { 18232 // When compiling for device, host functions are never emitted. Similarly, 18233 // when compiling for host, device and global functions are never emitted. 18234 // (Technically, we do emit a host-side stub for global functions, but this 18235 // doesn't count for our purposes here.) 18236 Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD); 18237 if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host) 18238 return FunctionEmissionStatus::CUDADiscarded; 18239 if (!LangOpts.CUDAIsDevice && 18240 (T == Sema::CFT_Device || T == Sema::CFT_Global)) 18241 return FunctionEmissionStatus::CUDADiscarded; 18242 18243 // Check whether this function is externally visible -- if so, it's 18244 // known-emitted. 18245 // 18246 // We have to check the GVA linkage of the function's *definition* -- if we 18247 // only have a declaration, we don't know whether or not the function will 18248 // be emitted, because (say) the definition could include "inline". 18249 FunctionDecl *Def = FD->getDefinition(); 18250 18251 if (Def && 18252 !isDiscardableGVALinkage(getASTContext().GetGVALinkageForFunction(Def)) 18253 && (!LangOpts.OpenMP || OMPES == FunctionEmissionStatus::Emitted)) 18254 return FunctionEmissionStatus::Emitted; 18255 } 18256 18257 // Otherwise, the function is known-emitted if it's in our set of 18258 // known-emitted functions. 18259 return FunctionEmissionStatus::Unknown; 18260 } 18261 18262 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) { 18263 // Host-side references to a __global__ function refer to the stub, so the 18264 // function itself is never emitted and therefore should not be marked. 18265 // If we have host fn calls kernel fn calls host+device, the HD function 18266 // does not get instantiated on the host. We model this by omitting at the 18267 // call to the kernel from the callgraph. This ensures that, when compiling 18268 // for host, only HD functions actually called from the host get marked as 18269 // known-emitted. 18270 return LangOpts.CUDA && !LangOpts.CUDAIsDevice && 18271 IdentifyCUDATarget(Callee) == CFT_Global; 18272 } 18273