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 (Decl->getType()->isDependentType()) 6294 return; 6295 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) { 6296 QualType Type = Var->getType(); 6297 if (Type->isSamplerT() || Type->isVoidType()) 6298 return; 6299 LangAS ImplAS = LangAS::opencl_private; 6300 if ((getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) && 6301 Var->hasGlobalStorage()) 6302 ImplAS = LangAS::opencl_global; 6303 // If the original type from a decayed type is an array type and that array 6304 // type has no address space yet, deduce it now. 6305 if (auto DT = dyn_cast<DecayedType>(Type)) { 6306 auto OrigTy = DT->getOriginalType(); 6307 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) { 6308 // Add the address space to the original array type and then propagate 6309 // that to the element type through `getAsArrayType`. 6310 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS); 6311 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0); 6312 // Re-generate the decayed type. 6313 Type = Context.getDecayedType(OrigTy); 6314 } 6315 } 6316 Type = Context.getAddrSpaceQualType(Type, ImplAS); 6317 // Apply any qualifiers (including address space) from the array type to 6318 // the element type. This implements C99 6.7.3p8: "If the specification of 6319 // an array type includes any type qualifiers, the element type is so 6320 // qualified, not the array type." 6321 if (Type->isArrayType()) 6322 Type = QualType(Context.getAsArrayType(Type), 0); 6323 Decl->setType(Type); 6324 } 6325 } 6326 6327 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 6328 // Ensure that an auto decl is deduced otherwise the checks below might cache 6329 // the wrong linkage. 6330 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 6331 6332 // 'weak' only applies to declarations with external linkage. 6333 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 6334 if (!ND.isExternallyVisible()) { 6335 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 6336 ND.dropAttr<WeakAttr>(); 6337 } 6338 } 6339 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 6340 if (ND.isExternallyVisible()) { 6341 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 6342 ND.dropAttr<WeakRefAttr>(); 6343 ND.dropAttr<AliasAttr>(); 6344 } 6345 } 6346 6347 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 6348 if (VD->hasInit()) { 6349 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 6350 assert(VD->isThisDeclarationADefinition() && 6351 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 6352 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 6353 VD->dropAttr<AliasAttr>(); 6354 } 6355 } 6356 } 6357 6358 // 'selectany' only applies to externally visible variable declarations. 6359 // It does not apply to functions. 6360 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 6361 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 6362 S.Diag(Attr->getLocation(), 6363 diag::err_attribute_selectany_non_extern_data); 6364 ND.dropAttr<SelectAnyAttr>(); 6365 } 6366 } 6367 6368 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 6369 auto *VD = dyn_cast<VarDecl>(&ND); 6370 bool IsAnonymousNS = false; 6371 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6372 if (VD) { 6373 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext()); 6374 while (NS && !IsAnonymousNS) { 6375 IsAnonymousNS = NS->isAnonymousNamespace(); 6376 NS = dyn_cast<NamespaceDecl>(NS->getParent()); 6377 } 6378 } 6379 // dll attributes require external linkage. Static locals may have external 6380 // linkage but still cannot be explicitly imported or exported. 6381 // In Microsoft mode, a variable defined in anonymous namespace must have 6382 // external linkage in order to be exported. 6383 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft; 6384 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) || 6385 (!AnonNSInMicrosoftMode && 6386 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) { 6387 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 6388 << &ND << Attr; 6389 ND.setInvalidDecl(); 6390 } 6391 } 6392 6393 // Virtual functions cannot be marked as 'notail'. 6394 if (auto *Attr = ND.getAttr<NotTailCalledAttr>()) 6395 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND)) 6396 if (MD->isVirtual()) { 6397 S.Diag(ND.getLocation(), 6398 diag::err_invalid_attribute_on_virtual_function) 6399 << Attr; 6400 ND.dropAttr<NotTailCalledAttr>(); 6401 } 6402 6403 // Check the attributes on the function type, if any. 6404 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) { 6405 // Don't declare this variable in the second operand of the for-statement; 6406 // GCC miscompiles that by ending its lifetime before evaluating the 6407 // third operand. See gcc.gnu.org/PR86769. 6408 AttributedTypeLoc ATL; 6409 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc(); 6410 (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); 6411 TL = ATL.getModifiedLoc()) { 6412 // The [[lifetimebound]] attribute can be applied to the implicit object 6413 // parameter of a non-static member function (other than a ctor or dtor) 6414 // by applying it to the function type. 6415 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) { 6416 const auto *MD = dyn_cast<CXXMethodDecl>(FD); 6417 if (!MD || MD->isStatic()) { 6418 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param) 6419 << !MD << A->getRange(); 6420 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) { 6421 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor) 6422 << isa<CXXDestructorDecl>(MD) << A->getRange(); 6423 } 6424 } 6425 } 6426 } 6427 } 6428 6429 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 6430 NamedDecl *NewDecl, 6431 bool IsSpecialization, 6432 bool IsDefinition) { 6433 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl()) 6434 return; 6435 6436 bool IsTemplate = false; 6437 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 6438 OldDecl = OldTD->getTemplatedDecl(); 6439 IsTemplate = true; 6440 if (!IsSpecialization) 6441 IsDefinition = false; 6442 } 6443 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { 6444 NewDecl = NewTD->getTemplatedDecl(); 6445 IsTemplate = true; 6446 } 6447 6448 if (!OldDecl || !NewDecl) 6449 return; 6450 6451 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 6452 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 6453 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 6454 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 6455 6456 // dllimport and dllexport are inheritable attributes so we have to exclude 6457 // inherited attribute instances. 6458 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 6459 (NewExportAttr && !NewExportAttr->isInherited()); 6460 6461 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 6462 // the only exception being explicit specializations. 6463 // Implicitly generated declarations are also excluded for now because there 6464 // is no other way to switch these to use dllimport or dllexport. 6465 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 6466 6467 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 6468 // Allow with a warning for free functions and global variables. 6469 bool JustWarn = false; 6470 if (!OldDecl->isCXXClassMember()) { 6471 auto *VD = dyn_cast<VarDecl>(OldDecl); 6472 if (VD && !VD->getDescribedVarTemplate()) 6473 JustWarn = true; 6474 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 6475 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 6476 JustWarn = true; 6477 } 6478 6479 // We cannot change a declaration that's been used because IR has already 6480 // been emitted. Dllimported functions will still work though (modulo 6481 // address equality) as they can use the thunk. 6482 if (OldDecl->isUsed()) 6483 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 6484 JustWarn = false; 6485 6486 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 6487 : diag::err_attribute_dll_redeclaration; 6488 S.Diag(NewDecl->getLocation(), DiagID) 6489 << NewDecl 6490 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 6491 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6492 if (!JustWarn) { 6493 NewDecl->setInvalidDecl(); 6494 return; 6495 } 6496 } 6497 6498 // A redeclaration is not allowed to drop a dllimport attribute, the only 6499 // exceptions being inline function definitions (except for function 6500 // templates), local extern declarations, qualified friend declarations or 6501 // special MSVC extension: in the last case, the declaration is treated as if 6502 // it were marked dllexport. 6503 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 6504 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6505 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 6506 // Ignore static data because out-of-line definitions are diagnosed 6507 // separately. 6508 IsStaticDataMember = VD->isStaticDataMember(); 6509 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 6510 VarDecl::DeclarationOnly; 6511 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 6512 IsInline = FD->isInlined(); 6513 IsQualifiedFriend = FD->getQualifier() && 6514 FD->getFriendObjectKind() == Decl::FOK_Declared; 6515 } 6516 6517 if (OldImportAttr && !HasNewAttr && 6518 (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember && 6519 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 6520 if (IsMicrosoft && IsDefinition) { 6521 S.Diag(NewDecl->getLocation(), 6522 diag::warn_redeclaration_without_import_attribute) 6523 << NewDecl; 6524 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6525 NewDecl->dropAttr<DLLImportAttr>(); 6526 NewDecl->addAttr( 6527 DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange())); 6528 } else { 6529 S.Diag(NewDecl->getLocation(), 6530 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 6531 << NewDecl << OldImportAttr; 6532 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6533 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 6534 OldDecl->dropAttr<DLLImportAttr>(); 6535 NewDecl->dropAttr<DLLImportAttr>(); 6536 } 6537 } else if (IsInline && OldImportAttr && !IsMicrosoft) { 6538 // In MinGW, seeing a function declared inline drops the dllimport 6539 // attribute. 6540 OldDecl->dropAttr<DLLImportAttr>(); 6541 NewDecl->dropAttr<DLLImportAttr>(); 6542 S.Diag(NewDecl->getLocation(), 6543 diag::warn_dllimport_dropped_from_inline_function) 6544 << NewDecl << OldImportAttr; 6545 } 6546 6547 // A specialization of a class template member function is processed here 6548 // since it's a redeclaration. If the parent class is dllexport, the 6549 // specialization inherits that attribute. This doesn't happen automatically 6550 // since the parent class isn't instantiated until later. 6551 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) { 6552 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && 6553 !NewImportAttr && !NewExportAttr) { 6554 if (const DLLExportAttr *ParentExportAttr = 6555 MD->getParent()->getAttr<DLLExportAttr>()) { 6556 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context); 6557 NewAttr->setInherited(true); 6558 NewDecl->addAttr(NewAttr); 6559 } 6560 } 6561 } 6562 } 6563 6564 /// Given that we are within the definition of the given function, 6565 /// will that definition behave like C99's 'inline', where the 6566 /// definition is discarded except for optimization purposes? 6567 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 6568 // Try to avoid calling GetGVALinkageForFunction. 6569 6570 // All cases of this require the 'inline' keyword. 6571 if (!FD->isInlined()) return false; 6572 6573 // This is only possible in C++ with the gnu_inline attribute. 6574 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 6575 return false; 6576 6577 // Okay, go ahead and call the relatively-more-expensive function. 6578 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 6579 } 6580 6581 /// Determine whether a variable is extern "C" prior to attaching 6582 /// an initializer. We can't just call isExternC() here, because that 6583 /// will also compute and cache whether the declaration is externally 6584 /// visible, which might change when we attach the initializer. 6585 /// 6586 /// This can only be used if the declaration is known to not be a 6587 /// redeclaration of an internal linkage declaration. 6588 /// 6589 /// For instance: 6590 /// 6591 /// auto x = []{}; 6592 /// 6593 /// Attaching the initializer here makes this declaration not externally 6594 /// visible, because its type has internal linkage. 6595 /// 6596 /// FIXME: This is a hack. 6597 template<typename T> 6598 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 6599 if (S.getLangOpts().CPlusPlus) { 6600 // In C++, the overloadable attribute negates the effects of extern "C". 6601 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 6602 return false; 6603 6604 // So do CUDA's host/device attributes. 6605 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 6606 D->template hasAttr<CUDAHostAttr>())) 6607 return false; 6608 } 6609 return D->isExternC(); 6610 } 6611 6612 static bool shouldConsiderLinkage(const VarDecl *VD) { 6613 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 6614 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) || 6615 isa<OMPDeclareMapperDecl>(DC)) 6616 return VD->hasExternalStorage(); 6617 if (DC->isFileContext()) 6618 return true; 6619 if (DC->isRecord()) 6620 return false; 6621 if (isa<RequiresExprBodyDecl>(DC)) 6622 return false; 6623 llvm_unreachable("Unexpected context"); 6624 } 6625 6626 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 6627 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 6628 if (DC->isFileContext() || DC->isFunctionOrMethod() || 6629 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC)) 6630 return true; 6631 if (DC->isRecord()) 6632 return false; 6633 llvm_unreachable("Unexpected context"); 6634 } 6635 6636 static bool hasParsedAttr(Scope *S, const Declarator &PD, 6637 ParsedAttr::Kind Kind) { 6638 // Check decl attributes on the DeclSpec. 6639 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind)) 6640 return true; 6641 6642 // Walk the declarator structure, checking decl attributes that were in a type 6643 // position to the decl itself. 6644 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 6645 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind)) 6646 return true; 6647 } 6648 6649 // Finally, check attributes on the decl itself. 6650 return PD.getAttributes().hasAttribute(Kind); 6651 } 6652 6653 /// Adjust the \c DeclContext for a function or variable that might be a 6654 /// function-local external declaration. 6655 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 6656 if (!DC->isFunctionOrMethod()) 6657 return false; 6658 6659 // If this is a local extern function or variable declared within a function 6660 // template, don't add it into the enclosing namespace scope until it is 6661 // instantiated; it might have a dependent type right now. 6662 if (DC->isDependentContext()) 6663 return true; 6664 6665 // C++11 [basic.link]p7: 6666 // When a block scope declaration of an entity with linkage is not found to 6667 // refer to some other declaration, then that entity is a member of the 6668 // innermost enclosing namespace. 6669 // 6670 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 6671 // semantically-enclosing namespace, not a lexically-enclosing one. 6672 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 6673 DC = DC->getParent(); 6674 return true; 6675 } 6676 6677 /// Returns true if given declaration has external C language linkage. 6678 static bool isDeclExternC(const Decl *D) { 6679 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 6680 return FD->isExternC(); 6681 if (const auto *VD = dyn_cast<VarDecl>(D)) 6682 return VD->isExternC(); 6683 6684 llvm_unreachable("Unknown type of decl!"); 6685 } 6686 /// Returns true if there hasn't been any invalid type diagnosed. 6687 static bool diagnoseOpenCLTypes(Scope *S, Sema &Se, Declarator &D, 6688 DeclContext *DC, QualType R) { 6689 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 6690 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 6691 // argument. 6692 if (R->isImageType() || R->isPipeType()) { 6693 Se.Diag(D.getIdentifierLoc(), 6694 diag::err_opencl_type_can_only_be_used_as_function_parameter) 6695 << R; 6696 D.setInvalidType(); 6697 return false; 6698 } 6699 6700 // OpenCL v1.2 s6.9.r: 6701 // The event type cannot be used to declare a program scope variable. 6702 // OpenCL v2.0 s6.9.q: 6703 // The clk_event_t and reserve_id_t types cannot be declared in program 6704 // scope. 6705 if (NULL == S->getParent()) { 6706 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 6707 Se.Diag(D.getIdentifierLoc(), 6708 diag::err_invalid_type_for_program_scope_var) 6709 << R; 6710 D.setInvalidType(); 6711 return false; 6712 } 6713 } 6714 6715 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 6716 QualType NR = R; 6717 while (NR->isPointerType()) { 6718 if (NR->isFunctionPointerType()) { 6719 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer); 6720 D.setInvalidType(); 6721 return false; 6722 } 6723 NR = NR->getPointeeType(); 6724 } 6725 6726 if (!Se.getOpenCLOptions().isEnabled("cl_khr_fp16")) { 6727 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 6728 // half array type (unless the cl_khr_fp16 extension is enabled). 6729 if (Se.Context.getBaseElementType(R)->isHalfType()) { 6730 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 6731 D.setInvalidType(); 6732 return false; 6733 } 6734 } 6735 6736 // OpenCL v1.2 s6.9.r: 6737 // The event type cannot be used with the __local, __constant and __global 6738 // address space qualifiers. 6739 if (R->isEventT()) { 6740 if (R.getAddressSpace() != LangAS::opencl_private) { 6741 Se.Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual); 6742 D.setInvalidType(); 6743 return false; 6744 } 6745 } 6746 6747 // C++ for OpenCL does not allow the thread_local storage qualifier. 6748 // OpenCL C does not support thread_local either, and 6749 // also reject all other thread storage class specifiers. 6750 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec(); 6751 if (TSC != TSCS_unspecified) { 6752 bool IsCXX = Se.getLangOpts().OpenCLCPlusPlus; 6753 Se.Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6754 diag::err_opencl_unknown_type_specifier) 6755 << IsCXX << Se.getLangOpts().getOpenCLVersionTuple().getAsString() 6756 << DeclSpec::getSpecifierName(TSC) << 1; 6757 D.setInvalidType(); 6758 return false; 6759 } 6760 6761 if (R->isSamplerT()) { 6762 // OpenCL v1.2 s6.9.b p4: 6763 // The sampler type cannot be used with the __local and __global address 6764 // space qualifiers. 6765 if (R.getAddressSpace() == LangAS::opencl_local || 6766 R.getAddressSpace() == LangAS::opencl_global) { 6767 Se.Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 6768 D.setInvalidType(); 6769 } 6770 6771 // OpenCL v1.2 s6.12.14.1: 6772 // A global sampler must be declared with either the constant address 6773 // space qualifier or with the const qualifier. 6774 if (DC->isTranslationUnit() && 6775 !(R.getAddressSpace() == LangAS::opencl_constant || 6776 R.isConstQualified())) { 6777 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler); 6778 D.setInvalidType(); 6779 } 6780 if (D.isInvalidType()) 6781 return false; 6782 } 6783 return true; 6784 } 6785 6786 NamedDecl *Sema::ActOnVariableDeclarator( 6787 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 6788 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 6789 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 6790 QualType R = TInfo->getType(); 6791 DeclarationName Name = GetNameForDeclarator(D).getName(); 6792 6793 IdentifierInfo *II = Name.getAsIdentifierInfo(); 6794 6795 if (D.isDecompositionDeclarator()) { 6796 // Take the name of the first declarator as our name for diagnostic 6797 // purposes. 6798 auto &Decomp = D.getDecompositionDeclarator(); 6799 if (!Decomp.bindings().empty()) { 6800 II = Decomp.bindings()[0].Name; 6801 Name = II; 6802 } 6803 } else if (!II) { 6804 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; 6805 return nullptr; 6806 } 6807 6808 6809 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 6810 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 6811 6812 // dllimport globals without explicit storage class are treated as extern. We 6813 // have to change the storage class this early to get the right DeclContext. 6814 if (SC == SC_None && !DC->isRecord() && 6815 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) && 6816 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport)) 6817 SC = SC_Extern; 6818 6819 DeclContext *OriginalDC = DC; 6820 bool IsLocalExternDecl = SC == SC_Extern && 6821 adjustContextForLocalExternDecl(DC); 6822 6823 if (SCSpec == DeclSpec::SCS_mutable) { 6824 // mutable can only appear on non-static class members, so it's always 6825 // an error here 6826 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 6827 D.setInvalidType(); 6828 SC = SC_None; 6829 } 6830 6831 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 6832 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 6833 D.getDeclSpec().getStorageClassSpecLoc())) { 6834 // In C++11, the 'register' storage class specifier is deprecated. 6835 // Suppress the warning in system macros, it's used in macros in some 6836 // popular C system headers, such as in glibc's htonl() macro. 6837 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6838 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 6839 : diag::warn_deprecated_register) 6840 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6841 } 6842 6843 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6844 6845 if (!DC->isRecord() && S->getFnParent() == nullptr) { 6846 // C99 6.9p2: The storage-class specifiers auto and register shall not 6847 // appear in the declaration specifiers in an external declaration. 6848 // Global Register+Asm is a GNU extension we support. 6849 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 6850 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 6851 D.setInvalidType(); 6852 } 6853 } 6854 6855 bool IsMemberSpecialization = false; 6856 bool IsVariableTemplateSpecialization = false; 6857 bool IsPartialSpecialization = false; 6858 bool IsVariableTemplate = false; 6859 VarDecl *NewVD = nullptr; 6860 VarTemplateDecl *NewTemplate = nullptr; 6861 TemplateParameterList *TemplateParams = nullptr; 6862 if (!getLangOpts().CPlusPlus) { 6863 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), 6864 II, R, TInfo, SC); 6865 6866 if (R->getContainedDeducedType()) 6867 ParsingInitForAutoVars.insert(NewVD); 6868 6869 if (D.isInvalidType()) 6870 NewVD->setInvalidDecl(); 6871 6872 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() && 6873 NewVD->hasLocalStorage()) 6874 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(), 6875 NTCUC_AutoVar, NTCUK_Destruct); 6876 } else { 6877 bool Invalid = false; 6878 6879 if (DC->isRecord() && !CurContext->isRecord()) { 6880 // This is an out-of-line definition of a static data member. 6881 switch (SC) { 6882 case SC_None: 6883 break; 6884 case SC_Static: 6885 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6886 diag::err_static_out_of_line) 6887 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6888 break; 6889 case SC_Auto: 6890 case SC_Register: 6891 case SC_Extern: 6892 // [dcl.stc] p2: The auto or register specifiers shall be applied only 6893 // to names of variables declared in a block or to function parameters. 6894 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 6895 // of class members 6896 6897 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6898 diag::err_storage_class_for_static_member) 6899 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6900 break; 6901 case SC_PrivateExtern: 6902 llvm_unreachable("C storage class in c++!"); 6903 } 6904 } 6905 6906 if (SC == SC_Static && CurContext->isRecord()) { 6907 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 6908 // Walk up the enclosing DeclContexts to check for any that are 6909 // incompatible with static data members. 6910 const DeclContext *FunctionOrMethod = nullptr; 6911 const CXXRecordDecl *AnonStruct = nullptr; 6912 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) { 6913 if (Ctxt->isFunctionOrMethod()) { 6914 FunctionOrMethod = Ctxt; 6915 break; 6916 } 6917 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt); 6918 if (ParentDecl && !ParentDecl->getDeclName()) { 6919 AnonStruct = ParentDecl; 6920 break; 6921 } 6922 } 6923 if (FunctionOrMethod) { 6924 // C++ [class.static.data]p5: A local class shall not have static data 6925 // members. 6926 Diag(D.getIdentifierLoc(), 6927 diag::err_static_data_member_not_allowed_in_local_class) 6928 << Name << RD->getDeclName() << RD->getTagKind(); 6929 } else if (AnonStruct) { 6930 // C++ [class.static.data]p4: Unnamed classes and classes contained 6931 // directly or indirectly within unnamed classes shall not contain 6932 // static data members. 6933 Diag(D.getIdentifierLoc(), 6934 diag::err_static_data_member_not_allowed_in_anon_struct) 6935 << Name << AnonStruct->getTagKind(); 6936 Invalid = true; 6937 } else if (RD->isUnion()) { 6938 // C++98 [class.union]p1: If a union contains a static data member, 6939 // the program is ill-formed. C++11 drops this restriction. 6940 Diag(D.getIdentifierLoc(), 6941 getLangOpts().CPlusPlus11 6942 ? diag::warn_cxx98_compat_static_data_member_in_union 6943 : diag::ext_static_data_member_in_union) << Name; 6944 } 6945 } 6946 } 6947 6948 // Match up the template parameter lists with the scope specifier, then 6949 // determine whether we have a template or a template specialization. 6950 bool InvalidScope = false; 6951 TemplateParams = MatchTemplateParametersToScopeSpecifier( 6952 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 6953 D.getCXXScopeSpec(), 6954 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 6955 ? D.getName().TemplateId 6956 : nullptr, 6957 TemplateParamLists, 6958 /*never a friend*/ false, IsMemberSpecialization, InvalidScope); 6959 Invalid |= InvalidScope; 6960 6961 if (TemplateParams) { 6962 if (!TemplateParams->size() && 6963 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 6964 // There is an extraneous 'template<>' for this variable. Complain 6965 // about it, but allow the declaration of the variable. 6966 Diag(TemplateParams->getTemplateLoc(), 6967 diag::err_template_variable_noparams) 6968 << II 6969 << SourceRange(TemplateParams->getTemplateLoc(), 6970 TemplateParams->getRAngleLoc()); 6971 TemplateParams = nullptr; 6972 } else { 6973 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 6974 // This is an explicit specialization or a partial specialization. 6975 // FIXME: Check that we can declare a specialization here. 6976 IsVariableTemplateSpecialization = true; 6977 IsPartialSpecialization = TemplateParams->size() > 0; 6978 } else { // if (TemplateParams->size() > 0) 6979 // This is a template declaration. 6980 IsVariableTemplate = true; 6981 6982 // Check that we can declare a template here. 6983 if (CheckTemplateDeclScope(S, TemplateParams)) 6984 return nullptr; 6985 6986 // Only C++1y supports variable templates (N3651). 6987 Diag(D.getIdentifierLoc(), 6988 getLangOpts().CPlusPlus14 6989 ? diag::warn_cxx11_compat_variable_template 6990 : diag::ext_variable_template); 6991 } 6992 } 6993 } else { 6994 assert((Invalid || 6995 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && 6996 "should have a 'template<>' for this decl"); 6997 } 6998 6999 if (IsVariableTemplateSpecialization) { 7000 SourceLocation TemplateKWLoc = 7001 TemplateParamLists.size() > 0 7002 ? TemplateParamLists[0]->getTemplateLoc() 7003 : SourceLocation(); 7004 DeclResult Res = ActOnVarTemplateSpecialization( 7005 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 7006 IsPartialSpecialization); 7007 if (Res.isInvalid()) 7008 return nullptr; 7009 NewVD = cast<VarDecl>(Res.get()); 7010 AddToScope = false; 7011 } else if (D.isDecompositionDeclarator()) { 7012 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(), 7013 D.getIdentifierLoc(), R, TInfo, SC, 7014 Bindings); 7015 } else 7016 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), 7017 D.getIdentifierLoc(), II, R, TInfo, SC); 7018 7019 // If this is supposed to be a variable template, create it as such. 7020 if (IsVariableTemplate) { 7021 NewTemplate = 7022 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 7023 TemplateParams, NewVD); 7024 NewVD->setDescribedVarTemplate(NewTemplate); 7025 } 7026 7027 // If this decl has an auto type in need of deduction, make a note of the 7028 // Decl so we can diagnose uses of it in its own initializer. 7029 if (R->getContainedDeducedType()) 7030 ParsingInitForAutoVars.insert(NewVD); 7031 7032 if (D.isInvalidType() || Invalid) { 7033 NewVD->setInvalidDecl(); 7034 if (NewTemplate) 7035 NewTemplate->setInvalidDecl(); 7036 } 7037 7038 SetNestedNameSpecifier(*this, NewVD, D); 7039 7040 // If we have any template parameter lists that don't directly belong to 7041 // the variable (matching the scope specifier), store them. 7042 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 7043 if (TemplateParamLists.size() > VDTemplateParamLists) 7044 NewVD->setTemplateParameterListsInfo( 7045 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 7046 } 7047 7048 if (D.getDeclSpec().isInlineSpecified()) { 7049 if (!getLangOpts().CPlusPlus) { 7050 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 7051 << 0; 7052 } else if (CurContext->isFunctionOrMethod()) { 7053 // 'inline' is not allowed on block scope variable declaration. 7054 Diag(D.getDeclSpec().getInlineSpecLoc(), 7055 diag::err_inline_declaration_block_scope) << Name 7056 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 7057 } else { 7058 Diag(D.getDeclSpec().getInlineSpecLoc(), 7059 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable 7060 : diag::ext_inline_variable); 7061 NewVD->setInlineSpecified(); 7062 } 7063 } 7064 7065 // Set the lexical context. If the declarator has a C++ scope specifier, the 7066 // lexical context will be different from the semantic context. 7067 NewVD->setLexicalDeclContext(CurContext); 7068 if (NewTemplate) 7069 NewTemplate->setLexicalDeclContext(CurContext); 7070 7071 if (IsLocalExternDecl) { 7072 if (D.isDecompositionDeclarator()) 7073 for (auto *B : Bindings) 7074 B->setLocalExternDecl(); 7075 else 7076 NewVD->setLocalExternDecl(); 7077 } 7078 7079 bool EmitTLSUnsupportedError = false; 7080 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 7081 // C++11 [dcl.stc]p4: 7082 // When thread_local is applied to a variable of block scope the 7083 // storage-class-specifier static is implied if it does not appear 7084 // explicitly. 7085 // Core issue: 'static' is not implied if the variable is declared 7086 // 'extern'. 7087 if (NewVD->hasLocalStorage() && 7088 (SCSpec != DeclSpec::SCS_unspecified || 7089 TSCS != DeclSpec::TSCS_thread_local || 7090 !DC->isFunctionOrMethod())) 7091 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7092 diag::err_thread_non_global) 7093 << DeclSpec::getSpecifierName(TSCS); 7094 else if (!Context.getTargetInfo().isTLSSupported()) { 7095 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || 7096 getLangOpts().SYCLIsDevice) { 7097 // Postpone error emission until we've collected attributes required to 7098 // figure out whether it's a host or device variable and whether the 7099 // error should be ignored. 7100 EmitTLSUnsupportedError = true; 7101 // We still need to mark the variable as TLS so it shows up in AST with 7102 // proper storage class for other tools to use even if we're not going 7103 // to emit any code for it. 7104 NewVD->setTSCSpec(TSCS); 7105 } else 7106 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7107 diag::err_thread_unsupported); 7108 } else 7109 NewVD->setTSCSpec(TSCS); 7110 } 7111 7112 switch (D.getDeclSpec().getConstexprSpecifier()) { 7113 case CSK_unspecified: 7114 break; 7115 7116 case CSK_consteval: 7117 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7118 diag::err_constexpr_wrong_decl_kind) 7119 << D.getDeclSpec().getConstexprSpecifier(); 7120 LLVM_FALLTHROUGH; 7121 7122 case CSK_constexpr: 7123 NewVD->setConstexpr(true); 7124 MaybeAddCUDAConstantAttr(NewVD); 7125 // C++1z [dcl.spec.constexpr]p1: 7126 // A static data member declared with the constexpr specifier is 7127 // implicitly an inline variable. 7128 if (NewVD->isStaticDataMember() && 7129 (getLangOpts().CPlusPlus17 || 7130 Context.getTargetInfo().getCXXABI().isMicrosoft())) 7131 NewVD->setImplicitlyInline(); 7132 break; 7133 7134 case CSK_constinit: 7135 if (!NewVD->hasGlobalStorage()) 7136 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7137 diag::err_constinit_local_variable); 7138 else 7139 NewVD->addAttr(ConstInitAttr::Create( 7140 Context, D.getDeclSpec().getConstexprSpecLoc(), 7141 AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit)); 7142 break; 7143 } 7144 7145 // C99 6.7.4p3 7146 // An inline definition of a function with external linkage shall 7147 // not contain a definition of a modifiable object with static or 7148 // thread storage duration... 7149 // We only apply this when the function is required to be defined 7150 // elsewhere, i.e. when the function is not 'extern inline'. Note 7151 // that a local variable with thread storage duration still has to 7152 // be marked 'static'. Also note that it's possible to get these 7153 // semantics in C++ using __attribute__((gnu_inline)). 7154 if (SC == SC_Static && S->getFnParent() != nullptr && 7155 !NewVD->getType().isConstQualified()) { 7156 FunctionDecl *CurFD = getCurFunctionDecl(); 7157 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 7158 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7159 diag::warn_static_local_in_extern_inline); 7160 MaybeSuggestAddingStaticToDecl(CurFD); 7161 } 7162 } 7163 7164 if (D.getDeclSpec().isModulePrivateSpecified()) { 7165 if (IsVariableTemplateSpecialization) 7166 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7167 << (IsPartialSpecialization ? 1 : 0) 7168 << FixItHint::CreateRemoval( 7169 D.getDeclSpec().getModulePrivateSpecLoc()); 7170 else if (IsMemberSpecialization) 7171 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7172 << 2 7173 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 7174 else if (NewVD->hasLocalStorage()) 7175 Diag(NewVD->getLocation(), diag::err_module_private_local) 7176 << 0 << NewVD->getDeclName() 7177 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 7178 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 7179 else { 7180 NewVD->setModulePrivate(); 7181 if (NewTemplate) 7182 NewTemplate->setModulePrivate(); 7183 for (auto *B : Bindings) 7184 B->setModulePrivate(); 7185 } 7186 } 7187 7188 if (getLangOpts().OpenCL) { 7189 7190 deduceOpenCLAddressSpace(NewVD); 7191 7192 diagnoseOpenCLTypes(S, *this, D, DC, NewVD->getType()); 7193 } 7194 7195 // Handle attributes prior to checking for duplicates in MergeVarDecl 7196 ProcessDeclAttributes(S, NewVD, D); 7197 7198 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || 7199 getLangOpts().SYCLIsDevice) { 7200 if (EmitTLSUnsupportedError && 7201 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || 7202 (getLangOpts().OpenMPIsDevice && 7203 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD)))) 7204 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7205 diag::err_thread_unsupported); 7206 7207 if (EmitTLSUnsupportedError && 7208 (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice))) 7209 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported); 7210 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 7211 // storage [duration]." 7212 if (SC == SC_None && S->getFnParent() != nullptr && 7213 (NewVD->hasAttr<CUDASharedAttr>() || 7214 NewVD->hasAttr<CUDAConstantAttr>())) { 7215 NewVD->setStorageClass(SC_Static); 7216 } 7217 } 7218 7219 // Ensure that dllimport globals without explicit storage class are treated as 7220 // extern. The storage class is set above using parsed attributes. Now we can 7221 // check the VarDecl itself. 7222 assert(!NewVD->hasAttr<DLLImportAttr>() || 7223 NewVD->getAttr<DLLImportAttr>()->isInherited() || 7224 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 7225 7226 // In auto-retain/release, infer strong retension for variables of 7227 // retainable type. 7228 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 7229 NewVD->setInvalidDecl(); 7230 7231 // Handle GNU asm-label extension (encoded as an attribute). 7232 if (Expr *E = (Expr*)D.getAsmLabel()) { 7233 // The parser guarantees this is a string. 7234 StringLiteral *SE = cast<StringLiteral>(E); 7235 StringRef Label = SE->getString(); 7236 if (S->getFnParent() != nullptr) { 7237 switch (SC) { 7238 case SC_None: 7239 case SC_Auto: 7240 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 7241 break; 7242 case SC_Register: 7243 // Local Named register 7244 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 7245 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 7246 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7247 break; 7248 case SC_Static: 7249 case SC_Extern: 7250 case SC_PrivateExtern: 7251 break; 7252 } 7253 } else if (SC == SC_Register) { 7254 // Global Named register 7255 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 7256 const auto &TI = Context.getTargetInfo(); 7257 bool HasSizeMismatch; 7258 7259 if (!TI.isValidGCCRegisterName(Label)) 7260 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7261 else if (!TI.validateGlobalRegisterVariable(Label, 7262 Context.getTypeSize(R), 7263 HasSizeMismatch)) 7264 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 7265 else if (HasSizeMismatch) 7266 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 7267 } 7268 7269 if (!R->isIntegralType(Context) && !R->isPointerType()) { 7270 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type); 7271 NewVD->setInvalidDecl(true); 7272 } 7273 } 7274 7275 NewVD->addAttr(AsmLabelAttr::Create(Context, Label, 7276 /*IsLiteralLabel=*/true, 7277 SE->getStrTokenLoc(0))); 7278 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 7279 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 7280 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 7281 if (I != ExtnameUndeclaredIdentifiers.end()) { 7282 if (isDeclExternC(NewVD)) { 7283 NewVD->addAttr(I->second); 7284 ExtnameUndeclaredIdentifiers.erase(I); 7285 } else 7286 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 7287 << /*Variable*/1 << NewVD; 7288 } 7289 } 7290 7291 // Find the shadowed declaration before filtering for scope. 7292 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 7293 ? getShadowedDeclaration(NewVD, Previous) 7294 : nullptr; 7295 7296 // Don't consider existing declarations that are in a different 7297 // scope and are out-of-semantic-context declarations (if the new 7298 // declaration has linkage). 7299 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 7300 D.getCXXScopeSpec().isNotEmpty() || 7301 IsMemberSpecialization || 7302 IsVariableTemplateSpecialization); 7303 7304 // Check whether the previous declaration is in the same block scope. This 7305 // affects whether we merge types with it, per C++11 [dcl.array]p3. 7306 if (getLangOpts().CPlusPlus && 7307 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 7308 NewVD->setPreviousDeclInSameBlockScope( 7309 Previous.isSingleResult() && !Previous.isShadowed() && 7310 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 7311 7312 if (!getLangOpts().CPlusPlus) { 7313 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7314 } else { 7315 // If this is an explicit specialization of a static data member, check it. 7316 if (IsMemberSpecialization && !NewVD->isInvalidDecl() && 7317 CheckMemberSpecialization(NewVD, Previous)) 7318 NewVD->setInvalidDecl(); 7319 7320 // Merge the decl with the existing one if appropriate. 7321 if (!Previous.empty()) { 7322 if (Previous.isSingleResult() && 7323 isa<FieldDecl>(Previous.getFoundDecl()) && 7324 D.getCXXScopeSpec().isSet()) { 7325 // The user tried to define a non-static data member 7326 // out-of-line (C++ [dcl.meaning]p1). 7327 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 7328 << D.getCXXScopeSpec().getRange(); 7329 Previous.clear(); 7330 NewVD->setInvalidDecl(); 7331 } 7332 } else if (D.getCXXScopeSpec().isSet()) { 7333 // No previous declaration in the qualifying scope. 7334 Diag(D.getIdentifierLoc(), diag::err_no_member) 7335 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 7336 << D.getCXXScopeSpec().getRange(); 7337 NewVD->setInvalidDecl(); 7338 } 7339 7340 if (!IsVariableTemplateSpecialization) 7341 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7342 7343 if (NewTemplate) { 7344 VarTemplateDecl *PrevVarTemplate = 7345 NewVD->getPreviousDecl() 7346 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 7347 : nullptr; 7348 7349 // Check the template parameter list of this declaration, possibly 7350 // merging in the template parameter list from the previous variable 7351 // template declaration. 7352 if (CheckTemplateParameterList( 7353 TemplateParams, 7354 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 7355 : nullptr, 7356 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 7357 DC->isDependentContext()) 7358 ? TPC_ClassTemplateMember 7359 : TPC_VarTemplate)) 7360 NewVD->setInvalidDecl(); 7361 7362 // If we are providing an explicit specialization of a static variable 7363 // template, make a note of that. 7364 if (PrevVarTemplate && 7365 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 7366 PrevVarTemplate->setMemberSpecialization(); 7367 } 7368 } 7369 7370 // Diagnose shadowed variables iff this isn't a redeclaration. 7371 if (ShadowedDecl && !D.isRedeclaration()) 7372 CheckShadow(NewVD, ShadowedDecl, Previous); 7373 7374 ProcessPragmaWeak(S, NewVD); 7375 7376 // If this is the first declaration of an extern C variable, update 7377 // the map of such variables. 7378 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 7379 isIncompleteDeclExternC(*this, NewVD)) 7380 RegisterLocallyScopedExternCDecl(NewVD, S); 7381 7382 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 7383 MangleNumberingContext *MCtx; 7384 Decl *ManglingContextDecl; 7385 std::tie(MCtx, ManglingContextDecl) = 7386 getCurrentMangleNumberContext(NewVD->getDeclContext()); 7387 if (MCtx) { 7388 Context.setManglingNumber( 7389 NewVD, MCtx->getManglingNumber( 7390 NewVD, getMSManglingNumber(getLangOpts(), S))); 7391 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 7392 } 7393 } 7394 7395 // Special handling of variable named 'main'. 7396 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 7397 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 7398 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 7399 7400 // C++ [basic.start.main]p3 7401 // A program that declares a variable main at global scope is ill-formed. 7402 if (getLangOpts().CPlusPlus) 7403 Diag(D.getBeginLoc(), diag::err_main_global_variable); 7404 7405 // In C, and external-linkage variable named main results in undefined 7406 // behavior. 7407 else if (NewVD->hasExternalFormalLinkage()) 7408 Diag(D.getBeginLoc(), diag::warn_main_redefined); 7409 } 7410 7411 if (D.isRedeclaration() && !Previous.empty()) { 7412 NamedDecl *Prev = Previous.getRepresentativeDecl(); 7413 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization, 7414 D.isFunctionDefinition()); 7415 } 7416 7417 if (NewTemplate) { 7418 if (NewVD->isInvalidDecl()) 7419 NewTemplate->setInvalidDecl(); 7420 ActOnDocumentableDecl(NewTemplate); 7421 return NewTemplate; 7422 } 7423 7424 if (IsMemberSpecialization && !NewVD->isInvalidDecl()) 7425 CompleteMemberSpecialization(NewVD, Previous); 7426 7427 return NewVD; 7428 } 7429 7430 /// Enum describing the %select options in diag::warn_decl_shadow. 7431 enum ShadowedDeclKind { 7432 SDK_Local, 7433 SDK_Global, 7434 SDK_StaticMember, 7435 SDK_Field, 7436 SDK_Typedef, 7437 SDK_Using 7438 }; 7439 7440 /// Determine what kind of declaration we're shadowing. 7441 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 7442 const DeclContext *OldDC) { 7443 if (isa<TypeAliasDecl>(ShadowedDecl)) 7444 return SDK_Using; 7445 else if (isa<TypedefDecl>(ShadowedDecl)) 7446 return SDK_Typedef; 7447 else if (isa<RecordDecl>(OldDC)) 7448 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 7449 7450 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 7451 } 7452 7453 /// Return the location of the capture if the given lambda captures the given 7454 /// variable \p VD, or an invalid source location otherwise. 7455 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 7456 const VarDecl *VD) { 7457 for (const Capture &Capture : LSI->Captures) { 7458 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 7459 return Capture.getLocation(); 7460 } 7461 return SourceLocation(); 7462 } 7463 7464 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, 7465 const LookupResult &R) { 7466 // Only diagnose if we're shadowing an unambiguous field or variable. 7467 if (R.getResultKind() != LookupResult::Found) 7468 return false; 7469 7470 // Return false if warning is ignored. 7471 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); 7472 } 7473 7474 /// Return the declaration shadowed by the given variable \p D, or null 7475 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7476 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 7477 const LookupResult &R) { 7478 if (!shouldWarnIfShadowedDecl(Diags, R)) 7479 return nullptr; 7480 7481 // Don't diagnose declarations at file scope. 7482 if (D->hasGlobalStorage()) 7483 return nullptr; 7484 7485 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7486 return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl) 7487 ? ShadowedDecl 7488 : nullptr; 7489 } 7490 7491 /// Return the declaration shadowed by the given typedef \p D, or null 7492 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7493 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, 7494 const LookupResult &R) { 7495 // Don't warn if typedef declaration is part of a class 7496 if (D->getDeclContext()->isRecord()) 7497 return nullptr; 7498 7499 if (!shouldWarnIfShadowedDecl(Diags, R)) 7500 return nullptr; 7501 7502 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7503 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; 7504 } 7505 7506 /// Diagnose variable or built-in function shadowing. Implements 7507 /// -Wshadow. 7508 /// 7509 /// This method is called whenever a VarDecl is added to a "useful" 7510 /// scope. 7511 /// 7512 /// \param ShadowedDecl the declaration that is shadowed by the given variable 7513 /// \param R the lookup of the name 7514 /// 7515 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 7516 const LookupResult &R) { 7517 DeclContext *NewDC = D->getDeclContext(); 7518 7519 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 7520 // Fields are not shadowed by variables in C++ static methods. 7521 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 7522 if (MD->isStatic()) 7523 return; 7524 7525 // Fields shadowed by constructor parameters are a special case. Usually 7526 // the constructor initializes the field with the parameter. 7527 if (isa<CXXConstructorDecl>(NewDC)) 7528 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { 7529 // Remember that this was shadowed so we can either warn about its 7530 // modification or its existence depending on warning settings. 7531 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); 7532 return; 7533 } 7534 } 7535 7536 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 7537 if (shadowedVar->isExternC()) { 7538 // For shadowing external vars, make sure that we point to the global 7539 // declaration, not a locally scoped extern declaration. 7540 for (auto I : shadowedVar->redecls()) 7541 if (I->isFileVarDecl()) { 7542 ShadowedDecl = I; 7543 break; 7544 } 7545 } 7546 7547 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); 7548 7549 unsigned WarningDiag = diag::warn_decl_shadow; 7550 SourceLocation CaptureLoc; 7551 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && 7552 isa<CXXMethodDecl>(NewDC)) { 7553 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 7554 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 7555 if (RD->getLambdaCaptureDefault() == LCD_None) { 7556 // Try to avoid warnings for lambdas with an explicit capture list. 7557 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 7558 // Warn only when the lambda captures the shadowed decl explicitly. 7559 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 7560 if (CaptureLoc.isInvalid()) 7561 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 7562 } else { 7563 // Remember that this was shadowed so we can avoid the warning if the 7564 // shadowed decl isn't captured and the warning settings allow it. 7565 cast<LambdaScopeInfo>(getCurFunction()) 7566 ->ShadowingDecls.push_back( 7567 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); 7568 return; 7569 } 7570 } 7571 7572 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { 7573 // A variable can't shadow a local variable in an enclosing scope, if 7574 // they are separated by a non-capturing declaration context. 7575 for (DeclContext *ParentDC = NewDC; 7576 ParentDC && !ParentDC->Equals(OldDC); 7577 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { 7578 // Only block literals, captured statements, and lambda expressions 7579 // can capture; other scopes don't. 7580 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && 7581 !isLambdaCallOperator(ParentDC)) { 7582 return; 7583 } 7584 } 7585 } 7586 } 7587 } 7588 7589 // Only warn about certain kinds of shadowing for class members. 7590 if (NewDC && NewDC->isRecord()) { 7591 // In particular, don't warn about shadowing non-class members. 7592 if (!OldDC->isRecord()) 7593 return; 7594 7595 // TODO: should we warn about static data members shadowing 7596 // static data members from base classes? 7597 7598 // TODO: don't diagnose for inaccessible shadowed members. 7599 // This is hard to do perfectly because we might friend the 7600 // shadowing context, but that's just a false negative. 7601 } 7602 7603 7604 DeclarationName Name = R.getLookupName(); 7605 7606 // Emit warning and note. 7607 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 7608 return; 7609 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 7610 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 7611 if (!CaptureLoc.isInvalid()) 7612 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7613 << Name << /*explicitly*/ 1; 7614 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7615 } 7616 7617 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 7618 /// when these variables are captured by the lambda. 7619 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 7620 for (const auto &Shadow : LSI->ShadowingDecls) { 7621 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 7622 // Try to avoid the warning when the shadowed decl isn't captured. 7623 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 7624 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7625 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 7626 ? diag::warn_decl_shadow_uncaptured_local 7627 : diag::warn_decl_shadow) 7628 << Shadow.VD->getDeclName() 7629 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 7630 if (!CaptureLoc.isInvalid()) 7631 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7632 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 7633 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7634 } 7635 } 7636 7637 /// Check -Wshadow without the advantage of a previous lookup. 7638 void Sema::CheckShadow(Scope *S, VarDecl *D) { 7639 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 7640 return; 7641 7642 LookupResult R(*this, D->getDeclName(), D->getLocation(), 7643 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); 7644 LookupName(R, S); 7645 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 7646 CheckShadow(D, ShadowedDecl, R); 7647 } 7648 7649 /// Check if 'E', which is an expression that is about to be modified, refers 7650 /// to a constructor parameter that shadows a field. 7651 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 7652 // Quickly ignore expressions that can't be shadowing ctor parameters. 7653 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 7654 return; 7655 E = E->IgnoreParenImpCasts(); 7656 auto *DRE = dyn_cast<DeclRefExpr>(E); 7657 if (!DRE) 7658 return; 7659 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 7660 auto I = ShadowingDecls.find(D); 7661 if (I == ShadowingDecls.end()) 7662 return; 7663 const NamedDecl *ShadowedDecl = I->second; 7664 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7665 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 7666 Diag(D->getLocation(), diag::note_var_declared_here) << D; 7667 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7668 7669 // Avoid issuing multiple warnings about the same decl. 7670 ShadowingDecls.erase(I); 7671 } 7672 7673 /// Check for conflict between this global or extern "C" declaration and 7674 /// previous global or extern "C" declarations. This is only used in C++. 7675 template<typename T> 7676 static bool checkGlobalOrExternCConflict( 7677 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 7678 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 7679 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 7680 7681 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 7682 // The common case: this global doesn't conflict with any extern "C" 7683 // declaration. 7684 return false; 7685 } 7686 7687 if (Prev) { 7688 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 7689 // Both the old and new declarations have C language linkage. This is a 7690 // redeclaration. 7691 Previous.clear(); 7692 Previous.addDecl(Prev); 7693 return true; 7694 } 7695 7696 // This is a global, non-extern "C" declaration, and there is a previous 7697 // non-global extern "C" declaration. Diagnose if this is a variable 7698 // declaration. 7699 if (!isa<VarDecl>(ND)) 7700 return false; 7701 } else { 7702 // The declaration is extern "C". Check for any declaration in the 7703 // translation unit which might conflict. 7704 if (IsGlobal) { 7705 // We have already performed the lookup into the translation unit. 7706 IsGlobal = false; 7707 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7708 I != E; ++I) { 7709 if (isa<VarDecl>(*I)) { 7710 Prev = *I; 7711 break; 7712 } 7713 } 7714 } else { 7715 DeclContext::lookup_result R = 7716 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 7717 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 7718 I != E; ++I) { 7719 if (isa<VarDecl>(*I)) { 7720 Prev = *I; 7721 break; 7722 } 7723 // FIXME: If we have any other entity with this name in global scope, 7724 // the declaration is ill-formed, but that is a defect: it breaks the 7725 // 'stat' hack, for instance. Only variables can have mangled name 7726 // clashes with extern "C" declarations, so only they deserve a 7727 // diagnostic. 7728 } 7729 } 7730 7731 if (!Prev) 7732 return false; 7733 } 7734 7735 // Use the first declaration's location to ensure we point at something which 7736 // is lexically inside an extern "C" linkage-spec. 7737 assert(Prev && "should have found a previous declaration to diagnose"); 7738 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 7739 Prev = FD->getFirstDecl(); 7740 else 7741 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 7742 7743 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 7744 << IsGlobal << ND; 7745 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 7746 << IsGlobal; 7747 return false; 7748 } 7749 7750 /// Apply special rules for handling extern "C" declarations. Returns \c true 7751 /// if we have found that this is a redeclaration of some prior entity. 7752 /// 7753 /// Per C++ [dcl.link]p6: 7754 /// Two declarations [for a function or variable] with C language linkage 7755 /// with the same name that appear in different scopes refer to the same 7756 /// [entity]. An entity with C language linkage shall not be declared with 7757 /// the same name as an entity in global scope. 7758 template<typename T> 7759 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 7760 LookupResult &Previous) { 7761 if (!S.getLangOpts().CPlusPlus) { 7762 // In C, when declaring a global variable, look for a corresponding 'extern' 7763 // variable declared in function scope. We don't need this in C++, because 7764 // we find local extern decls in the surrounding file-scope DeclContext. 7765 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7766 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 7767 Previous.clear(); 7768 Previous.addDecl(Prev); 7769 return true; 7770 } 7771 } 7772 return false; 7773 } 7774 7775 // A declaration in the translation unit can conflict with an extern "C" 7776 // declaration. 7777 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 7778 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 7779 7780 // An extern "C" declaration can conflict with a declaration in the 7781 // translation unit or can be a redeclaration of an extern "C" declaration 7782 // in another scope. 7783 if (isIncompleteDeclExternC(S,ND)) 7784 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 7785 7786 // Neither global nor extern "C": nothing to do. 7787 return false; 7788 } 7789 7790 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 7791 // If the decl is already known invalid, don't check it. 7792 if (NewVD->isInvalidDecl()) 7793 return; 7794 7795 QualType T = NewVD->getType(); 7796 7797 // Defer checking an 'auto' type until its initializer is attached. 7798 if (T->isUndeducedType()) 7799 return; 7800 7801 if (NewVD->hasAttrs()) 7802 CheckAlignasUnderalignment(NewVD); 7803 7804 if (T->isObjCObjectType()) { 7805 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 7806 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 7807 T = Context.getObjCObjectPointerType(T); 7808 NewVD->setType(T); 7809 } 7810 7811 // Emit an error if an address space was applied to decl with local storage. 7812 // This includes arrays of objects with address space qualifiers, but not 7813 // automatic variables that point to other address spaces. 7814 // ISO/IEC TR 18037 S5.1.2 7815 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && 7816 T.getAddressSpace() != LangAS::Default) { 7817 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; 7818 NewVD->setInvalidDecl(); 7819 return; 7820 } 7821 7822 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 7823 // scope. 7824 if (getLangOpts().OpenCLVersion == 120 && 7825 !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") && 7826 NewVD->isStaticLocal()) { 7827 Diag(NewVD->getLocation(), diag::err_static_function_scope); 7828 NewVD->setInvalidDecl(); 7829 return; 7830 } 7831 7832 if (getLangOpts().OpenCL) { 7833 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 7834 if (NewVD->hasAttr<BlocksAttr>()) { 7835 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 7836 return; 7837 } 7838 7839 if (T->isBlockPointerType()) { 7840 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 7841 // can't use 'extern' storage class. 7842 if (!T.isConstQualified()) { 7843 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 7844 << 0 /*const*/; 7845 NewVD->setInvalidDecl(); 7846 return; 7847 } 7848 if (NewVD->hasExternalStorage()) { 7849 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 7850 NewVD->setInvalidDecl(); 7851 return; 7852 } 7853 } 7854 // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the 7855 // __constant address space. 7856 // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static 7857 // variables inside a function can also be declared in the global 7858 // address space. 7859 // C++ for OpenCL inherits rule from OpenCL C v2.0. 7860 // FIXME: Adding local AS in C++ for OpenCL might make sense. 7861 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 7862 NewVD->hasExternalStorage()) { 7863 if (!T->isSamplerT() && 7864 !T->isDependentType() && 7865 !(T.getAddressSpace() == LangAS::opencl_constant || 7866 (T.getAddressSpace() == LangAS::opencl_global && 7867 (getLangOpts().OpenCLVersion == 200 || 7868 getLangOpts().OpenCLCPlusPlus)))) { 7869 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 7870 if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus) 7871 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7872 << Scope << "global or constant"; 7873 else 7874 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7875 << Scope << "constant"; 7876 NewVD->setInvalidDecl(); 7877 return; 7878 } 7879 } else { 7880 if (T.getAddressSpace() == LangAS::opencl_global) { 7881 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7882 << 1 /*is any function*/ << "global"; 7883 NewVD->setInvalidDecl(); 7884 return; 7885 } 7886 if (T.getAddressSpace() == LangAS::opencl_constant || 7887 T.getAddressSpace() == LangAS::opencl_local) { 7888 FunctionDecl *FD = getCurFunctionDecl(); 7889 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables 7890 // in functions. 7891 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 7892 if (T.getAddressSpace() == LangAS::opencl_constant) 7893 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7894 << 0 /*non-kernel only*/ << "constant"; 7895 else 7896 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7897 << 0 /*non-kernel only*/ << "local"; 7898 NewVD->setInvalidDecl(); 7899 return; 7900 } 7901 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be 7902 // in the outermost scope of a kernel function. 7903 if (FD && FD->hasAttr<OpenCLKernelAttr>()) { 7904 if (!getCurScope()->isFunctionScope()) { 7905 if (T.getAddressSpace() == LangAS::opencl_constant) 7906 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7907 << "constant"; 7908 else 7909 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7910 << "local"; 7911 NewVD->setInvalidDecl(); 7912 return; 7913 } 7914 } 7915 } else if (T.getAddressSpace() != LangAS::opencl_private && 7916 // If we are parsing a template we didn't deduce an addr 7917 // space yet. 7918 T.getAddressSpace() != LangAS::Default) { 7919 // Do not allow other address spaces on automatic variable. 7920 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; 7921 NewVD->setInvalidDecl(); 7922 return; 7923 } 7924 } 7925 } 7926 7927 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 7928 && !NewVD->hasAttr<BlocksAttr>()) { 7929 if (getLangOpts().getGC() != LangOptions::NonGC) 7930 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 7931 else { 7932 assert(!getLangOpts().ObjCAutoRefCount); 7933 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 7934 } 7935 } 7936 7937 bool isVM = T->isVariablyModifiedType(); 7938 if (isVM || NewVD->hasAttr<CleanupAttr>() || 7939 NewVD->hasAttr<BlocksAttr>()) 7940 setFunctionHasBranchProtectedScope(); 7941 7942 if ((isVM && NewVD->hasLinkage()) || 7943 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 7944 bool SizeIsNegative; 7945 llvm::APSInt Oversized; 7946 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 7947 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized); 7948 QualType FixedT; 7949 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType()) 7950 FixedT = FixedTInfo->getType(); 7951 else if (FixedTInfo) { 7952 // Type and type-as-written are canonically different. We need to fix up 7953 // both types separately. 7954 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 7955 Oversized); 7956 } 7957 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) { 7958 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 7959 // FIXME: This won't give the correct result for 7960 // int a[10][n]; 7961 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 7962 7963 if (NewVD->isFileVarDecl()) 7964 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 7965 << SizeRange; 7966 else if (NewVD->isStaticLocal()) 7967 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 7968 << SizeRange; 7969 else 7970 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 7971 << SizeRange; 7972 NewVD->setInvalidDecl(); 7973 return; 7974 } 7975 7976 if (!FixedTInfo) { 7977 if (NewVD->isFileVarDecl()) 7978 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 7979 else 7980 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 7981 NewVD->setInvalidDecl(); 7982 return; 7983 } 7984 7985 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 7986 NewVD->setType(FixedT); 7987 NewVD->setTypeSourceInfo(FixedTInfo); 7988 } 7989 7990 if (T->isVoidType()) { 7991 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 7992 // of objects and functions. 7993 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 7994 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 7995 << T; 7996 NewVD->setInvalidDecl(); 7997 return; 7998 } 7999 } 8000 8001 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 8002 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 8003 NewVD->setInvalidDecl(); 8004 return; 8005 } 8006 8007 if (!NewVD->hasLocalStorage() && T->isSizelessType()) { 8008 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T; 8009 NewVD->setInvalidDecl(); 8010 return; 8011 } 8012 8013 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 8014 Diag(NewVD->getLocation(), diag::err_block_on_vm); 8015 NewVD->setInvalidDecl(); 8016 return; 8017 } 8018 8019 if (NewVD->isConstexpr() && !T->isDependentType() && 8020 RequireLiteralType(NewVD->getLocation(), T, 8021 diag::err_constexpr_var_non_literal)) { 8022 NewVD->setInvalidDecl(); 8023 return; 8024 } 8025 } 8026 8027 /// Perform semantic checking on a newly-created variable 8028 /// declaration. 8029 /// 8030 /// This routine performs all of the type-checking required for a 8031 /// variable declaration once it has been built. It is used both to 8032 /// check variables after they have been parsed and their declarators 8033 /// have been translated into a declaration, and to check variables 8034 /// that have been instantiated from a template. 8035 /// 8036 /// Sets NewVD->isInvalidDecl() if an error was encountered. 8037 /// 8038 /// Returns true if the variable declaration is a redeclaration. 8039 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 8040 CheckVariableDeclarationType(NewVD); 8041 8042 // If the decl is already known invalid, don't check it. 8043 if (NewVD->isInvalidDecl()) 8044 return false; 8045 8046 // If we did not find anything by this name, look for a non-visible 8047 // extern "C" declaration with the same name. 8048 if (Previous.empty() && 8049 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 8050 Previous.setShadowed(); 8051 8052 if (!Previous.empty()) { 8053 MergeVarDecl(NewVD, Previous); 8054 return true; 8055 } 8056 return false; 8057 } 8058 8059 namespace { 8060 struct FindOverriddenMethod { 8061 Sema *S; 8062 CXXMethodDecl *Method; 8063 8064 /// Member lookup function that determines whether a given C++ 8065 /// method overrides a method in a base class, to be used with 8066 /// CXXRecordDecl::lookupInBases(). 8067 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 8068 RecordDecl *BaseRecord = 8069 Specifier->getType()->castAs<RecordType>()->getDecl(); 8070 8071 DeclarationName Name = Method->getDeclName(); 8072 8073 // FIXME: Do we care about other names here too? 8074 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8075 // We really want to find the base class destructor here. 8076 QualType T = S->Context.getTypeDeclType(BaseRecord); 8077 CanQualType CT = S->Context.getCanonicalType(T); 8078 8079 Name = S->Context.DeclarationNames.getCXXDestructorName(CT); 8080 } 8081 8082 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 8083 Path.Decls = Path.Decls.slice(1)) { 8084 NamedDecl *D = Path.Decls.front(); 8085 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 8086 if (MD->isVirtual() && 8087 !S->IsOverload( 8088 Method, MD, /*UseMemberUsingDeclRules=*/false, 8089 /*ConsiderCudaAttrs=*/true, 8090 // C++2a [class.virtual]p2 does not consider requires clauses 8091 // when overriding. 8092 /*ConsiderRequiresClauses=*/false)) 8093 return true; 8094 } 8095 } 8096 8097 return false; 8098 } 8099 }; 8100 } // end anonymous namespace 8101 8102 /// AddOverriddenMethods - See if a method overrides any in the base classes, 8103 /// and if so, check that it's a valid override and remember it. 8104 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 8105 // Look for methods in base classes that this method might override. 8106 CXXBasePaths Paths; 8107 FindOverriddenMethod FOM; 8108 FOM.Method = MD; 8109 FOM.S = this; 8110 bool AddedAny = false; 8111 if (DC->lookupInBases(FOM, Paths)) { 8112 for (auto *I : Paths.found_decls()) { 8113 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { 8114 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 8115 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 8116 !CheckOverridingFunctionAttributes(MD, OldMD) && 8117 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 8118 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 8119 AddedAny = true; 8120 } 8121 } 8122 } 8123 } 8124 8125 return AddedAny; 8126 } 8127 8128 namespace { 8129 // Struct for holding all of the extra arguments needed by 8130 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 8131 struct ActOnFDArgs { 8132 Scope *S; 8133 Declarator &D; 8134 MultiTemplateParamsArg TemplateParamLists; 8135 bool AddToScope; 8136 }; 8137 } // end anonymous namespace 8138 8139 namespace { 8140 8141 // Callback to only accept typo corrections that have a non-zero edit distance. 8142 // Also only accept corrections that have the same parent decl. 8143 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback { 8144 public: 8145 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 8146 CXXRecordDecl *Parent) 8147 : Context(Context), OriginalFD(TypoFD), 8148 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 8149 8150 bool ValidateCandidate(const TypoCorrection &candidate) override { 8151 if (candidate.getEditDistance() == 0) 8152 return false; 8153 8154 SmallVector<unsigned, 1> MismatchedParams; 8155 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 8156 CDeclEnd = candidate.end(); 8157 CDecl != CDeclEnd; ++CDecl) { 8158 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8159 8160 if (FD && !FD->hasBody() && 8161 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 8162 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 8163 CXXRecordDecl *Parent = MD->getParent(); 8164 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 8165 return true; 8166 } else if (!ExpectedParent) { 8167 return true; 8168 } 8169 } 8170 } 8171 8172 return false; 8173 } 8174 8175 std::unique_ptr<CorrectionCandidateCallback> clone() override { 8176 return std::make_unique<DifferentNameValidatorCCC>(*this); 8177 } 8178 8179 private: 8180 ASTContext &Context; 8181 FunctionDecl *OriginalFD; 8182 CXXRecordDecl *ExpectedParent; 8183 }; 8184 8185 } // end anonymous namespace 8186 8187 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { 8188 TypoCorrectedFunctionDefinitions.insert(F); 8189 } 8190 8191 /// Generate diagnostics for an invalid function redeclaration. 8192 /// 8193 /// This routine handles generating the diagnostic messages for an invalid 8194 /// function redeclaration, including finding possible similar declarations 8195 /// or performing typo correction if there are no previous declarations with 8196 /// the same name. 8197 /// 8198 /// Returns a NamedDecl iff typo correction was performed and substituting in 8199 /// the new declaration name does not cause new errors. 8200 static NamedDecl *DiagnoseInvalidRedeclaration( 8201 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 8202 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 8203 DeclarationName Name = NewFD->getDeclName(); 8204 DeclContext *NewDC = NewFD->getDeclContext(); 8205 SmallVector<unsigned, 1> MismatchedParams; 8206 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 8207 TypoCorrection Correction; 8208 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 8209 unsigned DiagMsg = 8210 IsLocalFriend ? diag::err_no_matching_local_friend : 8211 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match : 8212 diag::err_member_decl_does_not_match; 8213 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 8214 IsLocalFriend ? Sema::LookupLocalFriendName 8215 : Sema::LookupOrdinaryName, 8216 Sema::ForVisibleRedeclaration); 8217 8218 NewFD->setInvalidDecl(); 8219 if (IsLocalFriend) 8220 SemaRef.LookupName(Prev, S); 8221 else 8222 SemaRef.LookupQualifiedName(Prev, NewDC); 8223 assert(!Prev.isAmbiguous() && 8224 "Cannot have an ambiguity in previous-declaration lookup"); 8225 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 8226 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD, 8227 MD ? MD->getParent() : nullptr); 8228 if (!Prev.empty()) { 8229 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 8230 Func != FuncEnd; ++Func) { 8231 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 8232 if (FD && 8233 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8234 // Add 1 to the index so that 0 can mean the mismatch didn't 8235 // involve a parameter 8236 unsigned ParamNum = 8237 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 8238 NearMatches.push_back(std::make_pair(FD, ParamNum)); 8239 } 8240 } 8241 // If the qualified name lookup yielded nothing, try typo correction 8242 } else if ((Correction = SemaRef.CorrectTypo( 8243 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 8244 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery, 8245 IsLocalFriend ? nullptr : NewDC))) { 8246 // Set up everything for the call to ActOnFunctionDeclarator 8247 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 8248 ExtraArgs.D.getIdentifierLoc()); 8249 Previous.clear(); 8250 Previous.setLookupName(Correction.getCorrection()); 8251 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 8252 CDeclEnd = Correction.end(); 8253 CDecl != CDeclEnd; ++CDecl) { 8254 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8255 if (FD && !FD->hasBody() && 8256 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8257 Previous.addDecl(FD); 8258 } 8259 } 8260 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 8261 8262 NamedDecl *Result; 8263 // Retry building the function declaration with the new previous 8264 // declarations, and with errors suppressed. 8265 { 8266 // Trap errors. 8267 Sema::SFINAETrap Trap(SemaRef); 8268 8269 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 8270 // pieces need to verify the typo-corrected C++ declaration and hopefully 8271 // eliminate the need for the parameter pack ExtraArgs. 8272 Result = SemaRef.ActOnFunctionDeclarator( 8273 ExtraArgs.S, ExtraArgs.D, 8274 Correction.getCorrectionDecl()->getDeclContext(), 8275 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 8276 ExtraArgs.AddToScope); 8277 8278 if (Trap.hasErrorOccurred()) 8279 Result = nullptr; 8280 } 8281 8282 if (Result) { 8283 // Determine which correction we picked. 8284 Decl *Canonical = Result->getCanonicalDecl(); 8285 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 8286 I != E; ++I) 8287 if ((*I)->getCanonicalDecl() == Canonical) 8288 Correction.setCorrectionDecl(*I); 8289 8290 // Let Sema know about the correction. 8291 SemaRef.MarkTypoCorrectedFunctionDefinition(Result); 8292 SemaRef.diagnoseTypo( 8293 Correction, 8294 SemaRef.PDiag(IsLocalFriend 8295 ? diag::err_no_matching_local_friend_suggest 8296 : diag::err_member_decl_does_not_match_suggest) 8297 << Name << NewDC << IsDefinition); 8298 return Result; 8299 } 8300 8301 // Pretend the typo correction never occurred 8302 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 8303 ExtraArgs.D.getIdentifierLoc()); 8304 ExtraArgs.D.setRedeclaration(wasRedeclaration); 8305 Previous.clear(); 8306 Previous.setLookupName(Name); 8307 } 8308 8309 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 8310 << Name << NewDC << IsDefinition << NewFD->getLocation(); 8311 8312 bool NewFDisConst = false; 8313 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 8314 NewFDisConst = NewMD->isConst(); 8315 8316 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 8317 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 8318 NearMatch != NearMatchEnd; ++NearMatch) { 8319 FunctionDecl *FD = NearMatch->first; 8320 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 8321 bool FDisConst = MD && MD->isConst(); 8322 bool IsMember = MD || !IsLocalFriend; 8323 8324 // FIXME: These notes are poorly worded for the local friend case. 8325 if (unsigned Idx = NearMatch->second) { 8326 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 8327 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 8328 if (Loc.isInvalid()) Loc = FD->getLocation(); 8329 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 8330 : diag::note_local_decl_close_param_match) 8331 << Idx << FDParam->getType() 8332 << NewFD->getParamDecl(Idx - 1)->getType(); 8333 } else if (FDisConst != NewFDisConst) { 8334 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 8335 << NewFDisConst << FD->getSourceRange().getEnd(); 8336 } else 8337 SemaRef.Diag(FD->getLocation(), 8338 IsMember ? diag::note_member_def_close_match 8339 : diag::note_local_decl_close_match); 8340 } 8341 return nullptr; 8342 } 8343 8344 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 8345 switch (D.getDeclSpec().getStorageClassSpec()) { 8346 default: llvm_unreachable("Unknown storage class!"); 8347 case DeclSpec::SCS_auto: 8348 case DeclSpec::SCS_register: 8349 case DeclSpec::SCS_mutable: 8350 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8351 diag::err_typecheck_sclass_func); 8352 D.getMutableDeclSpec().ClearStorageClassSpecs(); 8353 D.setInvalidType(); 8354 break; 8355 case DeclSpec::SCS_unspecified: break; 8356 case DeclSpec::SCS_extern: 8357 if (D.getDeclSpec().isExternInLinkageSpec()) 8358 return SC_None; 8359 return SC_Extern; 8360 case DeclSpec::SCS_static: { 8361 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 8362 // C99 6.7.1p5: 8363 // The declaration of an identifier for a function that has 8364 // block scope shall have no explicit storage-class specifier 8365 // other than extern 8366 // See also (C++ [dcl.stc]p4). 8367 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8368 diag::err_static_block_func); 8369 break; 8370 } else 8371 return SC_Static; 8372 } 8373 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 8374 } 8375 8376 // No explicit storage class has already been returned 8377 return SC_None; 8378 } 8379 8380 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 8381 DeclContext *DC, QualType &R, 8382 TypeSourceInfo *TInfo, 8383 StorageClass SC, 8384 bool &IsVirtualOkay) { 8385 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 8386 DeclarationName Name = NameInfo.getName(); 8387 8388 FunctionDecl *NewFD = nullptr; 8389 bool isInline = D.getDeclSpec().isInlineSpecified(); 8390 8391 if (!SemaRef.getLangOpts().CPlusPlus) { 8392 // Determine whether the function was written with a 8393 // prototype. This true when: 8394 // - there is a prototype in the declarator, or 8395 // - the type R of the function is some kind of typedef or other non- 8396 // attributed reference to a type name (which eventually refers to a 8397 // function type). 8398 bool HasPrototype = 8399 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 8400 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 8401 8402 NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, 8403 R, TInfo, SC, isInline, HasPrototype, 8404 CSK_unspecified, 8405 /*TrailingRequiresClause=*/nullptr); 8406 if (D.isInvalidType()) 8407 NewFD->setInvalidDecl(); 8408 8409 return NewFD; 8410 } 8411 8412 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier(); 8413 8414 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 8415 if (ConstexprKind == CSK_constinit) { 8416 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(), 8417 diag::err_constexpr_wrong_decl_kind) 8418 << ConstexprKind; 8419 ConstexprKind = CSK_unspecified; 8420 D.getMutableDeclSpec().ClearConstexprSpec(); 8421 } 8422 Expr *TrailingRequiresClause = D.getTrailingRequiresClause(); 8423 8424 // Check that the return type is not an abstract class type. 8425 // For record types, this is done by the AbstractClassUsageDiagnoser once 8426 // the class has been completely parsed. 8427 if (!DC->isRecord() && 8428 SemaRef.RequireNonAbstractType( 8429 D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(), 8430 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 8431 D.setInvalidType(); 8432 8433 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 8434 // This is a C++ constructor declaration. 8435 assert(DC->isRecord() && 8436 "Constructors can only be declared in a member context"); 8437 8438 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 8439 return CXXConstructorDecl::Create( 8440 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8441 TInfo, ExplicitSpecifier, isInline, 8442 /*isImplicitlyDeclared=*/false, ConstexprKind, InheritedConstructor(), 8443 TrailingRequiresClause); 8444 8445 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8446 // This is a C++ destructor declaration. 8447 if (DC->isRecord()) { 8448 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 8449 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 8450 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 8451 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo, 8452 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind, 8453 TrailingRequiresClause); 8454 8455 // If the destructor needs an implicit exception specification, set it 8456 // now. FIXME: It'd be nice to be able to create the right type to start 8457 // with, but the type needs to reference the destructor declaration. 8458 if (SemaRef.getLangOpts().CPlusPlus11) 8459 SemaRef.AdjustDestructorExceptionSpec(NewDD); 8460 8461 IsVirtualOkay = true; 8462 return NewDD; 8463 8464 } else { 8465 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 8466 D.setInvalidType(); 8467 8468 // Create a FunctionDecl to satisfy the function definition parsing 8469 // code path. 8470 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8471 D.getIdentifierLoc(), Name, R, TInfo, SC, 8472 isInline, 8473 /*hasPrototype=*/true, ConstexprKind, 8474 TrailingRequiresClause); 8475 } 8476 8477 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 8478 if (!DC->isRecord()) { 8479 SemaRef.Diag(D.getIdentifierLoc(), 8480 diag::err_conv_function_not_member); 8481 return nullptr; 8482 } 8483 8484 SemaRef.CheckConversionDeclarator(D, R, SC); 8485 if (D.isInvalidType()) 8486 return nullptr; 8487 8488 IsVirtualOkay = true; 8489 return CXXConversionDecl::Create( 8490 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8491 TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation(), 8492 TrailingRequiresClause); 8493 8494 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 8495 if (TrailingRequiresClause) 8496 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(), 8497 diag::err_trailing_requires_clause_on_deduction_guide) 8498 << TrailingRequiresClause->getSourceRange(); 8499 SemaRef.CheckDeductionGuideDeclarator(D, R, SC); 8500 8501 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8502 ExplicitSpecifier, NameInfo, R, TInfo, 8503 D.getEndLoc()); 8504 } else if (DC->isRecord()) { 8505 // If the name of the function is the same as the name of the record, 8506 // then this must be an invalid constructor that has a return type. 8507 // (The parser checks for a return type and makes the declarator a 8508 // constructor if it has no return type). 8509 if (Name.getAsIdentifierInfo() && 8510 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 8511 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 8512 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8513 << SourceRange(D.getIdentifierLoc()); 8514 return nullptr; 8515 } 8516 8517 // This is a C++ method declaration. 8518 CXXMethodDecl *Ret = CXXMethodDecl::Create( 8519 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8520 TInfo, SC, isInline, ConstexprKind, SourceLocation(), 8521 TrailingRequiresClause); 8522 IsVirtualOkay = !Ret->isStatic(); 8523 return Ret; 8524 } else { 8525 bool isFriend = 8526 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 8527 if (!isFriend && SemaRef.CurContext->isRecord()) 8528 return nullptr; 8529 8530 // Determine whether the function was written with a 8531 // prototype. This true when: 8532 // - we're in C++ (where every function has a prototype), 8533 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, 8534 R, TInfo, SC, isInline, true /*HasPrototype*/, 8535 ConstexprKind, TrailingRequiresClause); 8536 } 8537 } 8538 8539 enum OpenCLParamType { 8540 ValidKernelParam, 8541 PtrPtrKernelParam, 8542 PtrKernelParam, 8543 InvalidAddrSpacePtrKernelParam, 8544 InvalidKernelParam, 8545 RecordKernelParam 8546 }; 8547 8548 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) { 8549 // Size dependent types are just typedefs to normal integer types 8550 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to 8551 // integers other than by their names. 8552 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"}; 8553 8554 // Remove typedefs one by one until we reach a typedef 8555 // for a size dependent type. 8556 QualType DesugaredTy = Ty; 8557 do { 8558 ArrayRef<StringRef> Names(SizeTypeNames); 8559 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString()); 8560 if (Names.end() != Match) 8561 return true; 8562 8563 Ty = DesugaredTy; 8564 DesugaredTy = Ty.getSingleStepDesugaredType(C); 8565 } while (DesugaredTy != Ty); 8566 8567 return false; 8568 } 8569 8570 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 8571 if (PT->isPointerType()) { 8572 QualType PointeeType = PT->getPointeeType(); 8573 if (PointeeType->isPointerType()) 8574 return PtrPtrKernelParam; 8575 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 8576 PointeeType.getAddressSpace() == LangAS::opencl_private || 8577 PointeeType.getAddressSpace() == LangAS::Default) 8578 return InvalidAddrSpacePtrKernelParam; 8579 return PtrKernelParam; 8580 } 8581 8582 // OpenCL v1.2 s6.9.k: 8583 // Arguments to kernel functions in a program cannot be declared with the 8584 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8585 // uintptr_t or a struct and/or union that contain fields declared to be one 8586 // of these built-in scalar types. 8587 if (isOpenCLSizeDependentType(S.getASTContext(), PT)) 8588 return InvalidKernelParam; 8589 8590 if (PT->isImageType()) 8591 return PtrKernelParam; 8592 8593 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) 8594 return InvalidKernelParam; 8595 8596 // OpenCL extension spec v1.2 s9.5: 8597 // This extension adds support for half scalar and vector types as built-in 8598 // types that can be used for arithmetic operations, conversions etc. 8599 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType()) 8600 return InvalidKernelParam; 8601 8602 if (PT->isRecordType()) 8603 return RecordKernelParam; 8604 8605 // Look into an array argument to check if it has a forbidden type. 8606 if (PT->isArrayType()) { 8607 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType(); 8608 // Call ourself to check an underlying type of an array. Since the 8609 // getPointeeOrArrayElementType returns an innermost type which is not an 8610 // array, this recursive call only happens once. 8611 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0)); 8612 } 8613 8614 return ValidKernelParam; 8615 } 8616 8617 static void checkIsValidOpenCLKernelParameter( 8618 Sema &S, 8619 Declarator &D, 8620 ParmVarDecl *Param, 8621 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 8622 QualType PT = Param->getType(); 8623 8624 // Cache the valid types we encounter to avoid rechecking structs that are 8625 // used again 8626 if (ValidTypes.count(PT.getTypePtr())) 8627 return; 8628 8629 switch (getOpenCLKernelParameterType(S, PT)) { 8630 case PtrPtrKernelParam: 8631 // OpenCL v1.2 s6.9.a: 8632 // A kernel function argument cannot be declared as a 8633 // pointer to a pointer type. 8634 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 8635 D.setInvalidType(); 8636 return; 8637 8638 case InvalidAddrSpacePtrKernelParam: 8639 // OpenCL v1.0 s6.5: 8640 // __kernel function arguments declared to be a pointer of a type can point 8641 // to one of the following address spaces only : __global, __local or 8642 // __constant. 8643 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 8644 D.setInvalidType(); 8645 return; 8646 8647 // OpenCL v1.2 s6.9.k: 8648 // Arguments to kernel functions in a program cannot be declared with the 8649 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8650 // uintptr_t or a struct and/or union that contain fields declared to be 8651 // one of these built-in scalar types. 8652 8653 case InvalidKernelParam: 8654 // OpenCL v1.2 s6.8 n: 8655 // A kernel function argument cannot be declared 8656 // of event_t type. 8657 // Do not diagnose half type since it is diagnosed as invalid argument 8658 // type for any function elsewhere. 8659 if (!PT->isHalfType()) { 8660 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8661 8662 // Explain what typedefs are involved. 8663 const TypedefType *Typedef = nullptr; 8664 while ((Typedef = PT->getAs<TypedefType>())) { 8665 SourceLocation Loc = Typedef->getDecl()->getLocation(); 8666 // SourceLocation may be invalid for a built-in type. 8667 if (Loc.isValid()) 8668 S.Diag(Loc, diag::note_entity_declared_at) << PT; 8669 PT = Typedef->desugar(); 8670 } 8671 } 8672 8673 D.setInvalidType(); 8674 return; 8675 8676 case PtrKernelParam: 8677 case ValidKernelParam: 8678 ValidTypes.insert(PT.getTypePtr()); 8679 return; 8680 8681 case RecordKernelParam: 8682 break; 8683 } 8684 8685 // Track nested structs we will inspect 8686 SmallVector<const Decl *, 4> VisitStack; 8687 8688 // Track where we are in the nested structs. Items will migrate from 8689 // VisitStack to HistoryStack as we do the DFS for bad field. 8690 SmallVector<const FieldDecl *, 4> HistoryStack; 8691 HistoryStack.push_back(nullptr); 8692 8693 // At this point we already handled everything except of a RecordType or 8694 // an ArrayType of a RecordType. 8695 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type."); 8696 const RecordType *RecTy = 8697 PT->getPointeeOrArrayElementType()->getAs<RecordType>(); 8698 const RecordDecl *OrigRecDecl = RecTy->getDecl(); 8699 8700 VisitStack.push_back(RecTy->getDecl()); 8701 assert(VisitStack.back() && "First decl null?"); 8702 8703 do { 8704 const Decl *Next = VisitStack.pop_back_val(); 8705 if (!Next) { 8706 assert(!HistoryStack.empty()); 8707 // Found a marker, we have gone up a level 8708 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 8709 ValidTypes.insert(Hist->getType().getTypePtr()); 8710 8711 continue; 8712 } 8713 8714 // Adds everything except the original parameter declaration (which is not a 8715 // field itself) to the history stack. 8716 const RecordDecl *RD; 8717 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 8718 HistoryStack.push_back(Field); 8719 8720 QualType FieldTy = Field->getType(); 8721 // Other field types (known to be valid or invalid) are handled while we 8722 // walk around RecordDecl::fields(). 8723 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) && 8724 "Unexpected type."); 8725 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType(); 8726 8727 RD = FieldRecTy->castAs<RecordType>()->getDecl(); 8728 } else { 8729 RD = cast<RecordDecl>(Next); 8730 } 8731 8732 // Add a null marker so we know when we've gone back up a level 8733 VisitStack.push_back(nullptr); 8734 8735 for (const auto *FD : RD->fields()) { 8736 QualType QT = FD->getType(); 8737 8738 if (ValidTypes.count(QT.getTypePtr())) 8739 continue; 8740 8741 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 8742 if (ParamType == ValidKernelParam) 8743 continue; 8744 8745 if (ParamType == RecordKernelParam) { 8746 VisitStack.push_back(FD); 8747 continue; 8748 } 8749 8750 // OpenCL v1.2 s6.9.p: 8751 // Arguments to kernel functions that are declared to be a struct or union 8752 // do not allow OpenCL objects to be passed as elements of the struct or 8753 // union. 8754 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 8755 ParamType == InvalidAddrSpacePtrKernelParam) { 8756 S.Diag(Param->getLocation(), 8757 diag::err_record_with_pointers_kernel_param) 8758 << PT->isUnionType() 8759 << PT; 8760 } else { 8761 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8762 } 8763 8764 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type) 8765 << OrigRecDecl->getDeclName(); 8766 8767 // We have an error, now let's go back up through history and show where 8768 // the offending field came from 8769 for (ArrayRef<const FieldDecl *>::const_iterator 8770 I = HistoryStack.begin() + 1, 8771 E = HistoryStack.end(); 8772 I != E; ++I) { 8773 const FieldDecl *OuterField = *I; 8774 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 8775 << OuterField->getType(); 8776 } 8777 8778 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 8779 << QT->isPointerType() 8780 << QT; 8781 D.setInvalidType(); 8782 return; 8783 } 8784 } while (!VisitStack.empty()); 8785 } 8786 8787 /// Find the DeclContext in which a tag is implicitly declared if we see an 8788 /// elaborated type specifier in the specified context, and lookup finds 8789 /// nothing. 8790 static DeclContext *getTagInjectionContext(DeclContext *DC) { 8791 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 8792 DC = DC->getParent(); 8793 return DC; 8794 } 8795 8796 /// Find the Scope in which a tag is implicitly declared if we see an 8797 /// elaborated type specifier in the specified context, and lookup finds 8798 /// nothing. 8799 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 8800 while (S->isClassScope() || 8801 (LangOpts.CPlusPlus && 8802 S->isFunctionPrototypeScope()) || 8803 ((S->getFlags() & Scope::DeclScope) == 0) || 8804 (S->getEntity() && S->getEntity()->isTransparentContext())) 8805 S = S->getParent(); 8806 return S; 8807 } 8808 8809 NamedDecl* 8810 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 8811 TypeSourceInfo *TInfo, LookupResult &Previous, 8812 MultiTemplateParamsArg TemplateParamListsRef, 8813 bool &AddToScope) { 8814 QualType R = TInfo->getType(); 8815 8816 assert(R->isFunctionType()); 8817 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr()) 8818 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call); 8819 8820 SmallVector<TemplateParameterList *, 4> TemplateParamLists; 8821 for (TemplateParameterList *TPL : TemplateParamListsRef) 8822 TemplateParamLists.push_back(TPL); 8823 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) { 8824 if (!TemplateParamLists.empty() && 8825 Invented->getDepth() == TemplateParamLists.back()->getDepth()) 8826 TemplateParamLists.back() = Invented; 8827 else 8828 TemplateParamLists.push_back(Invented); 8829 } 8830 8831 // TODO: consider using NameInfo for diagnostic. 8832 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 8833 DeclarationName Name = NameInfo.getName(); 8834 StorageClass SC = getFunctionStorageClass(*this, D); 8835 8836 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 8837 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 8838 diag::err_invalid_thread) 8839 << DeclSpec::getSpecifierName(TSCS); 8840 8841 if (D.isFirstDeclarationOfMember()) 8842 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 8843 D.getIdentifierLoc()); 8844 8845 bool isFriend = false; 8846 FunctionTemplateDecl *FunctionTemplate = nullptr; 8847 bool isMemberSpecialization = false; 8848 bool isFunctionTemplateSpecialization = false; 8849 8850 bool isDependentClassScopeExplicitSpecialization = false; 8851 bool HasExplicitTemplateArgs = false; 8852 TemplateArgumentListInfo TemplateArgs; 8853 8854 bool isVirtualOkay = false; 8855 8856 DeclContext *OriginalDC = DC; 8857 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 8858 8859 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 8860 isVirtualOkay); 8861 if (!NewFD) return nullptr; 8862 8863 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 8864 NewFD->setTopLevelDeclInObjCContainer(); 8865 8866 // Set the lexical context. If this is a function-scope declaration, or has a 8867 // C++ scope specifier, or is the object of a friend declaration, the lexical 8868 // context will be different from the semantic context. 8869 NewFD->setLexicalDeclContext(CurContext); 8870 8871 if (IsLocalExternDecl) 8872 NewFD->setLocalExternDecl(); 8873 8874 if (getLangOpts().CPlusPlus) { 8875 bool isInline = D.getDeclSpec().isInlineSpecified(); 8876 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 8877 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier(); 8878 isFriend = D.getDeclSpec().isFriendSpecified(); 8879 if (isFriend && !isInline && D.isFunctionDefinition()) { 8880 // C++ [class.friend]p5 8881 // A function can be defined in a friend declaration of a 8882 // class . . . . Such a function is implicitly inline. 8883 NewFD->setImplicitlyInline(); 8884 } 8885 8886 // If this is a method defined in an __interface, and is not a constructor 8887 // or an overloaded operator, then set the pure flag (isVirtual will already 8888 // return true). 8889 if (const CXXRecordDecl *Parent = 8890 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 8891 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 8892 NewFD->setPure(true); 8893 8894 // C++ [class.union]p2 8895 // A union can have member functions, but not virtual functions. 8896 if (isVirtual && Parent->isUnion()) 8897 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 8898 } 8899 8900 SetNestedNameSpecifier(*this, NewFD, D); 8901 isMemberSpecialization = false; 8902 isFunctionTemplateSpecialization = false; 8903 if (D.isInvalidType()) 8904 NewFD->setInvalidDecl(); 8905 8906 // Match up the template parameter lists with the scope specifier, then 8907 // determine whether we have a template or a template specialization. 8908 bool Invalid = false; 8909 TemplateParameterList *TemplateParams = 8910 MatchTemplateParametersToScopeSpecifier( 8911 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 8912 D.getCXXScopeSpec(), 8913 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 8914 ? D.getName().TemplateId 8915 : nullptr, 8916 TemplateParamLists, isFriend, isMemberSpecialization, 8917 Invalid); 8918 if (TemplateParams) { 8919 if (TemplateParams->size() > 0) { 8920 // This is a function template 8921 8922 // Check that we can declare a template here. 8923 if (CheckTemplateDeclScope(S, TemplateParams)) 8924 NewFD->setInvalidDecl(); 8925 8926 // A destructor cannot be a template. 8927 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8928 Diag(NewFD->getLocation(), diag::err_destructor_template); 8929 NewFD->setInvalidDecl(); 8930 } 8931 8932 // If we're adding a template to a dependent context, we may need to 8933 // rebuilding some of the types used within the template parameter list, 8934 // now that we know what the current instantiation is. 8935 if (DC->isDependentContext()) { 8936 ContextRAII SavedContext(*this, DC); 8937 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 8938 Invalid = true; 8939 } 8940 8941 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 8942 NewFD->getLocation(), 8943 Name, TemplateParams, 8944 NewFD); 8945 FunctionTemplate->setLexicalDeclContext(CurContext); 8946 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 8947 8948 // For source fidelity, store the other template param lists. 8949 if (TemplateParamLists.size() > 1) { 8950 NewFD->setTemplateParameterListsInfo(Context, 8951 ArrayRef<TemplateParameterList *>(TemplateParamLists) 8952 .drop_back(1)); 8953 } 8954 } else { 8955 // This is a function template specialization. 8956 isFunctionTemplateSpecialization = true; 8957 // For source fidelity, store all the template param lists. 8958 if (TemplateParamLists.size() > 0) 8959 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8960 8961 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 8962 if (isFriend) { 8963 // We want to remove the "template<>", found here. 8964 SourceRange RemoveRange = TemplateParams->getSourceRange(); 8965 8966 // If we remove the template<> and the name is not a 8967 // template-id, we're actually silently creating a problem: 8968 // the friend declaration will refer to an untemplated decl, 8969 // and clearly the user wants a template specialization. So 8970 // we need to insert '<>' after the name. 8971 SourceLocation InsertLoc; 8972 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 8973 InsertLoc = D.getName().getSourceRange().getEnd(); 8974 InsertLoc = getLocForEndOfToken(InsertLoc); 8975 } 8976 8977 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 8978 << Name << RemoveRange 8979 << FixItHint::CreateRemoval(RemoveRange) 8980 << FixItHint::CreateInsertion(InsertLoc, "<>"); 8981 } 8982 } 8983 } else { 8984 // All template param lists were matched against the scope specifier: 8985 // this is NOT (an explicit specialization of) a template. 8986 if (TemplateParamLists.size() > 0) 8987 // For source fidelity, store all the template param lists. 8988 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8989 } 8990 8991 if (Invalid) { 8992 NewFD->setInvalidDecl(); 8993 if (FunctionTemplate) 8994 FunctionTemplate->setInvalidDecl(); 8995 } 8996 8997 // C++ [dcl.fct.spec]p5: 8998 // The virtual specifier shall only be used in declarations of 8999 // nonstatic class member functions that appear within a 9000 // member-specification of a class declaration; see 10.3. 9001 // 9002 if (isVirtual && !NewFD->isInvalidDecl()) { 9003 if (!isVirtualOkay) { 9004 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9005 diag::err_virtual_non_function); 9006 } else if (!CurContext->isRecord()) { 9007 // 'virtual' was specified outside of the class. 9008 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9009 diag::err_virtual_out_of_class) 9010 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 9011 } else if (NewFD->getDescribedFunctionTemplate()) { 9012 // C++ [temp.mem]p3: 9013 // A member function template shall not be virtual. 9014 Diag(D.getDeclSpec().getVirtualSpecLoc(), 9015 diag::err_virtual_member_function_template) 9016 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 9017 } else { 9018 // Okay: Add virtual to the method. 9019 NewFD->setVirtualAsWritten(true); 9020 } 9021 9022 if (getLangOpts().CPlusPlus14 && 9023 NewFD->getReturnType()->isUndeducedType()) 9024 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 9025 } 9026 9027 if (getLangOpts().CPlusPlus14 && 9028 (NewFD->isDependentContext() || 9029 (isFriend && CurContext->isDependentContext())) && 9030 NewFD->getReturnType()->isUndeducedType()) { 9031 // If the function template is referenced directly (for instance, as a 9032 // member of the current instantiation), pretend it has a dependent type. 9033 // This is not really justified by the standard, but is the only sane 9034 // thing to do. 9035 // FIXME: For a friend function, we have not marked the function as being 9036 // a friend yet, so 'isDependentContext' on the FD doesn't work. 9037 const FunctionProtoType *FPT = 9038 NewFD->getType()->castAs<FunctionProtoType>(); 9039 QualType Result = 9040 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 9041 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 9042 FPT->getExtProtoInfo())); 9043 } 9044 9045 // C++ [dcl.fct.spec]p3: 9046 // The inline specifier shall not appear on a block scope function 9047 // declaration. 9048 if (isInline && !NewFD->isInvalidDecl()) { 9049 if (CurContext->isFunctionOrMethod()) { 9050 // 'inline' is not allowed on block scope function declaration. 9051 Diag(D.getDeclSpec().getInlineSpecLoc(), 9052 diag::err_inline_declaration_block_scope) << Name 9053 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 9054 } 9055 } 9056 9057 // C++ [dcl.fct.spec]p6: 9058 // The explicit specifier shall be used only in the declaration of a 9059 // constructor or conversion function within its class definition; 9060 // see 12.3.1 and 12.3.2. 9061 if (hasExplicit && !NewFD->isInvalidDecl() && 9062 !isa<CXXDeductionGuideDecl>(NewFD)) { 9063 if (!CurContext->isRecord()) { 9064 // 'explicit' was specified outside of the class. 9065 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9066 diag::err_explicit_out_of_class) 9067 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9068 } else if (!isa<CXXConstructorDecl>(NewFD) && 9069 !isa<CXXConversionDecl>(NewFD)) { 9070 // 'explicit' was specified on a function that wasn't a constructor 9071 // or conversion function. 9072 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9073 diag::err_explicit_non_ctor_or_conv_function) 9074 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9075 } 9076 } 9077 9078 if (ConstexprSpecKind ConstexprKind = 9079 D.getDeclSpec().getConstexprSpecifier()) { 9080 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 9081 // are implicitly inline. 9082 NewFD->setImplicitlyInline(); 9083 9084 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 9085 // be either constructors or to return a literal type. Therefore, 9086 // destructors cannot be declared constexpr. 9087 if (isa<CXXDestructorDecl>(NewFD) && 9088 (!getLangOpts().CPlusPlus20 || ConstexprKind == CSK_consteval)) { 9089 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor) 9090 << ConstexprKind; 9091 NewFD->setConstexprKind(getLangOpts().CPlusPlus20 ? CSK_unspecified : CSK_constexpr); 9092 } 9093 // C++20 [dcl.constexpr]p2: An allocation function, or a 9094 // deallocation function shall not be declared with the consteval 9095 // specifier. 9096 if (ConstexprKind == CSK_consteval && 9097 (NewFD->getOverloadedOperator() == OO_New || 9098 NewFD->getOverloadedOperator() == OO_Array_New || 9099 NewFD->getOverloadedOperator() == OO_Delete || 9100 NewFD->getOverloadedOperator() == OO_Array_Delete)) { 9101 Diag(D.getDeclSpec().getConstexprSpecLoc(), 9102 diag::err_invalid_consteval_decl_kind) 9103 << NewFD; 9104 NewFD->setConstexprKind(CSK_constexpr); 9105 } 9106 } 9107 9108 // If __module_private__ was specified, mark the function accordingly. 9109 if (D.getDeclSpec().isModulePrivateSpecified()) { 9110 if (isFunctionTemplateSpecialization) { 9111 SourceLocation ModulePrivateLoc 9112 = D.getDeclSpec().getModulePrivateSpecLoc(); 9113 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 9114 << 0 9115 << FixItHint::CreateRemoval(ModulePrivateLoc); 9116 } else { 9117 NewFD->setModulePrivate(); 9118 if (FunctionTemplate) 9119 FunctionTemplate->setModulePrivate(); 9120 } 9121 } 9122 9123 if (isFriend) { 9124 if (FunctionTemplate) { 9125 FunctionTemplate->setObjectOfFriendDecl(); 9126 FunctionTemplate->setAccess(AS_public); 9127 } 9128 NewFD->setObjectOfFriendDecl(); 9129 NewFD->setAccess(AS_public); 9130 } 9131 9132 // If a function is defined as defaulted or deleted, mark it as such now. 9133 // We'll do the relevant checks on defaulted / deleted functions later. 9134 switch (D.getFunctionDefinitionKind()) { 9135 case FDK_Declaration: 9136 case FDK_Definition: 9137 break; 9138 9139 case FDK_Defaulted: 9140 NewFD->setDefaulted(); 9141 break; 9142 9143 case FDK_Deleted: 9144 NewFD->setDeletedAsWritten(); 9145 break; 9146 } 9147 9148 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 9149 D.isFunctionDefinition()) { 9150 // C++ [class.mfct]p2: 9151 // A member function may be defined (8.4) in its class definition, in 9152 // which case it is an inline member function (7.1.2) 9153 NewFD->setImplicitlyInline(); 9154 } 9155 9156 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 9157 !CurContext->isRecord()) { 9158 // C++ [class.static]p1: 9159 // A data or function member of a class may be declared static 9160 // in a class definition, in which case it is a static member of 9161 // the class. 9162 9163 // Complain about the 'static' specifier if it's on an out-of-line 9164 // member function definition. 9165 9166 // MSVC permits the use of a 'static' storage specifier on an out-of-line 9167 // member function template declaration and class member template 9168 // declaration (MSVC versions before 2015), warn about this. 9169 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 9170 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 9171 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) || 9172 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate())) 9173 ? diag::ext_static_out_of_line : diag::err_static_out_of_line) 9174 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 9175 } 9176 9177 // C++11 [except.spec]p15: 9178 // A deallocation function with no exception-specification is treated 9179 // as if it were specified with noexcept(true). 9180 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 9181 if ((Name.getCXXOverloadedOperator() == OO_Delete || 9182 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 9183 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 9184 NewFD->setType(Context.getFunctionType( 9185 FPT->getReturnType(), FPT->getParamTypes(), 9186 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 9187 } 9188 9189 // Filter out previous declarations that don't match the scope. 9190 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 9191 D.getCXXScopeSpec().isNotEmpty() || 9192 isMemberSpecialization || 9193 isFunctionTemplateSpecialization); 9194 9195 // Handle GNU asm-label extension (encoded as an attribute). 9196 if (Expr *E = (Expr*) D.getAsmLabel()) { 9197 // The parser guarantees this is a string. 9198 StringLiteral *SE = cast<StringLiteral>(E); 9199 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(), 9200 /*IsLiteralLabel=*/true, 9201 SE->getStrTokenLoc(0))); 9202 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 9203 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 9204 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 9205 if (I != ExtnameUndeclaredIdentifiers.end()) { 9206 if (isDeclExternC(NewFD)) { 9207 NewFD->addAttr(I->second); 9208 ExtnameUndeclaredIdentifiers.erase(I); 9209 } else 9210 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 9211 << /*Variable*/0 << NewFD; 9212 } 9213 } 9214 9215 // Copy the parameter declarations from the declarator D to the function 9216 // declaration NewFD, if they are available. First scavenge them into Params. 9217 SmallVector<ParmVarDecl*, 16> Params; 9218 unsigned FTIIdx; 9219 if (D.isFunctionDeclarator(FTIIdx)) { 9220 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 9221 9222 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 9223 // function that takes no arguments, not a function that takes a 9224 // single void argument. 9225 // We let through "const void" here because Sema::GetTypeForDeclarator 9226 // already checks for that case. 9227 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 9228 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 9229 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 9230 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 9231 Param->setDeclContext(NewFD); 9232 Params.push_back(Param); 9233 9234 if (Param->isInvalidDecl()) 9235 NewFD->setInvalidDecl(); 9236 } 9237 } 9238 9239 if (!getLangOpts().CPlusPlus) { 9240 // In C, find all the tag declarations from the prototype and move them 9241 // into the function DeclContext. Remove them from the surrounding tag 9242 // injection context of the function, which is typically but not always 9243 // the TU. 9244 DeclContext *PrototypeTagContext = 9245 getTagInjectionContext(NewFD->getLexicalDeclContext()); 9246 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 9247 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 9248 9249 // We don't want to reparent enumerators. Look at their parent enum 9250 // instead. 9251 if (!TD) { 9252 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 9253 TD = cast<EnumDecl>(ECD->getDeclContext()); 9254 } 9255 if (!TD) 9256 continue; 9257 DeclContext *TagDC = TD->getLexicalDeclContext(); 9258 if (!TagDC->containsDecl(TD)) 9259 continue; 9260 TagDC->removeDecl(TD); 9261 TD->setDeclContext(NewFD); 9262 NewFD->addDecl(TD); 9263 9264 // Preserve the lexical DeclContext if it is not the surrounding tag 9265 // injection context of the FD. In this example, the semantic context of 9266 // E will be f and the lexical context will be S, while both the 9267 // semantic and lexical contexts of S will be f: 9268 // void f(struct S { enum E { a } f; } s); 9269 if (TagDC != PrototypeTagContext) 9270 TD->setLexicalDeclContext(TagDC); 9271 } 9272 } 9273 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 9274 // When we're declaring a function with a typedef, typeof, etc as in the 9275 // following example, we'll need to synthesize (unnamed) 9276 // parameters for use in the declaration. 9277 // 9278 // @code 9279 // typedef void fn(int); 9280 // fn f; 9281 // @endcode 9282 9283 // Synthesize a parameter for each argument type. 9284 for (const auto &AI : FT->param_types()) { 9285 ParmVarDecl *Param = 9286 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 9287 Param->setScopeInfo(0, Params.size()); 9288 Params.push_back(Param); 9289 } 9290 } else { 9291 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 9292 "Should not need args for typedef of non-prototype fn"); 9293 } 9294 9295 // Finally, we know we have the right number of parameters, install them. 9296 NewFD->setParams(Params); 9297 9298 if (D.getDeclSpec().isNoreturnSpecified()) 9299 NewFD->addAttr(C11NoReturnAttr::Create(Context, 9300 D.getDeclSpec().getNoreturnSpecLoc(), 9301 AttributeCommonInfo::AS_Keyword)); 9302 9303 // Functions returning a variably modified type violate C99 6.7.5.2p2 9304 // because all functions have linkage. 9305 if (!NewFD->isInvalidDecl() && 9306 NewFD->getReturnType()->isVariablyModifiedType()) { 9307 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 9308 NewFD->setInvalidDecl(); 9309 } 9310 9311 // Apply an implicit SectionAttr if '#pragma clang section text' is active 9312 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && 9313 !NewFD->hasAttr<SectionAttr>()) 9314 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit( 9315 Context, PragmaClangTextSection.SectionName, 9316 PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma)); 9317 9318 // Apply an implicit SectionAttr if #pragma code_seg is active. 9319 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 9320 !NewFD->hasAttr<SectionAttr>()) { 9321 NewFD->addAttr(SectionAttr::CreateImplicit( 9322 Context, CodeSegStack.CurrentValue->getString(), 9323 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 9324 SectionAttr::Declspec_allocate)); 9325 if (UnifySection(CodeSegStack.CurrentValue->getString(), 9326 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 9327 ASTContext::PSF_Read, 9328 NewFD)) 9329 NewFD->dropAttr<SectionAttr>(); 9330 } 9331 9332 // Apply an implicit CodeSegAttr from class declspec or 9333 // apply an implicit SectionAttr from #pragma code_seg if active. 9334 if (!NewFD->hasAttr<CodeSegAttr>()) { 9335 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD, 9336 D.isFunctionDefinition())) { 9337 NewFD->addAttr(SAttr); 9338 } 9339 } 9340 9341 // Handle attributes. 9342 ProcessDeclAttributes(S, NewFD, D); 9343 9344 if (getLangOpts().OpenCL) { 9345 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 9346 // type declaration will generate a compilation error. 9347 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); 9348 if (AddressSpace != LangAS::Default) { 9349 Diag(NewFD->getLocation(), 9350 diag::err_opencl_return_value_with_address_space); 9351 NewFD->setInvalidDecl(); 9352 } 9353 } 9354 9355 if (!getLangOpts().CPlusPlus) { 9356 // Perform semantic checking on the function declaration. 9357 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9358 CheckMain(NewFD, D.getDeclSpec()); 9359 9360 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9361 CheckMSVCRTEntryPoint(NewFD); 9362 9363 if (!NewFD->isInvalidDecl()) 9364 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9365 isMemberSpecialization)); 9366 else if (!Previous.empty()) 9367 // Recover gracefully from an invalid redeclaration. 9368 D.setRedeclaration(true); 9369 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9370 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9371 "previous declaration set still overloaded"); 9372 9373 // Diagnose no-prototype function declarations with calling conventions that 9374 // don't support variadic calls. Only do this in C and do it after merging 9375 // possibly prototyped redeclarations. 9376 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 9377 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 9378 CallingConv CC = FT->getExtInfo().getCC(); 9379 if (!supportsVariadicCall(CC)) { 9380 // Windows system headers sometimes accidentally use stdcall without 9381 // (void) parameters, so we relax this to a warning. 9382 int DiagID = 9383 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 9384 Diag(NewFD->getLocation(), DiagID) 9385 << FunctionType::getNameForCallConv(CC); 9386 } 9387 } 9388 9389 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() || 9390 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion()) 9391 checkNonTrivialCUnion(NewFD->getReturnType(), 9392 NewFD->getReturnTypeSourceRange().getBegin(), 9393 NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy); 9394 } else { 9395 // C++11 [replacement.functions]p3: 9396 // The program's definitions shall not be specified as inline. 9397 // 9398 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 9399 // 9400 // Suppress the diagnostic if the function is __attribute__((used)), since 9401 // that forces an external definition to be emitted. 9402 if (D.getDeclSpec().isInlineSpecified() && 9403 NewFD->isReplaceableGlobalAllocationFunction() && 9404 !NewFD->hasAttr<UsedAttr>()) 9405 Diag(D.getDeclSpec().getInlineSpecLoc(), 9406 diag::ext_operator_new_delete_declared_inline) 9407 << NewFD->getDeclName(); 9408 9409 // If the declarator is a template-id, translate the parser's template 9410 // argument list into our AST format. 9411 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 9412 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 9413 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 9414 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 9415 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 9416 TemplateId->NumArgs); 9417 translateTemplateArguments(TemplateArgsPtr, 9418 TemplateArgs); 9419 9420 HasExplicitTemplateArgs = true; 9421 9422 if (NewFD->isInvalidDecl()) { 9423 HasExplicitTemplateArgs = false; 9424 } else if (FunctionTemplate) { 9425 // Function template with explicit template arguments. 9426 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 9427 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 9428 9429 HasExplicitTemplateArgs = false; 9430 } else { 9431 assert((isFunctionTemplateSpecialization || 9432 D.getDeclSpec().isFriendSpecified()) && 9433 "should have a 'template<>' for this decl"); 9434 // "friend void foo<>(int);" is an implicit specialization decl. 9435 isFunctionTemplateSpecialization = true; 9436 } 9437 } else if (isFriend && isFunctionTemplateSpecialization) { 9438 // This combination is only possible in a recovery case; the user 9439 // wrote something like: 9440 // template <> friend void foo(int); 9441 // which we're recovering from as if the user had written: 9442 // friend void foo<>(int); 9443 // Go ahead and fake up a template id. 9444 HasExplicitTemplateArgs = true; 9445 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 9446 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 9447 } 9448 9449 // We do not add HD attributes to specializations here because 9450 // they may have different constexpr-ness compared to their 9451 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 9452 // may end up with different effective targets. Instead, a 9453 // specialization inherits its target attributes from its template 9454 // in the CheckFunctionTemplateSpecialization() call below. 9455 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization) 9456 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 9457 9458 // If it's a friend (and only if it's a friend), it's possible 9459 // that either the specialized function type or the specialized 9460 // template is dependent, and therefore matching will fail. In 9461 // this case, don't check the specialization yet. 9462 bool InstantiationDependent = false; 9463 if (isFunctionTemplateSpecialization && isFriend && 9464 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 9465 TemplateSpecializationType::anyDependentTemplateArguments( 9466 TemplateArgs, 9467 InstantiationDependent))) { 9468 assert(HasExplicitTemplateArgs && 9469 "friend function specialization without template args"); 9470 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 9471 Previous)) 9472 NewFD->setInvalidDecl(); 9473 } else if (isFunctionTemplateSpecialization) { 9474 if (CurContext->isDependentContext() && CurContext->isRecord() 9475 && !isFriend) { 9476 isDependentClassScopeExplicitSpecialization = true; 9477 } else if (!NewFD->isInvalidDecl() && 9478 CheckFunctionTemplateSpecialization( 9479 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), 9480 Previous)) 9481 NewFD->setInvalidDecl(); 9482 9483 // C++ [dcl.stc]p1: 9484 // A storage-class-specifier shall not be specified in an explicit 9485 // specialization (14.7.3) 9486 FunctionTemplateSpecializationInfo *Info = 9487 NewFD->getTemplateSpecializationInfo(); 9488 if (Info && SC != SC_None) { 9489 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 9490 Diag(NewFD->getLocation(), 9491 diag::err_explicit_specialization_inconsistent_storage_class) 9492 << SC 9493 << FixItHint::CreateRemoval( 9494 D.getDeclSpec().getStorageClassSpecLoc()); 9495 9496 else 9497 Diag(NewFD->getLocation(), 9498 diag::ext_explicit_specialization_storage_class) 9499 << FixItHint::CreateRemoval( 9500 D.getDeclSpec().getStorageClassSpecLoc()); 9501 } 9502 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 9503 if (CheckMemberSpecialization(NewFD, Previous)) 9504 NewFD->setInvalidDecl(); 9505 } 9506 9507 // Perform semantic checking on the function declaration. 9508 if (!isDependentClassScopeExplicitSpecialization) { 9509 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9510 CheckMain(NewFD, D.getDeclSpec()); 9511 9512 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9513 CheckMSVCRTEntryPoint(NewFD); 9514 9515 if (!NewFD->isInvalidDecl()) 9516 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9517 isMemberSpecialization)); 9518 else if (!Previous.empty()) 9519 // Recover gracefully from an invalid redeclaration. 9520 D.setRedeclaration(true); 9521 } 9522 9523 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9524 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9525 "previous declaration set still overloaded"); 9526 9527 NamedDecl *PrincipalDecl = (FunctionTemplate 9528 ? cast<NamedDecl>(FunctionTemplate) 9529 : NewFD); 9530 9531 if (isFriend && NewFD->getPreviousDecl()) { 9532 AccessSpecifier Access = AS_public; 9533 if (!NewFD->isInvalidDecl()) 9534 Access = NewFD->getPreviousDecl()->getAccess(); 9535 9536 NewFD->setAccess(Access); 9537 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 9538 } 9539 9540 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 9541 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 9542 PrincipalDecl->setNonMemberOperator(); 9543 9544 // If we have a function template, check the template parameter 9545 // list. This will check and merge default template arguments. 9546 if (FunctionTemplate) { 9547 FunctionTemplateDecl *PrevTemplate = 9548 FunctionTemplate->getPreviousDecl(); 9549 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 9550 PrevTemplate ? PrevTemplate->getTemplateParameters() 9551 : nullptr, 9552 D.getDeclSpec().isFriendSpecified() 9553 ? (D.isFunctionDefinition() 9554 ? TPC_FriendFunctionTemplateDefinition 9555 : TPC_FriendFunctionTemplate) 9556 : (D.getCXXScopeSpec().isSet() && 9557 DC && DC->isRecord() && 9558 DC->isDependentContext()) 9559 ? TPC_ClassTemplateMember 9560 : TPC_FunctionTemplate); 9561 } 9562 9563 if (NewFD->isInvalidDecl()) { 9564 // Ignore all the rest of this. 9565 } else if (!D.isRedeclaration()) { 9566 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 9567 AddToScope }; 9568 // Fake up an access specifier if it's supposed to be a class member. 9569 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 9570 NewFD->setAccess(AS_public); 9571 9572 // Qualified decls generally require a previous declaration. 9573 if (D.getCXXScopeSpec().isSet()) { 9574 // ...with the major exception of templated-scope or 9575 // dependent-scope friend declarations. 9576 9577 // TODO: we currently also suppress this check in dependent 9578 // contexts because (1) the parameter depth will be off when 9579 // matching friend templates and (2) we might actually be 9580 // selecting a friend based on a dependent factor. But there 9581 // are situations where these conditions don't apply and we 9582 // can actually do this check immediately. 9583 // 9584 // Unless the scope is dependent, it's always an error if qualified 9585 // redeclaration lookup found nothing at all. Diagnose that now; 9586 // nothing will diagnose that error later. 9587 if (isFriend && 9588 (D.getCXXScopeSpec().getScopeRep()->isDependent() || 9589 (!Previous.empty() && CurContext->isDependentContext()))) { 9590 // ignore these 9591 } else { 9592 // The user tried to provide an out-of-line definition for a 9593 // function that is a member of a class or namespace, but there 9594 // was no such member function declared (C++ [class.mfct]p2, 9595 // C++ [namespace.memdef]p2). For example: 9596 // 9597 // class X { 9598 // void f() const; 9599 // }; 9600 // 9601 // void X::f() { } // ill-formed 9602 // 9603 // Complain about this problem, and attempt to suggest close 9604 // matches (e.g., those that differ only in cv-qualifiers and 9605 // whether the parameter types are references). 9606 9607 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9608 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 9609 AddToScope = ExtraArgs.AddToScope; 9610 return Result; 9611 } 9612 } 9613 9614 // Unqualified local friend declarations are required to resolve 9615 // to something. 9616 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 9617 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9618 *this, Previous, NewFD, ExtraArgs, true, S)) { 9619 AddToScope = ExtraArgs.AddToScope; 9620 return Result; 9621 } 9622 } 9623 } else if (!D.isFunctionDefinition() && 9624 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 9625 !isFriend && !isFunctionTemplateSpecialization && 9626 !isMemberSpecialization) { 9627 // An out-of-line member function declaration must also be a 9628 // definition (C++ [class.mfct]p2). 9629 // Note that this is not the case for explicit specializations of 9630 // function templates or member functions of class templates, per 9631 // C++ [temp.expl.spec]p2. We also allow these declarations as an 9632 // extension for compatibility with old SWIG code which likes to 9633 // generate them. 9634 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 9635 << D.getCXXScopeSpec().getRange(); 9636 } 9637 } 9638 9639 ProcessPragmaWeak(S, NewFD); 9640 checkAttributesAfterMerging(*this, *NewFD); 9641 9642 AddKnownFunctionAttributes(NewFD); 9643 9644 if (NewFD->hasAttr<OverloadableAttr>() && 9645 !NewFD->getType()->getAs<FunctionProtoType>()) { 9646 Diag(NewFD->getLocation(), 9647 diag::err_attribute_overloadable_no_prototype) 9648 << NewFD; 9649 9650 // Turn this into a variadic function with no parameters. 9651 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 9652 FunctionProtoType::ExtProtoInfo EPI( 9653 Context.getDefaultCallingConvention(true, false)); 9654 EPI.Variadic = true; 9655 EPI.ExtInfo = FT->getExtInfo(); 9656 9657 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 9658 NewFD->setType(R); 9659 } 9660 9661 // If there's a #pragma GCC visibility in scope, and this isn't a class 9662 // member, set the visibility of this function. 9663 if (!DC->isRecord() && NewFD->isExternallyVisible()) 9664 AddPushedVisibilityAttribute(NewFD); 9665 9666 // If there's a #pragma clang arc_cf_code_audited in scope, consider 9667 // marking the function. 9668 AddCFAuditedAttribute(NewFD); 9669 9670 // If this is a function definition, check if we have to apply optnone due to 9671 // a pragma. 9672 if(D.isFunctionDefinition()) 9673 AddRangeBasedOptnone(NewFD); 9674 9675 // If this is the first declaration of an extern C variable, update 9676 // the map of such variables. 9677 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 9678 isIncompleteDeclExternC(*this, NewFD)) 9679 RegisterLocallyScopedExternCDecl(NewFD, S); 9680 9681 // Set this FunctionDecl's range up to the right paren. 9682 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 9683 9684 if (D.isRedeclaration() && !Previous.empty()) { 9685 NamedDecl *Prev = Previous.getRepresentativeDecl(); 9686 checkDLLAttributeRedeclaration(*this, Prev, NewFD, 9687 isMemberSpecialization || 9688 isFunctionTemplateSpecialization, 9689 D.isFunctionDefinition()); 9690 } 9691 9692 if (getLangOpts().CUDA) { 9693 IdentifierInfo *II = NewFD->getIdentifier(); 9694 if (II && II->isStr(getCudaConfigureFuncName()) && 9695 !NewFD->isInvalidDecl() && 9696 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 9697 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 9698 Diag(NewFD->getLocation(), diag::err_config_scalar_return) 9699 << getCudaConfigureFuncName(); 9700 Context.setcudaConfigureCallDecl(NewFD); 9701 } 9702 9703 // Variadic functions, other than a *declaration* of printf, are not allowed 9704 // in device-side CUDA code, unless someone passed 9705 // -fcuda-allow-variadic-functions. 9706 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 9707 (NewFD->hasAttr<CUDADeviceAttr>() || 9708 NewFD->hasAttr<CUDAGlobalAttr>()) && 9709 !(II && II->isStr("printf") && NewFD->isExternC() && 9710 !D.isFunctionDefinition())) { 9711 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 9712 } 9713 } 9714 9715 MarkUnusedFileScopedDecl(NewFD); 9716 9717 9718 9719 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) { 9720 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 9721 if ((getLangOpts().OpenCLVersion >= 120) 9722 && (SC == SC_Static)) { 9723 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 9724 D.setInvalidType(); 9725 } 9726 9727 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 9728 if (!NewFD->getReturnType()->isVoidType()) { 9729 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 9730 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 9731 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 9732 : FixItHint()); 9733 D.setInvalidType(); 9734 } 9735 9736 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 9737 for (auto Param : NewFD->parameters()) 9738 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 9739 9740 if (getLangOpts().OpenCLCPlusPlus) { 9741 if (DC->isRecord()) { 9742 Diag(D.getIdentifierLoc(), diag::err_method_kernel); 9743 D.setInvalidType(); 9744 } 9745 if (FunctionTemplate) { 9746 Diag(D.getIdentifierLoc(), diag::err_template_kernel); 9747 D.setInvalidType(); 9748 } 9749 } 9750 } 9751 9752 if (getLangOpts().CPlusPlus) { 9753 if (FunctionTemplate) { 9754 if (NewFD->isInvalidDecl()) 9755 FunctionTemplate->setInvalidDecl(); 9756 return FunctionTemplate; 9757 } 9758 9759 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 9760 CompleteMemberSpecialization(NewFD, Previous); 9761 } 9762 9763 for (const ParmVarDecl *Param : NewFD->parameters()) { 9764 QualType PT = Param->getType(); 9765 9766 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 9767 // types. 9768 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 9769 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 9770 QualType ElemTy = PipeTy->getElementType(); 9771 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 9772 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 9773 D.setInvalidType(); 9774 } 9775 } 9776 } 9777 } 9778 9779 // Here we have an function template explicit specialization at class scope. 9780 // The actual specialization will be postponed to template instatiation 9781 // time via the ClassScopeFunctionSpecializationDecl node. 9782 if (isDependentClassScopeExplicitSpecialization) { 9783 ClassScopeFunctionSpecializationDecl *NewSpec = 9784 ClassScopeFunctionSpecializationDecl::Create( 9785 Context, CurContext, NewFD->getLocation(), 9786 cast<CXXMethodDecl>(NewFD), 9787 HasExplicitTemplateArgs, TemplateArgs); 9788 CurContext->addDecl(NewSpec); 9789 AddToScope = false; 9790 } 9791 9792 // Diagnose availability attributes. Availability cannot be used on functions 9793 // that are run during load/unload. 9794 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { 9795 if (NewFD->hasAttr<ConstructorAttr>()) { 9796 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9797 << 1; 9798 NewFD->dropAttr<AvailabilityAttr>(); 9799 } 9800 if (NewFD->hasAttr<DestructorAttr>()) { 9801 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9802 << 2; 9803 NewFD->dropAttr<AvailabilityAttr>(); 9804 } 9805 } 9806 9807 // Diagnose no_builtin attribute on function declaration that are not a 9808 // definition. 9809 // FIXME: We should really be doing this in 9810 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to 9811 // the FunctionDecl and at this point of the code 9812 // FunctionDecl::isThisDeclarationADefinition() which always returns `false` 9813 // because Sema::ActOnStartOfFunctionDef has not been called yet. 9814 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>()) 9815 switch (D.getFunctionDefinitionKind()) { 9816 case FDK_Defaulted: 9817 case FDK_Deleted: 9818 Diag(NBA->getLocation(), 9819 diag::err_attribute_no_builtin_on_defaulted_deleted_function) 9820 << NBA->getSpelling(); 9821 break; 9822 case FDK_Declaration: 9823 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition) 9824 << NBA->getSpelling(); 9825 break; 9826 case FDK_Definition: 9827 break; 9828 } 9829 9830 return NewFD; 9831 } 9832 9833 /// Return a CodeSegAttr from a containing class. The Microsoft docs say 9834 /// when __declspec(code_seg) "is applied to a class, all member functions of 9835 /// the class and nested classes -- this includes compiler-generated special 9836 /// member functions -- are put in the specified segment." 9837 /// The actual behavior is a little more complicated. The Microsoft compiler 9838 /// won't check outer classes if there is an active value from #pragma code_seg. 9839 /// The CodeSeg is always applied from the direct parent but only from outer 9840 /// classes when the #pragma code_seg stack is empty. See: 9841 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer 9842 /// available since MS has removed the page. 9843 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) { 9844 const auto *Method = dyn_cast<CXXMethodDecl>(FD); 9845 if (!Method) 9846 return nullptr; 9847 const CXXRecordDecl *Parent = Method->getParent(); 9848 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 9849 Attr *NewAttr = SAttr->clone(S.getASTContext()); 9850 NewAttr->setImplicit(true); 9851 return NewAttr; 9852 } 9853 9854 // The Microsoft compiler won't check outer classes for the CodeSeg 9855 // when the #pragma code_seg stack is active. 9856 if (S.CodeSegStack.CurrentValue) 9857 return nullptr; 9858 9859 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) { 9860 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 9861 Attr *NewAttr = SAttr->clone(S.getASTContext()); 9862 NewAttr->setImplicit(true); 9863 return NewAttr; 9864 } 9865 } 9866 return nullptr; 9867 } 9868 9869 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a 9870 /// containing class. Otherwise it will return implicit SectionAttr if the 9871 /// function is a definition and there is an active value on CodeSegStack 9872 /// (from the current #pragma code-seg value). 9873 /// 9874 /// \param FD Function being declared. 9875 /// \param IsDefinition Whether it is a definition or just a declarartion. 9876 /// \returns A CodeSegAttr or SectionAttr to apply to the function or 9877 /// nullptr if no attribute should be added. 9878 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, 9879 bool IsDefinition) { 9880 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD)) 9881 return A; 9882 if (!FD->hasAttr<SectionAttr>() && IsDefinition && 9883 CodeSegStack.CurrentValue) 9884 return SectionAttr::CreateImplicit( 9885 getASTContext(), CodeSegStack.CurrentValue->getString(), 9886 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 9887 SectionAttr::Declspec_allocate); 9888 return nullptr; 9889 } 9890 9891 /// Determines if we can perform a correct type check for \p D as a 9892 /// redeclaration of \p PrevDecl. If not, we can generally still perform a 9893 /// best-effort check. 9894 /// 9895 /// \param NewD The new declaration. 9896 /// \param OldD The old declaration. 9897 /// \param NewT The portion of the type of the new declaration to check. 9898 /// \param OldT The portion of the type of the old declaration to check. 9899 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, 9900 QualType NewT, QualType OldT) { 9901 if (!NewD->getLexicalDeclContext()->isDependentContext()) 9902 return true; 9903 9904 // For dependently-typed local extern declarations and friends, we can't 9905 // perform a correct type check in general until instantiation: 9906 // 9907 // int f(); 9908 // template<typename T> void g() { T f(); } 9909 // 9910 // (valid if g() is only instantiated with T = int). 9911 if (NewT->isDependentType() && 9912 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind())) 9913 return false; 9914 9915 // Similarly, if the previous declaration was a dependent local extern 9916 // declaration, we don't really know its type yet. 9917 if (OldT->isDependentType() && OldD->isLocalExternDecl()) 9918 return false; 9919 9920 return true; 9921 } 9922 9923 /// Checks if the new declaration declared in dependent context must be 9924 /// put in the same redeclaration chain as the specified declaration. 9925 /// 9926 /// \param D Declaration that is checked. 9927 /// \param PrevDecl Previous declaration found with proper lookup method for the 9928 /// same declaration name. 9929 /// \returns True if D must be added to the redeclaration chain which PrevDecl 9930 /// belongs to. 9931 /// 9932 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 9933 if (!D->getLexicalDeclContext()->isDependentContext()) 9934 return true; 9935 9936 // Don't chain dependent friend function definitions until instantiation, to 9937 // permit cases like 9938 // 9939 // void func(); 9940 // template<typename T> class C1 { friend void func() {} }; 9941 // template<typename T> class C2 { friend void func() {} }; 9942 // 9943 // ... which is valid if only one of C1 and C2 is ever instantiated. 9944 // 9945 // FIXME: This need only apply to function definitions. For now, we proxy 9946 // this by checking for a file-scope function. We do not want this to apply 9947 // to friend declarations nominating member functions, because that gets in 9948 // the way of access checks. 9949 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext()) 9950 return false; 9951 9952 auto *VD = dyn_cast<ValueDecl>(D); 9953 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl); 9954 return !VD || !PrevVD || 9955 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(), 9956 PrevVD->getType()); 9957 } 9958 9959 /// Check the target attribute of the function for MultiVersion 9960 /// validity. 9961 /// 9962 /// Returns true if there was an error, false otherwise. 9963 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { 9964 const auto *TA = FD->getAttr<TargetAttr>(); 9965 assert(TA && "MultiVersion Candidate requires a target attribute"); 9966 ParsedTargetAttr ParseInfo = TA->parse(); 9967 const TargetInfo &TargetInfo = S.Context.getTargetInfo(); 9968 enum ErrType { Feature = 0, Architecture = 1 }; 9969 9970 if (!ParseInfo.Architecture.empty() && 9971 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) { 9972 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9973 << Architecture << ParseInfo.Architecture; 9974 return true; 9975 } 9976 9977 for (const auto &Feat : ParseInfo.Features) { 9978 auto BareFeat = StringRef{Feat}.substr(1); 9979 if (Feat[0] == '-') { 9980 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9981 << Feature << ("no-" + BareFeat).str(); 9982 return true; 9983 } 9984 9985 if (!TargetInfo.validateCpuSupports(BareFeat) || 9986 !TargetInfo.isValidFeatureName(BareFeat)) { 9987 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9988 << Feature << BareFeat; 9989 return true; 9990 } 9991 } 9992 return false; 9993 } 9994 9995 // Provide a white-list of attributes that are allowed to be combined with 9996 // multiversion functions. 9997 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, 9998 MultiVersionKind MVType) { 9999 switch (Kind) { 10000 default: 10001 return false; 10002 case attr::Used: 10003 return MVType == MultiVersionKind::Target; 10004 } 10005 } 10006 10007 static bool HasNonMultiVersionAttributes(const FunctionDecl *FD, 10008 MultiVersionKind MVType) { 10009 for (const Attr *A : FD->attrs()) { 10010 switch (A->getKind()) { 10011 case attr::CPUDispatch: 10012 case attr::CPUSpecific: 10013 if (MVType != MultiVersionKind::CPUDispatch && 10014 MVType != MultiVersionKind::CPUSpecific) 10015 return true; 10016 break; 10017 case attr::Target: 10018 if (MVType != MultiVersionKind::Target) 10019 return true; 10020 break; 10021 default: 10022 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType)) 10023 return true; 10024 break; 10025 } 10026 } 10027 return false; 10028 } 10029 10030 bool Sema::areMultiversionVariantFunctionsCompatible( 10031 const FunctionDecl *OldFD, const FunctionDecl *NewFD, 10032 const PartialDiagnostic &NoProtoDiagID, 10033 const PartialDiagnosticAt &NoteCausedDiagIDAt, 10034 const PartialDiagnosticAt &NoSupportDiagIDAt, 10035 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, 10036 bool ConstexprSupported, bool CLinkageMayDiffer) { 10037 enum DoesntSupport { 10038 FuncTemplates = 0, 10039 VirtFuncs = 1, 10040 DeducedReturn = 2, 10041 Constructors = 3, 10042 Destructors = 4, 10043 DeletedFuncs = 5, 10044 DefaultedFuncs = 6, 10045 ConstexprFuncs = 7, 10046 ConstevalFuncs = 8, 10047 }; 10048 enum Different { 10049 CallingConv = 0, 10050 ReturnType = 1, 10051 ConstexprSpec = 2, 10052 InlineSpec = 3, 10053 StorageClass = 4, 10054 Linkage = 5, 10055 }; 10056 10057 if (NoProtoDiagID.getDiagID() != 0 && OldFD && 10058 !OldFD->getType()->getAs<FunctionProtoType>()) { 10059 Diag(OldFD->getLocation(), NoProtoDiagID); 10060 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second); 10061 return true; 10062 } 10063 10064 if (NoProtoDiagID.getDiagID() != 0 && 10065 !NewFD->getType()->getAs<FunctionProtoType>()) 10066 return Diag(NewFD->getLocation(), NoProtoDiagID); 10067 10068 if (!TemplatesSupported && 10069 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 10070 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10071 << FuncTemplates; 10072 10073 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { 10074 if (NewCXXFD->isVirtual()) 10075 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10076 << VirtFuncs; 10077 10078 if (isa<CXXConstructorDecl>(NewCXXFD)) 10079 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10080 << Constructors; 10081 10082 if (isa<CXXDestructorDecl>(NewCXXFD)) 10083 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10084 << Destructors; 10085 } 10086 10087 if (NewFD->isDeleted()) 10088 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10089 << DeletedFuncs; 10090 10091 if (NewFD->isDefaulted()) 10092 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10093 << DefaultedFuncs; 10094 10095 if (!ConstexprSupported && NewFD->isConstexpr()) 10096 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10097 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs); 10098 10099 QualType NewQType = Context.getCanonicalType(NewFD->getType()); 10100 const auto *NewType = cast<FunctionType>(NewQType); 10101 QualType NewReturnType = NewType->getReturnType(); 10102 10103 if (NewReturnType->isUndeducedType()) 10104 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10105 << DeducedReturn; 10106 10107 // Ensure the return type is identical. 10108 if (OldFD) { 10109 QualType OldQType = Context.getCanonicalType(OldFD->getType()); 10110 const auto *OldType = cast<FunctionType>(OldQType); 10111 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 10112 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 10113 10114 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) 10115 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv; 10116 10117 QualType OldReturnType = OldType->getReturnType(); 10118 10119 if (OldReturnType != NewReturnType) 10120 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType; 10121 10122 if (OldFD->getConstexprKind() != NewFD->getConstexprKind()) 10123 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec; 10124 10125 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) 10126 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec; 10127 10128 if (OldFD->getStorageClass() != NewFD->getStorageClass()) 10129 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass; 10130 10131 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC()) 10132 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage; 10133 10134 if (CheckEquivalentExceptionSpec( 10135 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), 10136 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) 10137 return true; 10138 } 10139 return false; 10140 } 10141 10142 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, 10143 const FunctionDecl *NewFD, 10144 bool CausesMV, 10145 MultiVersionKind MVType) { 10146 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10147 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10148 if (OldFD) 10149 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10150 return true; 10151 } 10152 10153 bool IsCPUSpecificCPUDispatchMVType = 10154 MVType == MultiVersionKind::CPUDispatch || 10155 MVType == MultiVersionKind::CPUSpecific; 10156 10157 // For now, disallow all other attributes. These should be opt-in, but 10158 // an analysis of all of them is a future FIXME. 10159 if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) { 10160 S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs) 10161 << IsCPUSpecificCPUDispatchMVType; 10162 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10163 return true; 10164 } 10165 10166 if (HasNonMultiVersionAttributes(NewFD, MVType)) 10167 return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs) 10168 << IsCPUSpecificCPUDispatchMVType; 10169 10170 // Only allow transition to MultiVersion if it hasn't been used. 10171 if (OldFD && CausesMV && OldFD->isUsed(false)) 10172 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 10173 10174 return S.areMultiversionVariantFunctionsCompatible( 10175 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto), 10176 PartialDiagnosticAt(NewFD->getLocation(), 10177 S.PDiag(diag::note_multiversioning_caused_here)), 10178 PartialDiagnosticAt(NewFD->getLocation(), 10179 S.PDiag(diag::err_multiversion_doesnt_support) 10180 << IsCPUSpecificCPUDispatchMVType), 10181 PartialDiagnosticAt(NewFD->getLocation(), 10182 S.PDiag(diag::err_multiversion_diff)), 10183 /*TemplatesSupported=*/false, 10184 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType, 10185 /*CLinkageMayDiffer=*/false); 10186 } 10187 10188 /// Check the validity of a multiversion function declaration that is the 10189 /// first of its kind. Also sets the multiversion'ness' of the function itself. 10190 /// 10191 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10192 /// 10193 /// Returns true if there was an error, false otherwise. 10194 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD, 10195 MultiVersionKind MVType, 10196 const TargetAttr *TA) { 10197 assert(MVType != MultiVersionKind::None && 10198 "Function lacks multiversion attribute"); 10199 10200 // Target only causes MV if it is default, otherwise this is a normal 10201 // function. 10202 if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion()) 10203 return false; 10204 10205 if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) { 10206 FD->setInvalidDecl(); 10207 return true; 10208 } 10209 10210 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) { 10211 FD->setInvalidDecl(); 10212 return true; 10213 } 10214 10215 FD->setIsMultiVersion(); 10216 return false; 10217 } 10218 10219 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) { 10220 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) { 10221 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None) 10222 return true; 10223 } 10224 10225 return false; 10226 } 10227 10228 static bool CheckTargetCausesMultiVersioning( 10229 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA, 10230 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 10231 LookupResult &Previous) { 10232 const auto *OldTA = OldFD->getAttr<TargetAttr>(); 10233 ParsedTargetAttr NewParsed = NewTA->parse(); 10234 // Sort order doesn't matter, it just needs to be consistent. 10235 llvm::sort(NewParsed.Features); 10236 10237 // If the old decl is NOT MultiVersioned yet, and we don't cause that 10238 // to change, this is a simple redeclaration. 10239 if (!NewTA->isDefaultVersion() && 10240 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) 10241 return false; 10242 10243 // Otherwise, this decl causes MultiVersioning. 10244 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10245 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10246 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10247 NewFD->setInvalidDecl(); 10248 return true; 10249 } 10250 10251 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true, 10252 MultiVersionKind::Target)) { 10253 NewFD->setInvalidDecl(); 10254 return true; 10255 } 10256 10257 if (CheckMultiVersionValue(S, NewFD)) { 10258 NewFD->setInvalidDecl(); 10259 return true; 10260 } 10261 10262 // If this is 'default', permit the forward declaration. 10263 if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) { 10264 Redeclaration = true; 10265 OldDecl = OldFD; 10266 OldFD->setIsMultiVersion(); 10267 NewFD->setIsMultiVersion(); 10268 return false; 10269 } 10270 10271 if (CheckMultiVersionValue(S, OldFD)) { 10272 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10273 NewFD->setInvalidDecl(); 10274 return true; 10275 } 10276 10277 ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>()); 10278 10279 if (OldParsed == NewParsed) { 10280 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10281 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10282 NewFD->setInvalidDecl(); 10283 return true; 10284 } 10285 10286 for (const auto *FD : OldFD->redecls()) { 10287 const auto *CurTA = FD->getAttr<TargetAttr>(); 10288 // We allow forward declarations before ANY multiversioning attributes, but 10289 // nothing after the fact. 10290 if (PreviousDeclsHaveMultiVersionAttribute(FD) && 10291 (!CurTA || CurTA->isInherited())) { 10292 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl) 10293 << 0; 10294 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10295 NewFD->setInvalidDecl(); 10296 return true; 10297 } 10298 } 10299 10300 OldFD->setIsMultiVersion(); 10301 NewFD->setIsMultiVersion(); 10302 Redeclaration = false; 10303 MergeTypeWithPrevious = false; 10304 OldDecl = nullptr; 10305 Previous.clear(); 10306 return false; 10307 } 10308 10309 /// Check the validity of a new function declaration being added to an existing 10310 /// multiversioned declaration collection. 10311 static bool CheckMultiVersionAdditionalDecl( 10312 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, 10313 MultiVersionKind NewMVType, const TargetAttr *NewTA, 10314 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, 10315 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 10316 LookupResult &Previous) { 10317 10318 MultiVersionKind OldMVType = OldFD->getMultiVersionKind(); 10319 // Disallow mixing of multiversioning types. 10320 if ((OldMVType == MultiVersionKind::Target && 10321 NewMVType != MultiVersionKind::Target) || 10322 (NewMVType == MultiVersionKind::Target && 10323 OldMVType != MultiVersionKind::Target)) { 10324 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10325 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10326 NewFD->setInvalidDecl(); 10327 return true; 10328 } 10329 10330 ParsedTargetAttr NewParsed; 10331 if (NewTA) { 10332 NewParsed = NewTA->parse(); 10333 llvm::sort(NewParsed.Features); 10334 } 10335 10336 bool UseMemberUsingDeclRules = 10337 S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); 10338 10339 // Next, check ALL non-overloads to see if this is a redeclaration of a 10340 // previous member of the MultiVersion set. 10341 for (NamedDecl *ND : Previous) { 10342 FunctionDecl *CurFD = ND->getAsFunction(); 10343 if (!CurFD) 10344 continue; 10345 if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) 10346 continue; 10347 10348 if (NewMVType == MultiVersionKind::Target) { 10349 const auto *CurTA = CurFD->getAttr<TargetAttr>(); 10350 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { 10351 NewFD->setIsMultiVersion(); 10352 Redeclaration = true; 10353 OldDecl = ND; 10354 return false; 10355 } 10356 10357 ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>()); 10358 if (CurParsed == NewParsed) { 10359 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10360 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10361 NewFD->setInvalidDecl(); 10362 return true; 10363 } 10364 } else { 10365 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>(); 10366 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>(); 10367 // Handle CPUDispatch/CPUSpecific versions. 10368 // Only 1 CPUDispatch function is allowed, this will make it go through 10369 // the redeclaration errors. 10370 if (NewMVType == MultiVersionKind::CPUDispatch && 10371 CurFD->hasAttr<CPUDispatchAttr>()) { 10372 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() && 10373 std::equal( 10374 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(), 10375 NewCPUDisp->cpus_begin(), 10376 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10377 return Cur->getName() == New->getName(); 10378 })) { 10379 NewFD->setIsMultiVersion(); 10380 Redeclaration = true; 10381 OldDecl = ND; 10382 return false; 10383 } 10384 10385 // If the declarations don't match, this is an error condition. 10386 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch); 10387 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10388 NewFD->setInvalidDecl(); 10389 return true; 10390 } 10391 if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) { 10392 10393 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() && 10394 std::equal( 10395 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(), 10396 NewCPUSpec->cpus_begin(), 10397 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10398 return Cur->getName() == New->getName(); 10399 })) { 10400 NewFD->setIsMultiVersion(); 10401 Redeclaration = true; 10402 OldDecl = ND; 10403 return false; 10404 } 10405 10406 // Only 1 version of CPUSpecific is allowed for each CPU. 10407 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) { 10408 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) { 10409 if (CurII == NewII) { 10410 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs) 10411 << NewII; 10412 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10413 NewFD->setInvalidDecl(); 10414 return true; 10415 } 10416 } 10417 } 10418 } 10419 // If the two decls aren't the same MVType, there is no possible error 10420 // condition. 10421 } 10422 } 10423 10424 // Else, this is simply a non-redecl case. Checking the 'value' is only 10425 // necessary in the Target case, since The CPUSpecific/Dispatch cases are 10426 // handled in the attribute adding step. 10427 if (NewMVType == MultiVersionKind::Target && 10428 CheckMultiVersionValue(S, NewFD)) { 10429 NewFD->setInvalidDecl(); 10430 return true; 10431 } 10432 10433 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, 10434 !OldFD->isMultiVersion(), NewMVType)) { 10435 NewFD->setInvalidDecl(); 10436 return true; 10437 } 10438 10439 // Permit forward declarations in the case where these two are compatible. 10440 if (!OldFD->isMultiVersion()) { 10441 OldFD->setIsMultiVersion(); 10442 NewFD->setIsMultiVersion(); 10443 Redeclaration = true; 10444 OldDecl = OldFD; 10445 return false; 10446 } 10447 10448 NewFD->setIsMultiVersion(); 10449 Redeclaration = false; 10450 MergeTypeWithPrevious = false; 10451 OldDecl = nullptr; 10452 Previous.clear(); 10453 return false; 10454 } 10455 10456 10457 /// Check the validity of a mulitversion function declaration. 10458 /// Also sets the multiversion'ness' of the function itself. 10459 /// 10460 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10461 /// 10462 /// Returns true if there was an error, false otherwise. 10463 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, 10464 bool &Redeclaration, NamedDecl *&OldDecl, 10465 bool &MergeTypeWithPrevious, 10466 LookupResult &Previous) { 10467 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 10468 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>(); 10469 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>(); 10470 10471 // Mixing Multiversioning types is prohibited. 10472 if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) || 10473 (NewCPUDisp && NewCPUSpec)) { 10474 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10475 NewFD->setInvalidDecl(); 10476 return true; 10477 } 10478 10479 MultiVersionKind MVType = NewFD->getMultiVersionKind(); 10480 10481 // Main isn't allowed to become a multiversion function, however it IS 10482 // permitted to have 'main' be marked with the 'target' optimization hint. 10483 if (NewFD->isMain()) { 10484 if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) || 10485 MVType == MultiVersionKind::CPUDispatch || 10486 MVType == MultiVersionKind::CPUSpecific) { 10487 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); 10488 NewFD->setInvalidDecl(); 10489 return true; 10490 } 10491 return false; 10492 } 10493 10494 if (!OldDecl || !OldDecl->getAsFunction() || 10495 OldDecl->getDeclContext()->getRedeclContext() != 10496 NewFD->getDeclContext()->getRedeclContext()) { 10497 // If there's no previous declaration, AND this isn't attempting to cause 10498 // multiversioning, this isn't an error condition. 10499 if (MVType == MultiVersionKind::None) 10500 return false; 10501 return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA); 10502 } 10503 10504 FunctionDecl *OldFD = OldDecl->getAsFunction(); 10505 10506 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None) 10507 return false; 10508 10509 if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) { 10510 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl) 10511 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target); 10512 NewFD->setInvalidDecl(); 10513 return true; 10514 } 10515 10516 // Handle the target potentially causes multiversioning case. 10517 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target) 10518 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA, 10519 Redeclaration, OldDecl, 10520 MergeTypeWithPrevious, Previous); 10521 10522 // At this point, we have a multiversion function decl (in OldFD) AND an 10523 // appropriate attribute in the current function decl. Resolve that these are 10524 // still compatible with previous declarations. 10525 return CheckMultiVersionAdditionalDecl( 10526 S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration, 10527 OldDecl, MergeTypeWithPrevious, Previous); 10528 } 10529 10530 /// Perform semantic checking of a new function declaration. 10531 /// 10532 /// Performs semantic analysis of the new function declaration 10533 /// NewFD. This routine performs all semantic checking that does not 10534 /// require the actual declarator involved in the declaration, and is 10535 /// used both for the declaration of functions as they are parsed 10536 /// (called via ActOnDeclarator) and for the declaration of functions 10537 /// that have been instantiated via C++ template instantiation (called 10538 /// via InstantiateDecl). 10539 /// 10540 /// \param IsMemberSpecialization whether this new function declaration is 10541 /// a member specialization (that replaces any definition provided by the 10542 /// previous declaration). 10543 /// 10544 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10545 /// 10546 /// \returns true if the function declaration is a redeclaration. 10547 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 10548 LookupResult &Previous, 10549 bool IsMemberSpecialization) { 10550 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 10551 "Variably modified return types are not handled here"); 10552 10553 // Determine whether the type of this function should be merged with 10554 // a previous visible declaration. This never happens for functions in C++, 10555 // and always happens in C if the previous declaration was visible. 10556 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 10557 !Previous.isShadowed(); 10558 10559 bool Redeclaration = false; 10560 NamedDecl *OldDecl = nullptr; 10561 bool MayNeedOverloadableChecks = false; 10562 10563 // Merge or overload the declaration with an existing declaration of 10564 // the same name, if appropriate. 10565 if (!Previous.empty()) { 10566 // Determine whether NewFD is an overload of PrevDecl or 10567 // a declaration that requires merging. If it's an overload, 10568 // there's no more work to do here; we'll just add the new 10569 // function to the scope. 10570 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { 10571 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 10572 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 10573 Redeclaration = true; 10574 OldDecl = Candidate; 10575 } 10576 } else { 10577 MayNeedOverloadableChecks = true; 10578 switch (CheckOverload(S, NewFD, Previous, OldDecl, 10579 /*NewIsUsingDecl*/ false)) { 10580 case Ovl_Match: 10581 Redeclaration = true; 10582 break; 10583 10584 case Ovl_NonFunction: 10585 Redeclaration = true; 10586 break; 10587 10588 case Ovl_Overload: 10589 Redeclaration = false; 10590 break; 10591 } 10592 } 10593 } 10594 10595 // Check for a previous extern "C" declaration with this name. 10596 if (!Redeclaration && 10597 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 10598 if (!Previous.empty()) { 10599 // This is an extern "C" declaration with the same name as a previous 10600 // declaration, and thus redeclares that entity... 10601 Redeclaration = true; 10602 OldDecl = Previous.getFoundDecl(); 10603 MergeTypeWithPrevious = false; 10604 10605 // ... except in the presence of __attribute__((overloadable)). 10606 if (OldDecl->hasAttr<OverloadableAttr>() || 10607 NewFD->hasAttr<OverloadableAttr>()) { 10608 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 10609 MayNeedOverloadableChecks = true; 10610 Redeclaration = false; 10611 OldDecl = nullptr; 10612 } 10613 } 10614 } 10615 } 10616 10617 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, 10618 MergeTypeWithPrevious, Previous)) 10619 return Redeclaration; 10620 10621 // C++11 [dcl.constexpr]p8: 10622 // A constexpr specifier for a non-static member function that is not 10623 // a constructor declares that member function to be const. 10624 // 10625 // This needs to be delayed until we know whether this is an out-of-line 10626 // definition of a static member function. 10627 // 10628 // This rule is not present in C++1y, so we produce a backwards 10629 // compatibility warning whenever it happens in C++11. 10630 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 10631 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 10632 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 10633 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) { 10634 CXXMethodDecl *OldMD = nullptr; 10635 if (OldDecl) 10636 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 10637 if (!OldMD || !OldMD->isStatic()) { 10638 const FunctionProtoType *FPT = 10639 MD->getType()->castAs<FunctionProtoType>(); 10640 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10641 EPI.TypeQuals.addConst(); 10642 MD->setType(Context.getFunctionType(FPT->getReturnType(), 10643 FPT->getParamTypes(), EPI)); 10644 10645 // Warn that we did this, if we're not performing template instantiation. 10646 // In that case, we'll have warned already when the template was defined. 10647 if (!inTemplateInstantiation()) { 10648 SourceLocation AddConstLoc; 10649 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 10650 .IgnoreParens().getAs<FunctionTypeLoc>()) 10651 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 10652 10653 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 10654 << FixItHint::CreateInsertion(AddConstLoc, " const"); 10655 } 10656 } 10657 } 10658 10659 if (Redeclaration) { 10660 // NewFD and OldDecl represent declarations that need to be 10661 // merged. 10662 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 10663 NewFD->setInvalidDecl(); 10664 return Redeclaration; 10665 } 10666 10667 Previous.clear(); 10668 Previous.addDecl(OldDecl); 10669 10670 if (FunctionTemplateDecl *OldTemplateDecl = 10671 dyn_cast<FunctionTemplateDecl>(OldDecl)) { 10672 auto *OldFD = OldTemplateDecl->getTemplatedDecl(); 10673 FunctionTemplateDecl *NewTemplateDecl 10674 = NewFD->getDescribedFunctionTemplate(); 10675 assert(NewTemplateDecl && "Template/non-template mismatch"); 10676 10677 // The call to MergeFunctionDecl above may have created some state in 10678 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we 10679 // can add it as a redeclaration. 10680 NewTemplateDecl->mergePrevDecl(OldTemplateDecl); 10681 10682 NewFD->setPreviousDeclaration(OldFD); 10683 adjustDeclContextForDeclaratorDecl(NewFD, OldFD); 10684 if (NewFD->isCXXClassMember()) { 10685 NewFD->setAccess(OldTemplateDecl->getAccess()); 10686 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 10687 } 10688 10689 // If this is an explicit specialization of a member that is a function 10690 // template, mark it as a member specialization. 10691 if (IsMemberSpecialization && 10692 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 10693 NewTemplateDecl->setMemberSpecialization(); 10694 assert(OldTemplateDecl->isMemberSpecialization()); 10695 // Explicit specializations of a member template do not inherit deleted 10696 // status from the parent member template that they are specializing. 10697 if (OldFD->isDeleted()) { 10698 // FIXME: This assert will not hold in the presence of modules. 10699 assert(OldFD->getCanonicalDecl() == OldFD); 10700 // FIXME: We need an update record for this AST mutation. 10701 OldFD->setDeletedAsWritten(false); 10702 } 10703 } 10704 10705 } else { 10706 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 10707 auto *OldFD = cast<FunctionDecl>(OldDecl); 10708 // This needs to happen first so that 'inline' propagates. 10709 NewFD->setPreviousDeclaration(OldFD); 10710 adjustDeclContextForDeclaratorDecl(NewFD, OldFD); 10711 if (NewFD->isCXXClassMember()) 10712 NewFD->setAccess(OldFD->getAccess()); 10713 } 10714 } 10715 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && 10716 !NewFD->getAttr<OverloadableAttr>()) { 10717 assert((Previous.empty() || 10718 llvm::any_of(Previous, 10719 [](const NamedDecl *ND) { 10720 return ND->hasAttr<OverloadableAttr>(); 10721 })) && 10722 "Non-redecls shouldn't happen without overloadable present"); 10723 10724 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { 10725 const auto *FD = dyn_cast<FunctionDecl>(ND); 10726 return FD && !FD->hasAttr<OverloadableAttr>(); 10727 }); 10728 10729 if (OtherUnmarkedIter != Previous.end()) { 10730 Diag(NewFD->getLocation(), 10731 diag::err_attribute_overloadable_multiple_unmarked_overloads); 10732 Diag((*OtherUnmarkedIter)->getLocation(), 10733 diag::note_attribute_overloadable_prev_overload) 10734 << false; 10735 10736 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 10737 } 10738 } 10739 10740 // Semantic checking for this function declaration (in isolation). 10741 10742 if (getLangOpts().CPlusPlus) { 10743 // C++-specific checks. 10744 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 10745 CheckConstructor(Constructor); 10746 } else if (CXXDestructorDecl *Destructor = 10747 dyn_cast<CXXDestructorDecl>(NewFD)) { 10748 CXXRecordDecl *Record = Destructor->getParent(); 10749 QualType ClassType = Context.getTypeDeclType(Record); 10750 10751 // FIXME: Shouldn't we be able to perform this check even when the class 10752 // type is dependent? Both gcc and edg can handle that. 10753 if (!ClassType->isDependentType()) { 10754 DeclarationName Name 10755 = Context.DeclarationNames.getCXXDestructorName( 10756 Context.getCanonicalType(ClassType)); 10757 if (NewFD->getDeclName() != Name) { 10758 Diag(NewFD->getLocation(), diag::err_destructor_name); 10759 NewFD->setInvalidDecl(); 10760 return Redeclaration; 10761 } 10762 } 10763 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 10764 if (auto *TD = Guide->getDescribedFunctionTemplate()) 10765 CheckDeductionGuideTemplate(TD); 10766 10767 // A deduction guide is not on the list of entities that can be 10768 // explicitly specialized. 10769 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 10770 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized) 10771 << /*explicit specialization*/ 1; 10772 } 10773 10774 // Find any virtual functions that this function overrides. 10775 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 10776 if (!Method->isFunctionTemplateSpecialization() && 10777 !Method->getDescribedFunctionTemplate() && 10778 Method->isCanonicalDecl()) { 10779 AddOverriddenMethods(Method->getParent(), Method); 10780 } 10781 if (Method->isVirtual() && NewFD->getTrailingRequiresClause()) 10782 // C++2a [class.virtual]p6 10783 // A virtual method shall not have a requires-clause. 10784 Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(), 10785 diag::err_constrained_virtual_method); 10786 10787 if (Method->isStatic()) 10788 checkThisInStaticMemberFunctionType(Method); 10789 } 10790 10791 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD)) 10792 ActOnConversionDeclarator(Conversion); 10793 10794 // Extra checking for C++ overloaded operators (C++ [over.oper]). 10795 if (NewFD->isOverloadedOperator() && 10796 CheckOverloadedOperatorDeclaration(NewFD)) { 10797 NewFD->setInvalidDecl(); 10798 return Redeclaration; 10799 } 10800 10801 // Extra checking for C++0x literal operators (C++0x [over.literal]). 10802 if (NewFD->getLiteralIdentifier() && 10803 CheckLiteralOperatorDeclaration(NewFD)) { 10804 NewFD->setInvalidDecl(); 10805 return Redeclaration; 10806 } 10807 10808 // In C++, check default arguments now that we have merged decls. Unless 10809 // the lexical context is the class, because in this case this is done 10810 // during delayed parsing anyway. 10811 if (!CurContext->isRecord()) 10812 CheckCXXDefaultArguments(NewFD); 10813 10814 // If this function declares a builtin function, check the type of this 10815 // declaration against the expected type for the builtin. 10816 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 10817 ASTContext::GetBuiltinTypeError Error; 10818 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 10819 QualType T = Context.GetBuiltinType(BuiltinID, Error); 10820 // If the type of the builtin differs only in its exception 10821 // specification, that's OK. 10822 // FIXME: If the types do differ in this way, it would be better to 10823 // retain the 'noexcept' form of the type. 10824 if (!T.isNull() && 10825 !Context.hasSameFunctionTypeIgnoringExceptionSpec(T, 10826 NewFD->getType())) 10827 // The type of this function differs from the type of the builtin, 10828 // so forget about the builtin entirely. 10829 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); 10830 } 10831 10832 // If this function is declared as being extern "C", then check to see if 10833 // the function returns a UDT (class, struct, or union type) that is not C 10834 // compatible, and if it does, warn the user. 10835 // But, issue any diagnostic on the first declaration only. 10836 if (Previous.empty() && NewFD->isExternC()) { 10837 QualType R = NewFD->getReturnType(); 10838 if (R->isIncompleteType() && !R->isVoidType()) 10839 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 10840 << NewFD << R; 10841 else if (!R.isPODType(Context) && !R->isVoidType() && 10842 !R->isObjCObjectPointerType()) 10843 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 10844 } 10845 10846 // C++1z [dcl.fct]p6: 10847 // [...] whether the function has a non-throwing exception-specification 10848 // [is] part of the function type 10849 // 10850 // This results in an ABI break between C++14 and C++17 for functions whose 10851 // declared type includes an exception-specification in a parameter or 10852 // return type. (Exception specifications on the function itself are OK in 10853 // most cases, and exception specifications are not permitted in most other 10854 // contexts where they could make it into a mangling.) 10855 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { 10856 auto HasNoexcept = [&](QualType T) -> bool { 10857 // Strip off declarator chunks that could be between us and a function 10858 // type. We don't need to look far, exception specifications are very 10859 // restricted prior to C++17. 10860 if (auto *RT = T->getAs<ReferenceType>()) 10861 T = RT->getPointeeType(); 10862 else if (T->isAnyPointerType()) 10863 T = T->getPointeeType(); 10864 else if (auto *MPT = T->getAs<MemberPointerType>()) 10865 T = MPT->getPointeeType(); 10866 if (auto *FPT = T->getAs<FunctionProtoType>()) 10867 if (FPT->isNothrow()) 10868 return true; 10869 return false; 10870 }; 10871 10872 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 10873 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 10874 for (QualType T : FPT->param_types()) 10875 AnyNoexcept |= HasNoexcept(T); 10876 if (AnyNoexcept) 10877 Diag(NewFD->getLocation(), 10878 diag::warn_cxx17_compat_exception_spec_in_signature) 10879 << NewFD; 10880 } 10881 10882 if (!Redeclaration && LangOpts.CUDA) 10883 checkCUDATargetOverload(NewFD, Previous); 10884 } 10885 return Redeclaration; 10886 } 10887 10888 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 10889 // C++11 [basic.start.main]p3: 10890 // A program that [...] declares main to be inline, static or 10891 // constexpr is ill-formed. 10892 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 10893 // appear in a declaration of main. 10894 // static main is not an error under C99, but we should warn about it. 10895 // We accept _Noreturn main as an extension. 10896 if (FD->getStorageClass() == SC_Static) 10897 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 10898 ? diag::err_static_main : diag::warn_static_main) 10899 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 10900 if (FD->isInlineSpecified()) 10901 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 10902 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 10903 if (DS.isNoreturnSpecified()) { 10904 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 10905 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 10906 Diag(NoreturnLoc, diag::ext_noreturn_main); 10907 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 10908 << FixItHint::CreateRemoval(NoreturnRange); 10909 } 10910 if (FD->isConstexpr()) { 10911 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 10912 << FD->isConsteval() 10913 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 10914 FD->setConstexprKind(CSK_unspecified); 10915 } 10916 10917 if (getLangOpts().OpenCL) { 10918 Diag(FD->getLocation(), diag::err_opencl_no_main) 10919 << FD->hasAttr<OpenCLKernelAttr>(); 10920 FD->setInvalidDecl(); 10921 return; 10922 } 10923 10924 QualType T = FD->getType(); 10925 assert(T->isFunctionType() && "function decl is not of function type"); 10926 const FunctionType* FT = T->castAs<FunctionType>(); 10927 10928 // Set default calling convention for main() 10929 if (FT->getCallConv() != CC_C) { 10930 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); 10931 FD->setType(QualType(FT, 0)); 10932 T = Context.getCanonicalType(FD->getType()); 10933 } 10934 10935 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 10936 // In C with GNU extensions we allow main() to have non-integer return 10937 // type, but we should warn about the extension, and we disable the 10938 // implicit-return-zero rule. 10939 10940 // GCC in C mode accepts qualified 'int'. 10941 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 10942 FD->setHasImplicitReturnZero(true); 10943 else { 10944 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 10945 SourceRange RTRange = FD->getReturnTypeSourceRange(); 10946 if (RTRange.isValid()) 10947 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 10948 << FixItHint::CreateReplacement(RTRange, "int"); 10949 } 10950 } else { 10951 // In C and C++, main magically returns 0 if you fall off the end; 10952 // set the flag which tells us that. 10953 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 10954 10955 // All the standards say that main() should return 'int'. 10956 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 10957 FD->setHasImplicitReturnZero(true); 10958 else { 10959 // Otherwise, this is just a flat-out error. 10960 SourceRange RTRange = FD->getReturnTypeSourceRange(); 10961 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 10962 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 10963 : FixItHint()); 10964 FD->setInvalidDecl(true); 10965 } 10966 } 10967 10968 // Treat protoless main() as nullary. 10969 if (isa<FunctionNoProtoType>(FT)) return; 10970 10971 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 10972 unsigned nparams = FTP->getNumParams(); 10973 assert(FD->getNumParams() == nparams); 10974 10975 bool HasExtraParameters = (nparams > 3); 10976 10977 if (FTP->isVariadic()) { 10978 Diag(FD->getLocation(), diag::ext_variadic_main); 10979 // FIXME: if we had information about the location of the ellipsis, we 10980 // could add a FixIt hint to remove it as a parameter. 10981 } 10982 10983 // Darwin passes an undocumented fourth argument of type char**. If 10984 // other platforms start sprouting these, the logic below will start 10985 // getting shifty. 10986 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 10987 HasExtraParameters = false; 10988 10989 if (HasExtraParameters) { 10990 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 10991 FD->setInvalidDecl(true); 10992 nparams = 3; 10993 } 10994 10995 // FIXME: a lot of the following diagnostics would be improved 10996 // if we had some location information about types. 10997 10998 QualType CharPP = 10999 Context.getPointerType(Context.getPointerType(Context.CharTy)); 11000 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 11001 11002 for (unsigned i = 0; i < nparams; ++i) { 11003 QualType AT = FTP->getParamType(i); 11004 11005 bool mismatch = true; 11006 11007 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 11008 mismatch = false; 11009 else if (Expected[i] == CharPP) { 11010 // As an extension, the following forms are okay: 11011 // char const ** 11012 // char const * const * 11013 // char * const * 11014 11015 QualifierCollector qs; 11016 const PointerType* PT; 11017 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 11018 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 11019 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 11020 Context.CharTy)) { 11021 qs.removeConst(); 11022 mismatch = !qs.empty(); 11023 } 11024 } 11025 11026 if (mismatch) { 11027 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 11028 // TODO: suggest replacing given type with expected type 11029 FD->setInvalidDecl(true); 11030 } 11031 } 11032 11033 if (nparams == 1 && !FD->isInvalidDecl()) { 11034 Diag(FD->getLocation(), diag::warn_main_one_arg); 11035 } 11036 11037 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11038 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11039 FD->setInvalidDecl(); 11040 } 11041 } 11042 11043 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 11044 QualType T = FD->getType(); 11045 assert(T->isFunctionType() && "function decl is not of function type"); 11046 const FunctionType *FT = T->castAs<FunctionType>(); 11047 11048 // Set an implicit return of 'zero' if the function can return some integral, 11049 // enumeration, pointer or nullptr type. 11050 if (FT->getReturnType()->isIntegralOrEnumerationType() || 11051 FT->getReturnType()->isAnyPointerType() || 11052 FT->getReturnType()->isNullPtrType()) 11053 // DllMain is exempt because a return value of zero means it failed. 11054 if (FD->getName() != "DllMain") 11055 FD->setHasImplicitReturnZero(true); 11056 11057 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11058 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11059 FD->setInvalidDecl(); 11060 } 11061 } 11062 11063 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 11064 // FIXME: Need strict checking. In C89, we need to check for 11065 // any assignment, increment, decrement, function-calls, or 11066 // commas outside of a sizeof. In C99, it's the same list, 11067 // except that the aforementioned are allowed in unevaluated 11068 // expressions. Everything else falls under the 11069 // "may accept other forms of constant expressions" exception. 11070 // (We never end up here for C++, so the constant expression 11071 // rules there don't matter.) 11072 const Expr *Culprit; 11073 if (Init->isConstantInitializer(Context, false, &Culprit)) 11074 return false; 11075 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 11076 << Culprit->getSourceRange(); 11077 return true; 11078 } 11079 11080 namespace { 11081 // Visits an initialization expression to see if OrigDecl is evaluated in 11082 // its own initialization and throws a warning if it does. 11083 class SelfReferenceChecker 11084 : public EvaluatedExprVisitor<SelfReferenceChecker> { 11085 Sema &S; 11086 Decl *OrigDecl; 11087 bool isRecordType; 11088 bool isPODType; 11089 bool isReferenceType; 11090 11091 bool isInitList; 11092 llvm::SmallVector<unsigned, 4> InitFieldIndex; 11093 11094 public: 11095 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 11096 11097 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 11098 S(S), OrigDecl(OrigDecl) { 11099 isPODType = false; 11100 isRecordType = false; 11101 isReferenceType = false; 11102 isInitList = false; 11103 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 11104 isPODType = VD->getType().isPODType(S.Context); 11105 isRecordType = VD->getType()->isRecordType(); 11106 isReferenceType = VD->getType()->isReferenceType(); 11107 } 11108 } 11109 11110 // For most expressions, just call the visitor. For initializer lists, 11111 // track the index of the field being initialized since fields are 11112 // initialized in order allowing use of previously initialized fields. 11113 void CheckExpr(Expr *E) { 11114 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 11115 if (!InitList) { 11116 Visit(E); 11117 return; 11118 } 11119 11120 // Track and increment the index here. 11121 isInitList = true; 11122 InitFieldIndex.push_back(0); 11123 for (auto Child : InitList->children()) { 11124 CheckExpr(cast<Expr>(Child)); 11125 ++InitFieldIndex.back(); 11126 } 11127 InitFieldIndex.pop_back(); 11128 } 11129 11130 // Returns true if MemberExpr is checked and no further checking is needed. 11131 // Returns false if additional checking is required. 11132 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 11133 llvm::SmallVector<FieldDecl*, 4> Fields; 11134 Expr *Base = E; 11135 bool ReferenceField = false; 11136 11137 // Get the field members used. 11138 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11139 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 11140 if (!FD) 11141 return false; 11142 Fields.push_back(FD); 11143 if (FD->getType()->isReferenceType()) 11144 ReferenceField = true; 11145 Base = ME->getBase()->IgnoreParenImpCasts(); 11146 } 11147 11148 // Keep checking only if the base Decl is the same. 11149 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 11150 if (!DRE || DRE->getDecl() != OrigDecl) 11151 return false; 11152 11153 // A reference field can be bound to an unininitialized field. 11154 if (CheckReference && !ReferenceField) 11155 return true; 11156 11157 // Convert FieldDecls to their index number. 11158 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 11159 for (const FieldDecl *I : llvm::reverse(Fields)) 11160 UsedFieldIndex.push_back(I->getFieldIndex()); 11161 11162 // See if a warning is needed by checking the first difference in index 11163 // numbers. If field being used has index less than the field being 11164 // initialized, then the use is safe. 11165 for (auto UsedIter = UsedFieldIndex.begin(), 11166 UsedEnd = UsedFieldIndex.end(), 11167 OrigIter = InitFieldIndex.begin(), 11168 OrigEnd = InitFieldIndex.end(); 11169 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 11170 if (*UsedIter < *OrigIter) 11171 return true; 11172 if (*UsedIter > *OrigIter) 11173 break; 11174 } 11175 11176 // TODO: Add a different warning which will print the field names. 11177 HandleDeclRefExpr(DRE); 11178 return true; 11179 } 11180 11181 // For most expressions, the cast is directly above the DeclRefExpr. 11182 // For conditional operators, the cast can be outside the conditional 11183 // operator if both expressions are DeclRefExpr's. 11184 void HandleValue(Expr *E) { 11185 E = E->IgnoreParens(); 11186 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 11187 HandleDeclRefExpr(DRE); 11188 return; 11189 } 11190 11191 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 11192 Visit(CO->getCond()); 11193 HandleValue(CO->getTrueExpr()); 11194 HandleValue(CO->getFalseExpr()); 11195 return; 11196 } 11197 11198 if (BinaryConditionalOperator *BCO = 11199 dyn_cast<BinaryConditionalOperator>(E)) { 11200 Visit(BCO->getCond()); 11201 HandleValue(BCO->getFalseExpr()); 11202 return; 11203 } 11204 11205 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 11206 HandleValue(OVE->getSourceExpr()); 11207 return; 11208 } 11209 11210 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11211 if (BO->getOpcode() == BO_Comma) { 11212 Visit(BO->getLHS()); 11213 HandleValue(BO->getRHS()); 11214 return; 11215 } 11216 } 11217 11218 if (isa<MemberExpr>(E)) { 11219 if (isInitList) { 11220 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 11221 false /*CheckReference*/)) 11222 return; 11223 } 11224 11225 Expr *Base = E->IgnoreParenImpCasts(); 11226 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11227 // Check for static member variables and don't warn on them. 11228 if (!isa<FieldDecl>(ME->getMemberDecl())) 11229 return; 11230 Base = ME->getBase()->IgnoreParenImpCasts(); 11231 } 11232 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 11233 HandleDeclRefExpr(DRE); 11234 return; 11235 } 11236 11237 Visit(E); 11238 } 11239 11240 // Reference types not handled in HandleValue are handled here since all 11241 // uses of references are bad, not just r-value uses. 11242 void VisitDeclRefExpr(DeclRefExpr *E) { 11243 if (isReferenceType) 11244 HandleDeclRefExpr(E); 11245 } 11246 11247 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 11248 if (E->getCastKind() == CK_LValueToRValue) { 11249 HandleValue(E->getSubExpr()); 11250 return; 11251 } 11252 11253 Inherited::VisitImplicitCastExpr(E); 11254 } 11255 11256 void VisitMemberExpr(MemberExpr *E) { 11257 if (isInitList) { 11258 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 11259 return; 11260 } 11261 11262 // Don't warn on arrays since they can be treated as pointers. 11263 if (E->getType()->canDecayToPointerType()) return; 11264 11265 // Warn when a non-static method call is followed by non-static member 11266 // field accesses, which is followed by a DeclRefExpr. 11267 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 11268 bool Warn = (MD && !MD->isStatic()); 11269 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 11270 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11271 if (!isa<FieldDecl>(ME->getMemberDecl())) 11272 Warn = false; 11273 Base = ME->getBase()->IgnoreParenImpCasts(); 11274 } 11275 11276 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 11277 if (Warn) 11278 HandleDeclRefExpr(DRE); 11279 return; 11280 } 11281 11282 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 11283 // Visit that expression. 11284 Visit(Base); 11285 } 11286 11287 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 11288 Expr *Callee = E->getCallee(); 11289 11290 if (isa<UnresolvedLookupExpr>(Callee)) 11291 return Inherited::VisitCXXOperatorCallExpr(E); 11292 11293 Visit(Callee); 11294 for (auto Arg: E->arguments()) 11295 HandleValue(Arg->IgnoreParenImpCasts()); 11296 } 11297 11298 void VisitUnaryOperator(UnaryOperator *E) { 11299 // For POD record types, addresses of its own members are well-defined. 11300 if (E->getOpcode() == UO_AddrOf && isRecordType && 11301 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 11302 if (!isPODType) 11303 HandleValue(E->getSubExpr()); 11304 return; 11305 } 11306 11307 if (E->isIncrementDecrementOp()) { 11308 HandleValue(E->getSubExpr()); 11309 return; 11310 } 11311 11312 Inherited::VisitUnaryOperator(E); 11313 } 11314 11315 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 11316 11317 void VisitCXXConstructExpr(CXXConstructExpr *E) { 11318 if (E->getConstructor()->isCopyConstructor()) { 11319 Expr *ArgExpr = E->getArg(0); 11320 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 11321 if (ILE->getNumInits() == 1) 11322 ArgExpr = ILE->getInit(0); 11323 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 11324 if (ICE->getCastKind() == CK_NoOp) 11325 ArgExpr = ICE->getSubExpr(); 11326 HandleValue(ArgExpr); 11327 return; 11328 } 11329 Inherited::VisitCXXConstructExpr(E); 11330 } 11331 11332 void VisitCallExpr(CallExpr *E) { 11333 // Treat std::move as a use. 11334 if (E->isCallToStdMove()) { 11335 HandleValue(E->getArg(0)); 11336 return; 11337 } 11338 11339 Inherited::VisitCallExpr(E); 11340 } 11341 11342 void VisitBinaryOperator(BinaryOperator *E) { 11343 if (E->isCompoundAssignmentOp()) { 11344 HandleValue(E->getLHS()); 11345 Visit(E->getRHS()); 11346 return; 11347 } 11348 11349 Inherited::VisitBinaryOperator(E); 11350 } 11351 11352 // A custom visitor for BinaryConditionalOperator is needed because the 11353 // regular visitor would check the condition and true expression separately 11354 // but both point to the same place giving duplicate diagnostics. 11355 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 11356 Visit(E->getCond()); 11357 Visit(E->getFalseExpr()); 11358 } 11359 11360 void HandleDeclRefExpr(DeclRefExpr *DRE) { 11361 Decl* ReferenceDecl = DRE->getDecl(); 11362 if (OrigDecl != ReferenceDecl) return; 11363 unsigned diag; 11364 if (isReferenceType) { 11365 diag = diag::warn_uninit_self_reference_in_reference_init; 11366 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 11367 diag = diag::warn_static_self_reference_in_init; 11368 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 11369 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 11370 DRE->getDecl()->getType()->isRecordType()) { 11371 diag = diag::warn_uninit_self_reference_in_init; 11372 } else { 11373 // Local variables will be handled by the CFG analysis. 11374 return; 11375 } 11376 11377 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE, 11378 S.PDiag(diag) 11379 << DRE->getDecl() << OrigDecl->getLocation() 11380 << DRE->getSourceRange()); 11381 } 11382 }; 11383 11384 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 11385 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 11386 bool DirectInit) { 11387 // Parameters arguments are occassionially constructed with itself, 11388 // for instance, in recursive functions. Skip them. 11389 if (isa<ParmVarDecl>(OrigDecl)) 11390 return; 11391 11392 E = E->IgnoreParens(); 11393 11394 // Skip checking T a = a where T is not a record or reference type. 11395 // Doing so is a way to silence uninitialized warnings. 11396 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 11397 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 11398 if (ICE->getCastKind() == CK_LValueToRValue) 11399 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 11400 if (DRE->getDecl() == OrigDecl) 11401 return; 11402 11403 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 11404 } 11405 } // end anonymous namespace 11406 11407 namespace { 11408 // Simple wrapper to add the name of a variable or (if no variable is 11409 // available) a DeclarationName into a diagnostic. 11410 struct VarDeclOrName { 11411 VarDecl *VDecl; 11412 DeclarationName Name; 11413 11414 friend const Sema::SemaDiagnosticBuilder & 11415 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 11416 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 11417 } 11418 }; 11419 } // end anonymous namespace 11420 11421 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 11422 DeclarationName Name, QualType Type, 11423 TypeSourceInfo *TSI, 11424 SourceRange Range, bool DirectInit, 11425 Expr *Init) { 11426 bool IsInitCapture = !VDecl; 11427 assert((!VDecl || !VDecl->isInitCapture()) && 11428 "init captures are expected to be deduced prior to initialization"); 11429 11430 VarDeclOrName VN{VDecl, Name}; 11431 11432 DeducedType *Deduced = Type->getContainedDeducedType(); 11433 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 11434 11435 // C++11 [dcl.spec.auto]p3 11436 if (!Init) { 11437 assert(VDecl && "no init for init capture deduction?"); 11438 11439 // Except for class argument deduction, and then for an initializing 11440 // declaration only, i.e. no static at class scope or extern. 11441 if (!isa<DeducedTemplateSpecializationType>(Deduced) || 11442 VDecl->hasExternalStorage() || 11443 VDecl->isStaticDataMember()) { 11444 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 11445 << VDecl->getDeclName() << Type; 11446 return QualType(); 11447 } 11448 } 11449 11450 ArrayRef<Expr*> DeduceInits; 11451 if (Init) 11452 DeduceInits = Init; 11453 11454 if (DirectInit) { 11455 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) 11456 DeduceInits = PL->exprs(); 11457 } 11458 11459 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 11460 assert(VDecl && "non-auto type for init capture deduction?"); 11461 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 11462 InitializationKind Kind = InitializationKind::CreateForInit( 11463 VDecl->getLocation(), DirectInit, Init); 11464 // FIXME: Initialization should not be taking a mutable list of inits. 11465 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 11466 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 11467 InitsCopy); 11468 } 11469 11470 if (DirectInit) { 11471 if (auto *IL = dyn_cast<InitListExpr>(Init)) 11472 DeduceInits = IL->inits(); 11473 } 11474 11475 // Deduction only works if we have exactly one source expression. 11476 if (DeduceInits.empty()) { 11477 // It isn't possible to write this directly, but it is possible to 11478 // end up in this situation with "auto x(some_pack...);" 11479 Diag(Init->getBeginLoc(), IsInitCapture 11480 ? diag::err_init_capture_no_expression 11481 : diag::err_auto_var_init_no_expression) 11482 << VN << Type << Range; 11483 return QualType(); 11484 } 11485 11486 if (DeduceInits.size() > 1) { 11487 Diag(DeduceInits[1]->getBeginLoc(), 11488 IsInitCapture ? diag::err_init_capture_multiple_expressions 11489 : diag::err_auto_var_init_multiple_expressions) 11490 << VN << Type << Range; 11491 return QualType(); 11492 } 11493 11494 Expr *DeduceInit = DeduceInits[0]; 11495 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 11496 Diag(Init->getBeginLoc(), IsInitCapture 11497 ? diag::err_init_capture_paren_braces 11498 : diag::err_auto_var_init_paren_braces) 11499 << isa<InitListExpr>(Init) << VN << Type << Range; 11500 return QualType(); 11501 } 11502 11503 // Expressions default to 'id' when we're in a debugger. 11504 bool DefaultedAnyToId = false; 11505 if (getLangOpts().DebuggerCastResultToId && 11506 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 11507 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 11508 if (Result.isInvalid()) { 11509 return QualType(); 11510 } 11511 Init = Result.get(); 11512 DefaultedAnyToId = true; 11513 } 11514 11515 // C++ [dcl.decomp]p1: 11516 // If the assignment-expression [...] has array type A and no ref-qualifier 11517 // is present, e has type cv A 11518 if (VDecl && isa<DecompositionDecl>(VDecl) && 11519 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 11520 DeduceInit->getType()->isConstantArrayType()) 11521 return Context.getQualifiedType(DeduceInit->getType(), 11522 Type.getQualifiers()); 11523 11524 QualType DeducedType; 11525 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 11526 if (!IsInitCapture) 11527 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 11528 else if (isa<InitListExpr>(Init)) 11529 Diag(Range.getBegin(), 11530 diag::err_init_capture_deduction_failure_from_init_list) 11531 << VN 11532 << (DeduceInit->getType().isNull() ? TSI->getType() 11533 : DeduceInit->getType()) 11534 << DeduceInit->getSourceRange(); 11535 else 11536 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 11537 << VN << TSI->getType() 11538 << (DeduceInit->getType().isNull() ? TSI->getType() 11539 : DeduceInit->getType()) 11540 << DeduceInit->getSourceRange(); 11541 } 11542 11543 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 11544 // 'id' instead of a specific object type prevents most of our usual 11545 // checks. 11546 // We only want to warn outside of template instantiations, though: 11547 // inside a template, the 'id' could have come from a parameter. 11548 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 11549 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 11550 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 11551 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 11552 } 11553 11554 return DeducedType; 11555 } 11556 11557 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 11558 Expr *Init) { 11559 assert(!Init || !Init->containsErrors()); 11560 QualType DeducedType = deduceVarTypeFromInitializer( 11561 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 11562 VDecl->getSourceRange(), DirectInit, Init); 11563 if (DeducedType.isNull()) { 11564 VDecl->setInvalidDecl(); 11565 return true; 11566 } 11567 11568 VDecl->setType(DeducedType); 11569 assert(VDecl->isLinkageValid()); 11570 11571 // In ARC, infer lifetime. 11572 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 11573 VDecl->setInvalidDecl(); 11574 11575 if (getLangOpts().OpenCL) 11576 deduceOpenCLAddressSpace(VDecl); 11577 11578 // If this is a redeclaration, check that the type we just deduced matches 11579 // the previously declared type. 11580 if (VarDecl *Old = VDecl->getPreviousDecl()) { 11581 // We never need to merge the type, because we cannot form an incomplete 11582 // array of auto, nor deduce such a type. 11583 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 11584 } 11585 11586 // Check the deduced type is valid for a variable declaration. 11587 CheckVariableDeclarationType(VDecl); 11588 return VDecl->isInvalidDecl(); 11589 } 11590 11591 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init, 11592 SourceLocation Loc) { 11593 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init)) 11594 Init = EWC->getSubExpr(); 11595 11596 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 11597 Init = CE->getSubExpr(); 11598 11599 QualType InitType = Init->getType(); 11600 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 11601 InitType.hasNonTrivialToPrimitiveCopyCUnion()) && 11602 "shouldn't be called if type doesn't have a non-trivial C struct"); 11603 if (auto *ILE = dyn_cast<InitListExpr>(Init)) { 11604 for (auto I : ILE->inits()) { 11605 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() && 11606 !I->getType().hasNonTrivialToPrimitiveCopyCUnion()) 11607 continue; 11608 SourceLocation SL = I->getExprLoc(); 11609 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc); 11610 } 11611 return; 11612 } 11613 11614 if (isa<ImplicitValueInitExpr>(Init)) { 11615 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 11616 checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject, 11617 NTCUK_Init); 11618 } else { 11619 // Assume all other explicit initializers involving copying some existing 11620 // object. 11621 // TODO: ignore any explicit initializers where we can guarantee 11622 // copy-elision. 11623 if (InitType.hasNonTrivialToPrimitiveCopyCUnion()) 11624 checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy); 11625 } 11626 } 11627 11628 namespace { 11629 11630 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) { 11631 // Ignore unavailable fields. A field can be marked as unavailable explicitly 11632 // in the source code or implicitly by the compiler if it is in a union 11633 // defined in a system header and has non-trivial ObjC ownership 11634 // qualifications. We don't want those fields to participate in determining 11635 // whether the containing union is non-trivial. 11636 return FD->hasAttr<UnavailableAttr>(); 11637 } 11638 11639 struct DiagNonTrivalCUnionDefaultInitializeVisitor 11640 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 11641 void> { 11642 using Super = 11643 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 11644 void>; 11645 11646 DiagNonTrivalCUnionDefaultInitializeVisitor( 11647 QualType OrigTy, SourceLocation OrigLoc, 11648 Sema::NonTrivialCUnionContext UseContext, Sema &S) 11649 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11650 11651 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT, 11652 const FieldDecl *FD, bool InNonTrivialUnion) { 11653 if (const auto *AT = S.Context.getAsArrayType(QT)) 11654 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11655 InNonTrivialUnion); 11656 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion); 11657 } 11658 11659 void visitARCStrong(QualType QT, const FieldDecl *FD, 11660 bool InNonTrivialUnion) { 11661 if (InNonTrivialUnion) 11662 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11663 << 1 << 0 << QT << FD->getName(); 11664 } 11665 11666 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11667 if (InNonTrivialUnion) 11668 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11669 << 1 << 0 << QT << FD->getName(); 11670 } 11671 11672 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11673 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11674 if (RD->isUnion()) { 11675 if (OrigLoc.isValid()) { 11676 bool IsUnion = false; 11677 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11678 IsUnion = OrigRD->isUnion(); 11679 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11680 << 0 << OrigTy << IsUnion << UseContext; 11681 // Reset OrigLoc so that this diagnostic is emitted only once. 11682 OrigLoc = SourceLocation(); 11683 } 11684 InNonTrivialUnion = true; 11685 } 11686 11687 if (InNonTrivialUnion) 11688 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11689 << 0 << 0 << QT.getUnqualifiedType() << ""; 11690 11691 for (const FieldDecl *FD : RD->fields()) 11692 if (!shouldIgnoreForRecordTriviality(FD)) 11693 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11694 } 11695 11696 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11697 11698 // The non-trivial C union type or the struct/union type that contains a 11699 // non-trivial C union. 11700 QualType OrigTy; 11701 SourceLocation OrigLoc; 11702 Sema::NonTrivialCUnionContext UseContext; 11703 Sema &S; 11704 }; 11705 11706 struct DiagNonTrivalCUnionDestructedTypeVisitor 11707 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> { 11708 using Super = 11709 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>; 11710 11711 DiagNonTrivalCUnionDestructedTypeVisitor( 11712 QualType OrigTy, SourceLocation OrigLoc, 11713 Sema::NonTrivialCUnionContext UseContext, Sema &S) 11714 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11715 11716 void visitWithKind(QualType::DestructionKind DK, QualType QT, 11717 const FieldDecl *FD, bool InNonTrivialUnion) { 11718 if (const auto *AT = S.Context.getAsArrayType(QT)) 11719 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11720 InNonTrivialUnion); 11721 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion); 11722 } 11723 11724 void visitARCStrong(QualType QT, const FieldDecl *FD, 11725 bool InNonTrivialUnion) { 11726 if (InNonTrivialUnion) 11727 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11728 << 1 << 1 << QT << FD->getName(); 11729 } 11730 11731 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11732 if (InNonTrivialUnion) 11733 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11734 << 1 << 1 << QT << FD->getName(); 11735 } 11736 11737 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11738 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11739 if (RD->isUnion()) { 11740 if (OrigLoc.isValid()) { 11741 bool IsUnion = false; 11742 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11743 IsUnion = OrigRD->isUnion(); 11744 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11745 << 1 << OrigTy << IsUnion << UseContext; 11746 // Reset OrigLoc so that this diagnostic is emitted only once. 11747 OrigLoc = SourceLocation(); 11748 } 11749 InNonTrivialUnion = true; 11750 } 11751 11752 if (InNonTrivialUnion) 11753 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11754 << 0 << 1 << QT.getUnqualifiedType() << ""; 11755 11756 for (const FieldDecl *FD : RD->fields()) 11757 if (!shouldIgnoreForRecordTriviality(FD)) 11758 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11759 } 11760 11761 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11762 void visitCXXDestructor(QualType QT, const FieldDecl *FD, 11763 bool InNonTrivialUnion) {} 11764 11765 // The non-trivial C union type or the struct/union type that contains a 11766 // non-trivial C union. 11767 QualType OrigTy; 11768 SourceLocation OrigLoc; 11769 Sema::NonTrivialCUnionContext UseContext; 11770 Sema &S; 11771 }; 11772 11773 struct DiagNonTrivalCUnionCopyVisitor 11774 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> { 11775 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>; 11776 11777 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc, 11778 Sema::NonTrivialCUnionContext UseContext, 11779 Sema &S) 11780 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11781 11782 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT, 11783 const FieldDecl *FD, bool InNonTrivialUnion) { 11784 if (const auto *AT = S.Context.getAsArrayType(QT)) 11785 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11786 InNonTrivialUnion); 11787 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion); 11788 } 11789 11790 void visitARCStrong(QualType QT, const FieldDecl *FD, 11791 bool InNonTrivialUnion) { 11792 if (InNonTrivialUnion) 11793 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11794 << 1 << 2 << QT << FD->getName(); 11795 } 11796 11797 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11798 if (InNonTrivialUnion) 11799 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11800 << 1 << 2 << QT << FD->getName(); 11801 } 11802 11803 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11804 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11805 if (RD->isUnion()) { 11806 if (OrigLoc.isValid()) { 11807 bool IsUnion = false; 11808 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11809 IsUnion = OrigRD->isUnion(); 11810 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11811 << 2 << OrigTy << IsUnion << UseContext; 11812 // Reset OrigLoc so that this diagnostic is emitted only once. 11813 OrigLoc = SourceLocation(); 11814 } 11815 InNonTrivialUnion = true; 11816 } 11817 11818 if (InNonTrivialUnion) 11819 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11820 << 0 << 2 << QT.getUnqualifiedType() << ""; 11821 11822 for (const FieldDecl *FD : RD->fields()) 11823 if (!shouldIgnoreForRecordTriviality(FD)) 11824 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11825 } 11826 11827 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT, 11828 const FieldDecl *FD, bool InNonTrivialUnion) {} 11829 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11830 void visitVolatileTrivial(QualType QT, const FieldDecl *FD, 11831 bool InNonTrivialUnion) {} 11832 11833 // The non-trivial C union type or the struct/union type that contains a 11834 // non-trivial C union. 11835 QualType OrigTy; 11836 SourceLocation OrigLoc; 11837 Sema::NonTrivialCUnionContext UseContext; 11838 Sema &S; 11839 }; 11840 11841 } // namespace 11842 11843 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc, 11844 NonTrivialCUnionContext UseContext, 11845 unsigned NonTrivialKind) { 11846 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 11847 QT.hasNonTrivialToPrimitiveDestructCUnion() || 11848 QT.hasNonTrivialToPrimitiveCopyCUnion()) && 11849 "shouldn't be called if type doesn't have a non-trivial C union"); 11850 11851 if ((NonTrivialKind & NTCUK_Init) && 11852 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 11853 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this) 11854 .visit(QT, nullptr, false); 11855 if ((NonTrivialKind & NTCUK_Destruct) && 11856 QT.hasNonTrivialToPrimitiveDestructCUnion()) 11857 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this) 11858 .visit(QT, nullptr, false); 11859 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion()) 11860 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this) 11861 .visit(QT, nullptr, false); 11862 } 11863 11864 /// AddInitializerToDecl - Adds the initializer Init to the 11865 /// declaration dcl. If DirectInit is true, this is C++ direct 11866 /// initialization rather than copy initialization. 11867 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 11868 // If there is no declaration, there was an error parsing it. Just ignore 11869 // the initializer. 11870 if (!RealDecl || RealDecl->isInvalidDecl()) { 11871 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 11872 return; 11873 } 11874 11875 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 11876 // Pure-specifiers are handled in ActOnPureSpecifier. 11877 Diag(Method->getLocation(), diag::err_member_function_initialization) 11878 << Method->getDeclName() << Init->getSourceRange(); 11879 Method->setInvalidDecl(); 11880 return; 11881 } 11882 11883 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 11884 if (!VDecl) { 11885 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 11886 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 11887 RealDecl->setInvalidDecl(); 11888 return; 11889 } 11890 11891 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 11892 if (VDecl->getType()->isUndeducedType()) { 11893 // Attempt typo correction early so that the type of the init expression can 11894 // be deduced based on the chosen correction if the original init contains a 11895 // TypoExpr. 11896 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 11897 if (!Res.isUsable()) { 11898 // There are unresolved typos in Init, just drop them. 11899 // FIXME: improve the recovery strategy to preserve the Init. 11900 RealDecl->setInvalidDecl(); 11901 return; 11902 } 11903 if (Res.get()->containsErrors()) { 11904 // Invalidate the decl as we don't know the type for recovery-expr yet. 11905 RealDecl->setInvalidDecl(); 11906 VDecl->setInit(Res.get()); 11907 return; 11908 } 11909 Init = Res.get(); 11910 11911 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 11912 return; 11913 } 11914 11915 // dllimport cannot be used on variable definitions. 11916 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 11917 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 11918 VDecl->setInvalidDecl(); 11919 return; 11920 } 11921 11922 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 11923 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 11924 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 11925 VDecl->setInvalidDecl(); 11926 return; 11927 } 11928 11929 if (!VDecl->getType()->isDependentType()) { 11930 // A definition must end up with a complete type, which means it must be 11931 // complete with the restriction that an array type might be completed by 11932 // the initializer; note that later code assumes this restriction. 11933 QualType BaseDeclType = VDecl->getType(); 11934 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 11935 BaseDeclType = Array->getElementType(); 11936 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 11937 diag::err_typecheck_decl_incomplete_type)) { 11938 RealDecl->setInvalidDecl(); 11939 return; 11940 } 11941 11942 // The variable can not have an abstract class type. 11943 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 11944 diag::err_abstract_type_in_decl, 11945 AbstractVariableType)) 11946 VDecl->setInvalidDecl(); 11947 } 11948 11949 // If adding the initializer will turn this declaration into a definition, 11950 // and we already have a definition for this variable, diagnose or otherwise 11951 // handle the situation. 11952 VarDecl *Def; 11953 if ((Def = VDecl->getDefinition()) && Def != VDecl && 11954 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 11955 !VDecl->isThisDeclarationADemotedDefinition() && 11956 checkVarDeclRedefinition(Def, VDecl)) 11957 return; 11958 11959 if (getLangOpts().CPlusPlus) { 11960 // C++ [class.static.data]p4 11961 // If a static data member is of const integral or const 11962 // enumeration type, its declaration in the class definition can 11963 // specify a constant-initializer which shall be an integral 11964 // constant expression (5.19). In that case, the member can appear 11965 // in integral constant expressions. The member shall still be 11966 // defined in a namespace scope if it is used in the program and the 11967 // namespace scope definition shall not contain an initializer. 11968 // 11969 // We already performed a redefinition check above, but for static 11970 // data members we also need to check whether there was an in-class 11971 // declaration with an initializer. 11972 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 11973 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 11974 << VDecl->getDeclName(); 11975 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 11976 diag::note_previous_initializer) 11977 << 0; 11978 return; 11979 } 11980 11981 if (VDecl->hasLocalStorage()) 11982 setFunctionHasBranchProtectedScope(); 11983 11984 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 11985 VDecl->setInvalidDecl(); 11986 return; 11987 } 11988 } 11989 11990 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 11991 // a kernel function cannot be initialized." 11992 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 11993 Diag(VDecl->getLocation(), diag::err_local_cant_init); 11994 VDecl->setInvalidDecl(); 11995 return; 11996 } 11997 11998 // The LoaderUninitialized attribute acts as a definition (of undef). 11999 if (VDecl->hasAttr<LoaderUninitializedAttr>()) { 12000 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init); 12001 VDecl->setInvalidDecl(); 12002 return; 12003 } 12004 12005 // Get the decls type and save a reference for later, since 12006 // CheckInitializerTypes may change it. 12007 QualType DclT = VDecl->getType(), SavT = DclT; 12008 12009 // Expressions default to 'id' when we're in a debugger 12010 // and we are assigning it to a variable of Objective-C pointer type. 12011 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 12012 Init->getType() == Context.UnknownAnyTy) { 12013 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 12014 if (Result.isInvalid()) { 12015 VDecl->setInvalidDecl(); 12016 return; 12017 } 12018 Init = Result.get(); 12019 } 12020 12021 // Perform the initialization. 12022 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 12023 if (!VDecl->isInvalidDecl()) { 12024 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 12025 InitializationKind Kind = InitializationKind::CreateForInit( 12026 VDecl->getLocation(), DirectInit, Init); 12027 12028 MultiExprArg Args = Init; 12029 if (CXXDirectInit) 12030 Args = MultiExprArg(CXXDirectInit->getExprs(), 12031 CXXDirectInit->getNumExprs()); 12032 12033 // Try to correct any TypoExprs in the initialization arguments. 12034 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 12035 ExprResult Res = CorrectDelayedTyposInExpr( 12036 Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/false, 12037 [this, Entity, Kind](Expr *E) { 12038 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 12039 return Init.Failed() ? ExprError() : E; 12040 }); 12041 if (Res.isInvalid()) { 12042 VDecl->setInvalidDecl(); 12043 } else if (Res.get() != Args[Idx]) { 12044 Args[Idx] = Res.get(); 12045 } 12046 } 12047 if (VDecl->isInvalidDecl()) 12048 return; 12049 12050 InitializationSequence InitSeq(*this, Entity, Kind, Args, 12051 /*TopLevelOfInitList=*/false, 12052 /*TreatUnavailableAsInvalid=*/false); 12053 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 12054 if (Result.isInvalid()) { 12055 // If the provied initializer fails to initialize the var decl, 12056 // we attach a recovery expr for better recovery. 12057 auto RecoveryExpr = 12058 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args); 12059 if (RecoveryExpr.get()) 12060 VDecl->setInit(RecoveryExpr.get()); 12061 return; 12062 } 12063 12064 Init = Result.getAs<Expr>(); 12065 } 12066 12067 // Check for self-references within variable initializers. 12068 // Variables declared within a function/method body (except for references) 12069 // are handled by a dataflow analysis. 12070 // This is undefined behavior in C++, but valid in C. 12071 if (getLangOpts().CPlusPlus) { 12072 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 12073 VDecl->getType()->isReferenceType()) { 12074 CheckSelfReference(*this, RealDecl, Init, DirectInit); 12075 } 12076 } 12077 12078 // If the type changed, it means we had an incomplete type that was 12079 // completed by the initializer. For example: 12080 // int ary[] = { 1, 3, 5 }; 12081 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 12082 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 12083 VDecl->setType(DclT); 12084 12085 if (!VDecl->isInvalidDecl()) { 12086 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 12087 12088 if (VDecl->hasAttr<BlocksAttr>()) 12089 checkRetainCycles(VDecl, Init); 12090 12091 // It is safe to assign a weak reference into a strong variable. 12092 // Although this code can still have problems: 12093 // id x = self.weakProp; 12094 // id y = self.weakProp; 12095 // we do not warn to warn spuriously when 'x' and 'y' are on separate 12096 // paths through the function. This should be revisited if 12097 // -Wrepeated-use-of-weak is made flow-sensitive. 12098 if (FunctionScopeInfo *FSI = getCurFunction()) 12099 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 12100 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 12101 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 12102 Init->getBeginLoc())) 12103 FSI->markSafeWeakUse(Init); 12104 } 12105 12106 // The initialization is usually a full-expression. 12107 // 12108 // FIXME: If this is a braced initialization of an aggregate, it is not 12109 // an expression, and each individual field initializer is a separate 12110 // full-expression. For instance, in: 12111 // 12112 // struct Temp { ~Temp(); }; 12113 // struct S { S(Temp); }; 12114 // struct T { S a, b; } t = { Temp(), Temp() } 12115 // 12116 // we should destroy the first Temp before constructing the second. 12117 ExprResult Result = 12118 ActOnFinishFullExpr(Init, VDecl->getLocation(), 12119 /*DiscardedValue*/ false, VDecl->isConstexpr()); 12120 if (Result.isInvalid()) { 12121 VDecl->setInvalidDecl(); 12122 return; 12123 } 12124 Init = Result.get(); 12125 12126 // Attach the initializer to the decl. 12127 VDecl->setInit(Init); 12128 12129 if (VDecl->isLocalVarDecl()) { 12130 // Don't check the initializer if the declaration is malformed. 12131 if (VDecl->isInvalidDecl()) { 12132 // do nothing 12133 12134 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 12135 // This is true even in C++ for OpenCL. 12136 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 12137 CheckForConstantInitializer(Init, DclT); 12138 12139 // Otherwise, C++ does not restrict the initializer. 12140 } else if (getLangOpts().CPlusPlus) { 12141 // do nothing 12142 12143 // C99 6.7.8p4: All the expressions in an initializer for an object that has 12144 // static storage duration shall be constant expressions or string literals. 12145 } else if (VDecl->getStorageClass() == SC_Static) { 12146 CheckForConstantInitializer(Init, DclT); 12147 12148 // C89 is stricter than C99 for aggregate initializers. 12149 // C89 6.5.7p3: All the expressions [...] in an initializer list 12150 // for an object that has aggregate or union type shall be 12151 // constant expressions. 12152 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 12153 isa<InitListExpr>(Init)) { 12154 const Expr *Culprit; 12155 if (!Init->isConstantInitializer(Context, false, &Culprit)) { 12156 Diag(Culprit->getExprLoc(), 12157 diag::ext_aggregate_init_not_constant) 12158 << Culprit->getSourceRange(); 12159 } 12160 } 12161 12162 if (auto *E = dyn_cast<ExprWithCleanups>(Init)) 12163 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens())) 12164 if (VDecl->hasLocalStorage()) 12165 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 12166 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 12167 VDecl->getLexicalDeclContext()->isRecord()) { 12168 // This is an in-class initialization for a static data member, e.g., 12169 // 12170 // struct S { 12171 // static const int value = 17; 12172 // }; 12173 12174 // C++ [class.mem]p4: 12175 // A member-declarator can contain a constant-initializer only 12176 // if it declares a static member (9.4) of const integral or 12177 // const enumeration type, see 9.4.2. 12178 // 12179 // C++11 [class.static.data]p3: 12180 // If a non-volatile non-inline const static data member is of integral 12181 // or enumeration type, its declaration in the class definition can 12182 // specify a brace-or-equal-initializer in which every initializer-clause 12183 // that is an assignment-expression is a constant expression. A static 12184 // data member of literal type can be declared in the class definition 12185 // with the constexpr specifier; if so, its declaration shall specify a 12186 // brace-or-equal-initializer in which every initializer-clause that is 12187 // an assignment-expression is a constant expression. 12188 12189 // Do nothing on dependent types. 12190 if (DclT->isDependentType()) { 12191 12192 // Allow any 'static constexpr' members, whether or not they are of literal 12193 // type. We separately check that every constexpr variable is of literal 12194 // type. 12195 } else if (VDecl->isConstexpr()) { 12196 12197 // Require constness. 12198 } else if (!DclT.isConstQualified()) { 12199 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 12200 << Init->getSourceRange(); 12201 VDecl->setInvalidDecl(); 12202 12203 // We allow integer constant expressions in all cases. 12204 } else if (DclT->isIntegralOrEnumerationType()) { 12205 // Check whether the expression is a constant expression. 12206 SourceLocation Loc; 12207 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 12208 // In C++11, a non-constexpr const static data member with an 12209 // in-class initializer cannot be volatile. 12210 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 12211 else if (Init->isValueDependent()) 12212 ; // Nothing to check. 12213 else if (Init->isIntegerConstantExpr(Context, &Loc)) 12214 ; // Ok, it's an ICE! 12215 else if (Init->getType()->isScopedEnumeralType() && 12216 Init->isCXX11ConstantExpr(Context)) 12217 ; // Ok, it is a scoped-enum constant expression. 12218 else if (Init->isEvaluatable(Context)) { 12219 // If we can constant fold the initializer through heroics, accept it, 12220 // but report this as a use of an extension for -pedantic. 12221 Diag(Loc, diag::ext_in_class_initializer_non_constant) 12222 << Init->getSourceRange(); 12223 } else { 12224 // Otherwise, this is some crazy unknown case. Report the issue at the 12225 // location provided by the isIntegerConstantExpr failed check. 12226 Diag(Loc, diag::err_in_class_initializer_non_constant) 12227 << Init->getSourceRange(); 12228 VDecl->setInvalidDecl(); 12229 } 12230 12231 // We allow foldable floating-point constants as an extension. 12232 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 12233 // In C++98, this is a GNU extension. In C++11, it is not, but we support 12234 // it anyway and provide a fixit to add the 'constexpr'. 12235 if (getLangOpts().CPlusPlus11) { 12236 Diag(VDecl->getLocation(), 12237 diag::ext_in_class_initializer_float_type_cxx11) 12238 << DclT << Init->getSourceRange(); 12239 Diag(VDecl->getBeginLoc(), 12240 diag::note_in_class_initializer_float_type_cxx11) 12241 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12242 } else { 12243 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 12244 << DclT << Init->getSourceRange(); 12245 12246 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 12247 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 12248 << Init->getSourceRange(); 12249 VDecl->setInvalidDecl(); 12250 } 12251 } 12252 12253 // Suggest adding 'constexpr' in C++11 for literal types. 12254 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 12255 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 12256 << DclT << Init->getSourceRange() 12257 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12258 VDecl->setConstexpr(true); 12259 12260 } else { 12261 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 12262 << DclT << Init->getSourceRange(); 12263 VDecl->setInvalidDecl(); 12264 } 12265 } else if (VDecl->isFileVarDecl()) { 12266 // In C, extern is typically used to avoid tentative definitions when 12267 // declaring variables in headers, but adding an intializer makes it a 12268 // definition. This is somewhat confusing, so GCC and Clang both warn on it. 12269 // In C++, extern is often used to give implictly static const variables 12270 // external linkage, so don't warn in that case. If selectany is present, 12271 // this might be header code intended for C and C++ inclusion, so apply the 12272 // C++ rules. 12273 if (VDecl->getStorageClass() == SC_Extern && 12274 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 12275 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 12276 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 12277 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 12278 Diag(VDecl->getLocation(), diag::warn_extern_init); 12279 12280 // In Microsoft C++ mode, a const variable defined in namespace scope has 12281 // external linkage by default if the variable is declared with 12282 // __declspec(dllexport). 12283 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 12284 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() && 12285 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition()) 12286 VDecl->setStorageClass(SC_Extern); 12287 12288 // C99 6.7.8p4. All file scoped initializers need to be constant. 12289 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 12290 CheckForConstantInitializer(Init, DclT); 12291 } 12292 12293 QualType InitType = Init->getType(); 12294 if (!InitType.isNull() && 12295 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12296 InitType.hasNonTrivialToPrimitiveCopyCUnion())) 12297 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc()); 12298 12299 // We will represent direct-initialization similarly to copy-initialization: 12300 // int x(1); -as-> int x = 1; 12301 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 12302 // 12303 // Clients that want to distinguish between the two forms, can check for 12304 // direct initializer using VarDecl::getInitStyle(). 12305 // A major benefit is that clients that don't particularly care about which 12306 // exactly form was it (like the CodeGen) can handle both cases without 12307 // special case code. 12308 12309 // C++ 8.5p11: 12310 // The form of initialization (using parentheses or '=') is generally 12311 // insignificant, but does matter when the entity being initialized has a 12312 // class type. 12313 if (CXXDirectInit) { 12314 assert(DirectInit && "Call-style initializer must be direct init."); 12315 VDecl->setInitStyle(VarDecl::CallInit); 12316 } else if (DirectInit) { 12317 // This must be list-initialization. No other way is direct-initialization. 12318 VDecl->setInitStyle(VarDecl::ListInit); 12319 } 12320 12321 if (LangOpts.OpenMP && VDecl->isFileVarDecl()) 12322 DeclsToCheckForDeferredDiags.push_back(VDecl); 12323 CheckCompleteVariableDeclaration(VDecl); 12324 } 12325 12326 /// ActOnInitializerError - Given that there was an error parsing an 12327 /// initializer for the given declaration, try to return to some form 12328 /// of sanity. 12329 void Sema::ActOnInitializerError(Decl *D) { 12330 // Our main concern here is re-establishing invariants like "a 12331 // variable's type is either dependent or complete". 12332 if (!D || D->isInvalidDecl()) return; 12333 12334 VarDecl *VD = dyn_cast<VarDecl>(D); 12335 if (!VD) return; 12336 12337 // Bindings are not usable if we can't make sense of the initializer. 12338 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 12339 for (auto *BD : DD->bindings()) 12340 BD->setInvalidDecl(); 12341 12342 // Auto types are meaningless if we can't make sense of the initializer. 12343 if (VD->getType()->isUndeducedType()) { 12344 D->setInvalidDecl(); 12345 return; 12346 } 12347 12348 QualType Ty = VD->getType(); 12349 if (Ty->isDependentType()) return; 12350 12351 // Require a complete type. 12352 if (RequireCompleteType(VD->getLocation(), 12353 Context.getBaseElementType(Ty), 12354 diag::err_typecheck_decl_incomplete_type)) { 12355 VD->setInvalidDecl(); 12356 return; 12357 } 12358 12359 // Require a non-abstract type. 12360 if (RequireNonAbstractType(VD->getLocation(), Ty, 12361 diag::err_abstract_type_in_decl, 12362 AbstractVariableType)) { 12363 VD->setInvalidDecl(); 12364 return; 12365 } 12366 12367 // Don't bother complaining about constructors or destructors, 12368 // though. 12369 } 12370 12371 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 12372 // If there is no declaration, there was an error parsing it. Just ignore it. 12373 if (!RealDecl) 12374 return; 12375 12376 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 12377 QualType Type = Var->getType(); 12378 12379 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 12380 if (isa<DecompositionDecl>(RealDecl)) { 12381 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 12382 Var->setInvalidDecl(); 12383 return; 12384 } 12385 12386 if (Type->isUndeducedType() && 12387 DeduceVariableDeclarationType(Var, false, nullptr)) 12388 return; 12389 12390 // C++11 [class.static.data]p3: A static data member can be declared with 12391 // the constexpr specifier; if so, its declaration shall specify 12392 // a brace-or-equal-initializer. 12393 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 12394 // the definition of a variable [...] or the declaration of a static data 12395 // member. 12396 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 12397 !Var->isThisDeclarationADemotedDefinition()) { 12398 if (Var->isStaticDataMember()) { 12399 // C++1z removes the relevant rule; the in-class declaration is always 12400 // a definition there. 12401 if (!getLangOpts().CPlusPlus17 && 12402 !Context.getTargetInfo().getCXXABI().isMicrosoft()) { 12403 Diag(Var->getLocation(), 12404 diag::err_constexpr_static_mem_var_requires_init) 12405 << Var->getDeclName(); 12406 Var->setInvalidDecl(); 12407 return; 12408 } 12409 } else { 12410 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 12411 Var->setInvalidDecl(); 12412 return; 12413 } 12414 } 12415 12416 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 12417 // be initialized. 12418 if (!Var->isInvalidDecl() && 12419 Var->getType().getAddressSpace() == LangAS::opencl_constant && 12420 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 12421 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 12422 Var->setInvalidDecl(); 12423 return; 12424 } 12425 12426 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) { 12427 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) { 12428 if (!RD->hasTrivialDefaultConstructor()) { 12429 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor); 12430 Var->setInvalidDecl(); 12431 return; 12432 } 12433 } 12434 if (Var->getStorageClass() == SC_Extern) { 12435 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl) 12436 << Var; 12437 Var->setInvalidDecl(); 12438 return; 12439 } 12440 } 12441 12442 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition(); 12443 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly && 12444 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 12445 checkNonTrivialCUnion(Var->getType(), Var->getLocation(), 12446 NTCUC_DefaultInitializedObject, NTCUK_Init); 12447 12448 12449 switch (DefKind) { 12450 case VarDecl::Definition: 12451 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 12452 break; 12453 12454 // We have an out-of-line definition of a static data member 12455 // that has an in-class initializer, so we type-check this like 12456 // a declaration. 12457 // 12458 LLVM_FALLTHROUGH; 12459 12460 case VarDecl::DeclarationOnly: 12461 // It's only a declaration. 12462 12463 // Block scope. C99 6.7p7: If an identifier for an object is 12464 // declared with no linkage (C99 6.2.2p6), the type for the 12465 // object shall be complete. 12466 if (!Type->isDependentType() && Var->isLocalVarDecl() && 12467 !Var->hasLinkage() && !Var->isInvalidDecl() && 12468 RequireCompleteType(Var->getLocation(), Type, 12469 diag::err_typecheck_decl_incomplete_type)) 12470 Var->setInvalidDecl(); 12471 12472 // Make sure that the type is not abstract. 12473 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12474 RequireNonAbstractType(Var->getLocation(), Type, 12475 diag::err_abstract_type_in_decl, 12476 AbstractVariableType)) 12477 Var->setInvalidDecl(); 12478 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12479 Var->getStorageClass() == SC_PrivateExtern) { 12480 Diag(Var->getLocation(), diag::warn_private_extern); 12481 Diag(Var->getLocation(), diag::note_private_extern); 12482 } 12483 12484 if (Context.getTargetInfo().allowDebugInfoForExternalVar() && 12485 !Var->isInvalidDecl() && !getLangOpts().CPlusPlus) 12486 ExternalDeclarations.push_back(Var); 12487 12488 return; 12489 12490 case VarDecl::TentativeDefinition: 12491 // File scope. C99 6.9.2p2: A declaration of an identifier for an 12492 // object that has file scope without an initializer, and without a 12493 // storage-class specifier or with the storage-class specifier "static", 12494 // constitutes a tentative definition. Note: A tentative definition with 12495 // external linkage is valid (C99 6.2.2p5). 12496 if (!Var->isInvalidDecl()) { 12497 if (const IncompleteArrayType *ArrayT 12498 = Context.getAsIncompleteArrayType(Type)) { 12499 if (RequireCompleteSizedType( 12500 Var->getLocation(), ArrayT->getElementType(), 12501 diag::err_array_incomplete_or_sizeless_type)) 12502 Var->setInvalidDecl(); 12503 } else if (Var->getStorageClass() == SC_Static) { 12504 // C99 6.9.2p3: If the declaration of an identifier for an object is 12505 // a tentative definition and has internal linkage (C99 6.2.2p3), the 12506 // declared type shall not be an incomplete type. 12507 // NOTE: code such as the following 12508 // static struct s; 12509 // struct s { int a; }; 12510 // is accepted by gcc. Hence here we issue a warning instead of 12511 // an error and we do not invalidate the static declaration. 12512 // NOTE: to avoid multiple warnings, only check the first declaration. 12513 if (Var->isFirstDecl()) 12514 RequireCompleteType(Var->getLocation(), Type, 12515 diag::ext_typecheck_decl_incomplete_type); 12516 } 12517 } 12518 12519 // Record the tentative definition; we're done. 12520 if (!Var->isInvalidDecl()) 12521 TentativeDefinitions.push_back(Var); 12522 return; 12523 } 12524 12525 // Provide a specific diagnostic for uninitialized variable 12526 // definitions with incomplete array type. 12527 if (Type->isIncompleteArrayType()) { 12528 Diag(Var->getLocation(), 12529 diag::err_typecheck_incomplete_array_needs_initializer); 12530 Var->setInvalidDecl(); 12531 return; 12532 } 12533 12534 // Provide a specific diagnostic for uninitialized variable 12535 // definitions with reference type. 12536 if (Type->isReferenceType()) { 12537 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 12538 << Var->getDeclName() 12539 << SourceRange(Var->getLocation(), Var->getLocation()); 12540 Var->setInvalidDecl(); 12541 return; 12542 } 12543 12544 // Do not attempt to type-check the default initializer for a 12545 // variable with dependent type. 12546 if (Type->isDependentType()) 12547 return; 12548 12549 if (Var->isInvalidDecl()) 12550 return; 12551 12552 if (!Var->hasAttr<AliasAttr>()) { 12553 if (RequireCompleteType(Var->getLocation(), 12554 Context.getBaseElementType(Type), 12555 diag::err_typecheck_decl_incomplete_type)) { 12556 Var->setInvalidDecl(); 12557 return; 12558 } 12559 } else { 12560 return; 12561 } 12562 12563 // The variable can not have an abstract class type. 12564 if (RequireNonAbstractType(Var->getLocation(), Type, 12565 diag::err_abstract_type_in_decl, 12566 AbstractVariableType)) { 12567 Var->setInvalidDecl(); 12568 return; 12569 } 12570 12571 // Check for jumps past the implicit initializer. C++0x 12572 // clarifies that this applies to a "variable with automatic 12573 // storage duration", not a "local variable". 12574 // C++11 [stmt.dcl]p3 12575 // A program that jumps from a point where a variable with automatic 12576 // storage duration is not in scope to a point where it is in scope is 12577 // ill-formed unless the variable has scalar type, class type with a 12578 // trivial default constructor and a trivial destructor, a cv-qualified 12579 // version of one of these types, or an array of one of the preceding 12580 // types and is declared without an initializer. 12581 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 12582 if (const RecordType *Record 12583 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 12584 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 12585 // Mark the function (if we're in one) for further checking even if the 12586 // looser rules of C++11 do not require such checks, so that we can 12587 // diagnose incompatibilities with C++98. 12588 if (!CXXRecord->isPOD()) 12589 setFunctionHasBranchProtectedScope(); 12590 } 12591 } 12592 // In OpenCL, we can't initialize objects in the __local address space, 12593 // even implicitly, so don't synthesize an implicit initializer. 12594 if (getLangOpts().OpenCL && 12595 Var->getType().getAddressSpace() == LangAS::opencl_local) 12596 return; 12597 // C++03 [dcl.init]p9: 12598 // If no initializer is specified for an object, and the 12599 // object is of (possibly cv-qualified) non-POD class type (or 12600 // array thereof), the object shall be default-initialized; if 12601 // the object is of const-qualified type, the underlying class 12602 // type shall have a user-declared default 12603 // constructor. Otherwise, if no initializer is specified for 12604 // a non- static object, the object and its subobjects, if 12605 // any, have an indeterminate initial value); if the object 12606 // or any of its subobjects are of const-qualified type, the 12607 // program is ill-formed. 12608 // C++0x [dcl.init]p11: 12609 // If no initializer is specified for an object, the object is 12610 // default-initialized; [...]. 12611 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 12612 InitializationKind Kind 12613 = InitializationKind::CreateDefault(Var->getLocation()); 12614 12615 InitializationSequence InitSeq(*this, Entity, Kind, None); 12616 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 12617 12618 if (Init.get()) { 12619 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 12620 // This is important for template substitution. 12621 Var->setInitStyle(VarDecl::CallInit); 12622 } else if (Init.isInvalid()) { 12623 // If default-init fails, attach a recovery-expr initializer to track 12624 // that initialization was attempted and failed. 12625 auto RecoveryExpr = 12626 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {}); 12627 if (RecoveryExpr.get()) 12628 Var->setInit(RecoveryExpr.get()); 12629 } 12630 12631 CheckCompleteVariableDeclaration(Var); 12632 } 12633 } 12634 12635 void Sema::ActOnCXXForRangeDecl(Decl *D) { 12636 // If there is no declaration, there was an error parsing it. Ignore it. 12637 if (!D) 12638 return; 12639 12640 VarDecl *VD = dyn_cast<VarDecl>(D); 12641 if (!VD) { 12642 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 12643 D->setInvalidDecl(); 12644 return; 12645 } 12646 12647 VD->setCXXForRangeDecl(true); 12648 12649 // for-range-declaration cannot be given a storage class specifier. 12650 int Error = -1; 12651 switch (VD->getStorageClass()) { 12652 case SC_None: 12653 break; 12654 case SC_Extern: 12655 Error = 0; 12656 break; 12657 case SC_Static: 12658 Error = 1; 12659 break; 12660 case SC_PrivateExtern: 12661 Error = 2; 12662 break; 12663 case SC_Auto: 12664 Error = 3; 12665 break; 12666 case SC_Register: 12667 Error = 4; 12668 break; 12669 } 12670 if (Error != -1) { 12671 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 12672 << VD->getDeclName() << Error; 12673 D->setInvalidDecl(); 12674 } 12675 } 12676 12677 StmtResult 12678 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 12679 IdentifierInfo *Ident, 12680 ParsedAttributes &Attrs, 12681 SourceLocation AttrEnd) { 12682 // C++1y [stmt.iter]p1: 12683 // A range-based for statement of the form 12684 // for ( for-range-identifier : for-range-initializer ) statement 12685 // is equivalent to 12686 // for ( auto&& for-range-identifier : for-range-initializer ) statement 12687 DeclSpec DS(Attrs.getPool().getFactory()); 12688 12689 const char *PrevSpec; 12690 unsigned DiagID; 12691 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 12692 getPrintingPolicy()); 12693 12694 Declarator D(DS, DeclaratorContext::ForContext); 12695 D.SetIdentifier(Ident, IdentLoc); 12696 D.takeAttributes(Attrs, AttrEnd); 12697 12698 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false), 12699 IdentLoc); 12700 Decl *Var = ActOnDeclarator(S, D); 12701 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 12702 FinalizeDeclaration(Var); 12703 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 12704 AttrEnd.isValid() ? AttrEnd : IdentLoc); 12705 } 12706 12707 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 12708 if (var->isInvalidDecl()) return; 12709 12710 if (getLangOpts().OpenCL) { 12711 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 12712 // initialiser 12713 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 12714 !var->hasInit()) { 12715 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 12716 << 1 /*Init*/; 12717 var->setInvalidDecl(); 12718 return; 12719 } 12720 } 12721 12722 // In Objective-C, don't allow jumps past the implicit initialization of a 12723 // local retaining variable. 12724 if (getLangOpts().ObjC && 12725 var->hasLocalStorage()) { 12726 switch (var->getType().getObjCLifetime()) { 12727 case Qualifiers::OCL_None: 12728 case Qualifiers::OCL_ExplicitNone: 12729 case Qualifiers::OCL_Autoreleasing: 12730 break; 12731 12732 case Qualifiers::OCL_Weak: 12733 case Qualifiers::OCL_Strong: 12734 setFunctionHasBranchProtectedScope(); 12735 break; 12736 } 12737 } 12738 12739 if (var->hasLocalStorage() && 12740 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 12741 setFunctionHasBranchProtectedScope(); 12742 12743 // Warn about externally-visible variables being defined without a 12744 // prior declaration. We only want to do this for global 12745 // declarations, but we also specifically need to avoid doing it for 12746 // class members because the linkage of an anonymous class can 12747 // change if it's later given a typedef name. 12748 if (var->isThisDeclarationADefinition() && 12749 var->getDeclContext()->getRedeclContext()->isFileContext() && 12750 var->isExternallyVisible() && var->hasLinkage() && 12751 !var->isInline() && !var->getDescribedVarTemplate() && 12752 !isa<VarTemplatePartialSpecializationDecl>(var) && 12753 !isTemplateInstantiation(var->getTemplateSpecializationKind()) && 12754 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 12755 var->getLocation())) { 12756 // Find a previous declaration that's not a definition. 12757 VarDecl *prev = var->getPreviousDecl(); 12758 while (prev && prev->isThisDeclarationADefinition()) 12759 prev = prev->getPreviousDecl(); 12760 12761 if (!prev) { 12762 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 12763 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 12764 << /* variable */ 0; 12765 } 12766 } 12767 12768 // Cache the result of checking for constant initialization. 12769 Optional<bool> CacheHasConstInit; 12770 const Expr *CacheCulprit = nullptr; 12771 auto checkConstInit = [&]() mutable { 12772 if (!CacheHasConstInit) 12773 CacheHasConstInit = var->getInit()->isConstantInitializer( 12774 Context, var->getType()->isReferenceType(), &CacheCulprit); 12775 return *CacheHasConstInit; 12776 }; 12777 12778 if (var->getTLSKind() == VarDecl::TLS_Static) { 12779 if (var->getType().isDestructedType()) { 12780 // GNU C++98 edits for __thread, [basic.start.term]p3: 12781 // The type of an object with thread storage duration shall not 12782 // have a non-trivial destructor. 12783 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 12784 if (getLangOpts().CPlusPlus11) 12785 Diag(var->getLocation(), diag::note_use_thread_local); 12786 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 12787 if (!checkConstInit()) { 12788 // GNU C++98 edits for __thread, [basic.start.init]p4: 12789 // An object of thread storage duration shall not require dynamic 12790 // initialization. 12791 // FIXME: Need strict checking here. 12792 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 12793 << CacheCulprit->getSourceRange(); 12794 if (getLangOpts().CPlusPlus11) 12795 Diag(var->getLocation(), diag::note_use_thread_local); 12796 } 12797 } 12798 } 12799 12800 // Apply section attributes and pragmas to global variables. 12801 bool GlobalStorage = var->hasGlobalStorage(); 12802 if (GlobalStorage && var->isThisDeclarationADefinition() && 12803 !inTemplateInstantiation()) { 12804 PragmaStack<StringLiteral *> *Stack = nullptr; 12805 int SectionFlags = ASTContext::PSF_Read; 12806 if (var->getType().isConstQualified()) 12807 Stack = &ConstSegStack; 12808 else if (!var->getInit()) { 12809 Stack = &BSSSegStack; 12810 SectionFlags |= ASTContext::PSF_Write; 12811 } else { 12812 Stack = &DataSegStack; 12813 SectionFlags |= ASTContext::PSF_Write; 12814 } 12815 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) { 12816 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec) 12817 SectionFlags |= ASTContext::PSF_Implicit; 12818 UnifySection(SA->getName(), SectionFlags, var); 12819 } else if (Stack->CurrentValue) { 12820 SectionFlags |= ASTContext::PSF_Implicit; 12821 auto SectionName = Stack->CurrentValue->getString(); 12822 var->addAttr(SectionAttr::CreateImplicit( 12823 Context, SectionName, Stack->CurrentPragmaLocation, 12824 AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate)); 12825 if (UnifySection(SectionName, SectionFlags, var)) 12826 var->dropAttr<SectionAttr>(); 12827 } 12828 12829 // Apply the init_seg attribute if this has an initializer. If the 12830 // initializer turns out to not be dynamic, we'll end up ignoring this 12831 // attribute. 12832 if (CurInitSeg && var->getInit()) 12833 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 12834 CurInitSegLoc, 12835 AttributeCommonInfo::AS_Pragma)); 12836 } 12837 12838 // All the following checks are C++ only. 12839 if (!getLangOpts().CPlusPlus) { 12840 // If this variable must be emitted, add it as an initializer for the 12841 // current module. 12842 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 12843 Context.addModuleInitializer(ModuleScopes.back().Module, var); 12844 return; 12845 } 12846 12847 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 12848 CheckCompleteDecompositionDeclaration(DD); 12849 12850 QualType type = var->getType(); 12851 if (type->isDependentType()) return; 12852 12853 if (var->hasAttr<BlocksAttr>()) 12854 getCurFunction()->addByrefBlockVar(var); 12855 12856 Expr *Init = var->getInit(); 12857 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 12858 QualType baseType = Context.getBaseElementType(type); 12859 12860 if (Init && !Init->isValueDependent()) { 12861 if (var->isConstexpr()) { 12862 SmallVector<PartialDiagnosticAt, 8> Notes; 12863 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 12864 SourceLocation DiagLoc = var->getLocation(); 12865 // If the note doesn't add any useful information other than a source 12866 // location, fold it into the primary diagnostic. 12867 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 12868 diag::note_invalid_subexpr_in_const_expr) { 12869 DiagLoc = Notes[0].first; 12870 Notes.clear(); 12871 } 12872 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 12873 << var << Init->getSourceRange(); 12874 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 12875 Diag(Notes[I].first, Notes[I].second); 12876 } 12877 } else if (var->mightBeUsableInConstantExpressions(Context)) { 12878 // Check whether the initializer of a const variable of integral or 12879 // enumeration type is an ICE now, since we can't tell whether it was 12880 // initialized by a constant expression if we check later. 12881 var->checkInitIsICE(); 12882 } 12883 12884 // Don't emit further diagnostics about constexpr globals since they 12885 // were just diagnosed. 12886 if (!var->isConstexpr() && GlobalStorage && var->hasAttr<ConstInitAttr>()) { 12887 // FIXME: Need strict checking in C++03 here. 12888 bool DiagErr = getLangOpts().CPlusPlus11 12889 ? !var->checkInitIsICE() : !checkConstInit(); 12890 if (DiagErr) { 12891 auto *Attr = var->getAttr<ConstInitAttr>(); 12892 Diag(var->getLocation(), diag::err_require_constant_init_failed) 12893 << Init->getSourceRange(); 12894 Diag(Attr->getLocation(), 12895 diag::note_declared_required_constant_init_here) 12896 << Attr->getRange() << Attr->isConstinit(); 12897 if (getLangOpts().CPlusPlus11) { 12898 APValue Value; 12899 SmallVector<PartialDiagnosticAt, 8> Notes; 12900 Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes); 12901 for (auto &it : Notes) 12902 Diag(it.first, it.second); 12903 } else { 12904 Diag(CacheCulprit->getExprLoc(), 12905 diag::note_invalid_subexpr_in_const_expr) 12906 << CacheCulprit->getSourceRange(); 12907 } 12908 } 12909 } 12910 else if (!var->isConstexpr() && IsGlobal && 12911 !getDiagnostics().isIgnored(diag::warn_global_constructor, 12912 var->getLocation())) { 12913 // Warn about globals which don't have a constant initializer. Don't 12914 // warn about globals with a non-trivial destructor because we already 12915 // warned about them. 12916 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 12917 if (!(RD && !RD->hasTrivialDestructor())) { 12918 if (!checkConstInit()) 12919 Diag(var->getLocation(), diag::warn_global_constructor) 12920 << Init->getSourceRange(); 12921 } 12922 } 12923 } 12924 12925 // Require the destructor. 12926 if (const RecordType *recordType = baseType->getAs<RecordType>()) 12927 FinalizeVarWithDestructor(var, recordType); 12928 12929 // If this variable must be emitted, add it as an initializer for the current 12930 // module. 12931 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 12932 Context.addModuleInitializer(ModuleScopes.back().Module, var); 12933 } 12934 12935 /// Determines if a variable's alignment is dependent. 12936 static bool hasDependentAlignment(VarDecl *VD) { 12937 if (VD->getType()->isDependentType()) 12938 return true; 12939 for (auto *I : VD->specific_attrs<AlignedAttr>()) 12940 if (I->isAlignmentDependent()) 12941 return true; 12942 return false; 12943 } 12944 12945 /// Check if VD needs to be dllexport/dllimport due to being in a 12946 /// dllexport/import function. 12947 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) { 12948 assert(VD->isStaticLocal()); 12949 12950 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 12951 12952 // Find outermost function when VD is in lambda function. 12953 while (FD && !getDLLAttr(FD) && 12954 !FD->hasAttr<DLLExportStaticLocalAttr>() && 12955 !FD->hasAttr<DLLImportStaticLocalAttr>()) { 12956 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod()); 12957 } 12958 12959 if (!FD) 12960 return; 12961 12962 // Static locals inherit dll attributes from their function. 12963 if (Attr *A = getDLLAttr(FD)) { 12964 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 12965 NewAttr->setInherited(true); 12966 VD->addAttr(NewAttr); 12967 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) { 12968 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A); 12969 NewAttr->setInherited(true); 12970 VD->addAttr(NewAttr); 12971 12972 // Export this function to enforce exporting this static variable even 12973 // if it is not used in this compilation unit. 12974 if (!FD->hasAttr<DLLExportAttr>()) 12975 FD->addAttr(NewAttr); 12976 12977 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) { 12978 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A); 12979 NewAttr->setInherited(true); 12980 VD->addAttr(NewAttr); 12981 } 12982 } 12983 12984 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 12985 /// any semantic actions necessary after any initializer has been attached. 12986 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 12987 // Note that we are no longer parsing the initializer for this declaration. 12988 ParsingInitForAutoVars.erase(ThisDecl); 12989 12990 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 12991 if (!VD) 12992 return; 12993 12994 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active 12995 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && 12996 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { 12997 if (PragmaClangBSSSection.Valid) 12998 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit( 12999 Context, PragmaClangBSSSection.SectionName, 13000 PragmaClangBSSSection.PragmaLocation, 13001 AttributeCommonInfo::AS_Pragma)); 13002 if (PragmaClangDataSection.Valid) 13003 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit( 13004 Context, PragmaClangDataSection.SectionName, 13005 PragmaClangDataSection.PragmaLocation, 13006 AttributeCommonInfo::AS_Pragma)); 13007 if (PragmaClangRodataSection.Valid) 13008 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit( 13009 Context, PragmaClangRodataSection.SectionName, 13010 PragmaClangRodataSection.PragmaLocation, 13011 AttributeCommonInfo::AS_Pragma)); 13012 if (PragmaClangRelroSection.Valid) 13013 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit( 13014 Context, PragmaClangRelroSection.SectionName, 13015 PragmaClangRelroSection.PragmaLocation, 13016 AttributeCommonInfo::AS_Pragma)); 13017 } 13018 13019 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 13020 for (auto *BD : DD->bindings()) { 13021 FinalizeDeclaration(BD); 13022 } 13023 } 13024 13025 checkAttributesAfterMerging(*this, *VD); 13026 13027 // Perform TLS alignment check here after attributes attached to the variable 13028 // which may affect the alignment have been processed. Only perform the check 13029 // if the target has a maximum TLS alignment (zero means no constraints). 13030 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 13031 // Protect the check so that it's not performed on dependent types and 13032 // dependent alignments (we can't determine the alignment in that case). 13033 if (VD->getTLSKind() && !hasDependentAlignment(VD) && 13034 !VD->isInvalidDecl()) { 13035 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 13036 if (Context.getDeclAlign(VD) > MaxAlignChars) { 13037 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 13038 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 13039 << (unsigned)MaxAlignChars.getQuantity(); 13040 } 13041 } 13042 } 13043 13044 if (VD->isStaticLocal()) { 13045 CheckStaticLocalForDllExport(VD); 13046 13047 if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { 13048 // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__ 13049 // function, only __shared__ variables or variables without any device 13050 // memory qualifiers may be declared with static storage class. 13051 // Note: It is unclear how a function-scope non-const static variable 13052 // without device memory qualifier is implemented, therefore only static 13053 // const variable without device memory qualifier is allowed. 13054 [&]() { 13055 if (!getLangOpts().CUDA) 13056 return; 13057 if (VD->hasAttr<CUDASharedAttr>()) 13058 return; 13059 if (VD->getType().isConstQualified() && 13060 !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>())) 13061 return; 13062 if (CUDADiagIfDeviceCode(VD->getLocation(), 13063 diag::err_device_static_local_var) 13064 << CurrentCUDATarget()) 13065 VD->setInvalidDecl(); 13066 }(); 13067 } 13068 } 13069 13070 // Perform check for initializers of device-side global variables. 13071 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 13072 // 7.5). We must also apply the same checks to all __shared__ 13073 // variables whether they are local or not. CUDA also allows 13074 // constant initializers for __constant__ and __device__ variables. 13075 if (getLangOpts().CUDA) 13076 checkAllowedCUDAInitializer(VD); 13077 13078 // Grab the dllimport or dllexport attribute off of the VarDecl. 13079 const InheritableAttr *DLLAttr = getDLLAttr(VD); 13080 13081 // Imported static data members cannot be defined out-of-line. 13082 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 13083 if (VD->isStaticDataMember() && VD->isOutOfLine() && 13084 VD->isThisDeclarationADefinition()) { 13085 // We allow definitions of dllimport class template static data members 13086 // with a warning. 13087 CXXRecordDecl *Context = 13088 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 13089 bool IsClassTemplateMember = 13090 isa<ClassTemplatePartialSpecializationDecl>(Context) || 13091 Context->getDescribedClassTemplate(); 13092 13093 Diag(VD->getLocation(), 13094 IsClassTemplateMember 13095 ? diag::warn_attribute_dllimport_static_field_definition 13096 : diag::err_attribute_dllimport_static_field_definition); 13097 Diag(IA->getLocation(), diag::note_attribute); 13098 if (!IsClassTemplateMember) 13099 VD->setInvalidDecl(); 13100 } 13101 } 13102 13103 // dllimport/dllexport variables cannot be thread local, their TLS index 13104 // isn't exported with the variable. 13105 if (DLLAttr && VD->getTLSKind()) { 13106 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 13107 if (F && getDLLAttr(F)) { 13108 assert(VD->isStaticLocal()); 13109 // But if this is a static local in a dlimport/dllexport function, the 13110 // function will never be inlined, which means the var would never be 13111 // imported, so having it marked import/export is safe. 13112 } else { 13113 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 13114 << DLLAttr; 13115 VD->setInvalidDecl(); 13116 } 13117 } 13118 13119 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 13120 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 13121 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 13122 VD->dropAttr<UsedAttr>(); 13123 } 13124 } 13125 13126 const DeclContext *DC = VD->getDeclContext(); 13127 // If there's a #pragma GCC visibility in scope, and this isn't a class 13128 // member, set the visibility of this variable. 13129 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 13130 AddPushedVisibilityAttribute(VD); 13131 13132 // FIXME: Warn on unused var template partial specializations. 13133 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 13134 MarkUnusedFileScopedDecl(VD); 13135 13136 // Now we have parsed the initializer and can update the table of magic 13137 // tag values. 13138 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 13139 !VD->getType()->isIntegralOrEnumerationType()) 13140 return; 13141 13142 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 13143 const Expr *MagicValueExpr = VD->getInit(); 13144 if (!MagicValueExpr) { 13145 continue; 13146 } 13147 llvm::APSInt MagicValueInt; 13148 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 13149 Diag(I->getRange().getBegin(), 13150 diag::err_type_tag_for_datatype_not_ice) 13151 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13152 continue; 13153 } 13154 if (MagicValueInt.getActiveBits() > 64) { 13155 Diag(I->getRange().getBegin(), 13156 diag::err_type_tag_for_datatype_too_large) 13157 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13158 continue; 13159 } 13160 uint64_t MagicValue = MagicValueInt.getZExtValue(); 13161 RegisterTypeTagForDatatype(I->getArgumentKind(), 13162 MagicValue, 13163 I->getMatchingCType(), 13164 I->getLayoutCompatible(), 13165 I->getMustBeNull()); 13166 } 13167 } 13168 13169 static bool hasDeducedAuto(DeclaratorDecl *DD) { 13170 auto *VD = dyn_cast<VarDecl>(DD); 13171 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 13172 } 13173 13174 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 13175 ArrayRef<Decl *> Group) { 13176 SmallVector<Decl*, 8> Decls; 13177 13178 if (DS.isTypeSpecOwned()) 13179 Decls.push_back(DS.getRepAsDecl()); 13180 13181 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 13182 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 13183 bool DiagnosedMultipleDecomps = false; 13184 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 13185 bool DiagnosedNonDeducedAuto = false; 13186 13187 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13188 if (Decl *D = Group[i]) { 13189 // For declarators, there are some additional syntactic-ish checks we need 13190 // to perform. 13191 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 13192 if (!FirstDeclaratorInGroup) 13193 FirstDeclaratorInGroup = DD; 13194 if (!FirstDecompDeclaratorInGroup) 13195 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 13196 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 13197 !hasDeducedAuto(DD)) 13198 FirstNonDeducedAutoInGroup = DD; 13199 13200 if (FirstDeclaratorInGroup != DD) { 13201 // A decomposition declaration cannot be combined with any other 13202 // declaration in the same group. 13203 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 13204 Diag(FirstDecompDeclaratorInGroup->getLocation(), 13205 diag::err_decomp_decl_not_alone) 13206 << FirstDeclaratorInGroup->getSourceRange() 13207 << DD->getSourceRange(); 13208 DiagnosedMultipleDecomps = true; 13209 } 13210 13211 // A declarator that uses 'auto' in any way other than to declare a 13212 // variable with a deduced type cannot be combined with any other 13213 // declarator in the same group. 13214 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 13215 Diag(FirstNonDeducedAutoInGroup->getLocation(), 13216 diag::err_auto_non_deduced_not_alone) 13217 << FirstNonDeducedAutoInGroup->getType() 13218 ->hasAutoForTrailingReturnType() 13219 << FirstDeclaratorInGroup->getSourceRange() 13220 << DD->getSourceRange(); 13221 DiagnosedNonDeducedAuto = true; 13222 } 13223 } 13224 } 13225 13226 Decls.push_back(D); 13227 } 13228 } 13229 13230 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 13231 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 13232 handleTagNumbering(Tag, S); 13233 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 13234 getLangOpts().CPlusPlus) 13235 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 13236 } 13237 } 13238 13239 return BuildDeclaratorGroup(Decls); 13240 } 13241 13242 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 13243 /// group, performing any necessary semantic checking. 13244 Sema::DeclGroupPtrTy 13245 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 13246 // C++14 [dcl.spec.auto]p7: (DR1347) 13247 // If the type that replaces the placeholder type is not the same in each 13248 // deduction, the program is ill-formed. 13249 if (Group.size() > 1) { 13250 QualType Deduced; 13251 VarDecl *DeducedDecl = nullptr; 13252 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13253 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 13254 if (!D || D->isInvalidDecl()) 13255 break; 13256 DeducedType *DT = D->getType()->getContainedDeducedType(); 13257 if (!DT || DT->getDeducedType().isNull()) 13258 continue; 13259 if (Deduced.isNull()) { 13260 Deduced = DT->getDeducedType(); 13261 DeducedDecl = D; 13262 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 13263 auto *AT = dyn_cast<AutoType>(DT); 13264 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 13265 diag::err_auto_different_deductions) 13266 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced 13267 << DeducedDecl->getDeclName() << DT->getDeducedType() 13268 << D->getDeclName(); 13269 if (DeducedDecl->hasInit()) 13270 Dia << DeducedDecl->getInit()->getSourceRange(); 13271 if (D->getInit()) 13272 Dia << D->getInit()->getSourceRange(); 13273 D->setInvalidDecl(); 13274 break; 13275 } 13276 } 13277 } 13278 13279 ActOnDocumentableDecls(Group); 13280 13281 return DeclGroupPtrTy::make( 13282 DeclGroupRef::Create(Context, Group.data(), Group.size())); 13283 } 13284 13285 void Sema::ActOnDocumentableDecl(Decl *D) { 13286 ActOnDocumentableDecls(D); 13287 } 13288 13289 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 13290 // Don't parse the comment if Doxygen diagnostics are ignored. 13291 if (Group.empty() || !Group[0]) 13292 return; 13293 13294 if (Diags.isIgnored(diag::warn_doc_param_not_found, 13295 Group[0]->getLocation()) && 13296 Diags.isIgnored(diag::warn_unknown_comment_command_name, 13297 Group[0]->getLocation())) 13298 return; 13299 13300 if (Group.size() >= 2) { 13301 // This is a decl group. Normally it will contain only declarations 13302 // produced from declarator list. But in case we have any definitions or 13303 // additional declaration references: 13304 // 'typedef struct S {} S;' 13305 // 'typedef struct S *S;' 13306 // 'struct S *pS;' 13307 // FinalizeDeclaratorGroup adds these as separate declarations. 13308 Decl *MaybeTagDecl = Group[0]; 13309 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 13310 Group = Group.slice(1); 13311 } 13312 } 13313 13314 // FIMXE: We assume every Decl in the group is in the same file. 13315 // This is false when preprocessor constructs the group from decls in 13316 // different files (e. g. macros or #include). 13317 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor()); 13318 } 13319 13320 /// Common checks for a parameter-declaration that should apply to both function 13321 /// parameters and non-type template parameters. 13322 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) { 13323 // Check that there are no default arguments inside the type of this 13324 // parameter. 13325 if (getLangOpts().CPlusPlus) 13326 CheckExtraCXXDefaultArguments(D); 13327 13328 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 13329 if (D.getCXXScopeSpec().isSet()) { 13330 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 13331 << D.getCXXScopeSpec().getRange(); 13332 } 13333 13334 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a 13335 // simple identifier except [...irrelevant cases...]. 13336 switch (D.getName().getKind()) { 13337 case UnqualifiedIdKind::IK_Identifier: 13338 break; 13339 13340 case UnqualifiedIdKind::IK_OperatorFunctionId: 13341 case UnqualifiedIdKind::IK_ConversionFunctionId: 13342 case UnqualifiedIdKind::IK_LiteralOperatorId: 13343 case UnqualifiedIdKind::IK_ConstructorName: 13344 case UnqualifiedIdKind::IK_DestructorName: 13345 case UnqualifiedIdKind::IK_ImplicitSelfParam: 13346 case UnqualifiedIdKind::IK_DeductionGuideName: 13347 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 13348 << GetNameForDeclarator(D).getName(); 13349 break; 13350 13351 case UnqualifiedIdKind::IK_TemplateId: 13352 case UnqualifiedIdKind::IK_ConstructorTemplateId: 13353 // GetNameForDeclarator would not produce a useful name in this case. 13354 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id); 13355 break; 13356 } 13357 } 13358 13359 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 13360 /// to introduce parameters into function prototype scope. 13361 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 13362 const DeclSpec &DS = D.getDeclSpec(); 13363 13364 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 13365 13366 // C++03 [dcl.stc]p2 also permits 'auto'. 13367 StorageClass SC = SC_None; 13368 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 13369 SC = SC_Register; 13370 // In C++11, the 'register' storage class specifier is deprecated. 13371 // In C++17, it is not allowed, but we tolerate it as an extension. 13372 if (getLangOpts().CPlusPlus11) { 13373 Diag(DS.getStorageClassSpecLoc(), 13374 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 13375 : diag::warn_deprecated_register) 13376 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 13377 } 13378 } else if (getLangOpts().CPlusPlus && 13379 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 13380 SC = SC_Auto; 13381 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 13382 Diag(DS.getStorageClassSpecLoc(), 13383 diag::err_invalid_storage_class_in_func_decl); 13384 D.getMutableDeclSpec().ClearStorageClassSpecs(); 13385 } 13386 13387 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 13388 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 13389 << DeclSpec::getSpecifierName(TSCS); 13390 if (DS.isInlineSpecified()) 13391 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 13392 << getLangOpts().CPlusPlus17; 13393 if (DS.hasConstexprSpecifier()) 13394 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 13395 << 0 << D.getDeclSpec().getConstexprSpecifier(); 13396 13397 DiagnoseFunctionSpecifiers(DS); 13398 13399 CheckFunctionOrTemplateParamDeclarator(S, D); 13400 13401 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13402 QualType parmDeclType = TInfo->getType(); 13403 13404 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 13405 IdentifierInfo *II = D.getIdentifier(); 13406 if (II) { 13407 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 13408 ForVisibleRedeclaration); 13409 LookupName(R, S); 13410 if (R.isSingleResult()) { 13411 NamedDecl *PrevDecl = R.getFoundDecl(); 13412 if (PrevDecl->isTemplateParameter()) { 13413 // Maybe we will complain about the shadowed template parameter. 13414 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13415 // Just pretend that we didn't see the previous declaration. 13416 PrevDecl = nullptr; 13417 } else if (S->isDeclScope(PrevDecl)) { 13418 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 13419 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 13420 13421 // Recover by removing the name 13422 II = nullptr; 13423 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 13424 D.setInvalidType(true); 13425 } 13426 } 13427 } 13428 13429 // Temporarily put parameter variables in the translation unit, not 13430 // the enclosing context. This prevents them from accidentally 13431 // looking like class members in C++. 13432 ParmVarDecl *New = 13433 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(), 13434 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC); 13435 13436 if (D.isInvalidType()) 13437 New->setInvalidDecl(); 13438 13439 assert(S->isFunctionPrototypeScope()); 13440 assert(S->getFunctionPrototypeDepth() >= 1); 13441 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 13442 S->getNextFunctionPrototypeIndex()); 13443 13444 // Add the parameter declaration into this scope. 13445 S->AddDecl(New); 13446 if (II) 13447 IdResolver.AddDecl(New); 13448 13449 ProcessDeclAttributes(S, New, D); 13450 13451 if (D.getDeclSpec().isModulePrivateSpecified()) 13452 Diag(New->getLocation(), diag::err_module_private_local) 13453 << 1 << New->getDeclName() 13454 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 13455 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 13456 13457 if (New->hasAttr<BlocksAttr>()) { 13458 Diag(New->getLocation(), diag::err_block_on_nonlocal); 13459 } 13460 13461 if (getLangOpts().OpenCL) 13462 deduceOpenCLAddressSpace(New); 13463 13464 return New; 13465 } 13466 13467 /// Synthesizes a variable for a parameter arising from a 13468 /// typedef. 13469 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 13470 SourceLocation Loc, 13471 QualType T) { 13472 /* FIXME: setting StartLoc == Loc. 13473 Would it be worth to modify callers so as to provide proper source 13474 location for the unnamed parameters, embedding the parameter's type? */ 13475 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 13476 T, Context.getTrivialTypeSourceInfo(T, Loc), 13477 SC_None, nullptr); 13478 Param->setImplicit(); 13479 return Param; 13480 } 13481 13482 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 13483 // Don't diagnose unused-parameter errors in template instantiations; we 13484 // will already have done so in the template itself. 13485 if (inTemplateInstantiation()) 13486 return; 13487 13488 for (const ParmVarDecl *Parameter : Parameters) { 13489 if (!Parameter->isReferenced() && Parameter->getDeclName() && 13490 !Parameter->hasAttr<UnusedAttr>()) { 13491 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 13492 << Parameter->getDeclName(); 13493 } 13494 } 13495 } 13496 13497 void Sema::DiagnoseSizeOfParametersAndReturnValue( 13498 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 13499 if (LangOpts.NumLargeByValueCopy == 0) // No check. 13500 return; 13501 13502 // Warn if the return value is pass-by-value and larger than the specified 13503 // threshold. 13504 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 13505 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 13506 if (Size > LangOpts.NumLargeByValueCopy) 13507 Diag(D->getLocation(), diag::warn_return_value_size) 13508 << D->getDeclName() << Size; 13509 } 13510 13511 // Warn if any parameter is pass-by-value and larger than the specified 13512 // threshold. 13513 for (const ParmVarDecl *Parameter : Parameters) { 13514 QualType T = Parameter->getType(); 13515 if (T->isDependentType() || !T.isPODType(Context)) 13516 continue; 13517 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 13518 if (Size > LangOpts.NumLargeByValueCopy) 13519 Diag(Parameter->getLocation(), diag::warn_parameter_size) 13520 << Parameter->getDeclName() << Size; 13521 } 13522 } 13523 13524 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 13525 SourceLocation NameLoc, IdentifierInfo *Name, 13526 QualType T, TypeSourceInfo *TSInfo, 13527 StorageClass SC) { 13528 // In ARC, infer a lifetime qualifier for appropriate parameter types. 13529 if (getLangOpts().ObjCAutoRefCount && 13530 T.getObjCLifetime() == Qualifiers::OCL_None && 13531 T->isObjCLifetimeType()) { 13532 13533 Qualifiers::ObjCLifetime lifetime; 13534 13535 // Special cases for arrays: 13536 // - if it's const, use __unsafe_unretained 13537 // - otherwise, it's an error 13538 if (T->isArrayType()) { 13539 if (!T.isConstQualified()) { 13540 if (DelayedDiagnostics.shouldDelayDiagnostics()) 13541 DelayedDiagnostics.add( 13542 sema::DelayedDiagnostic::makeForbiddenType( 13543 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 13544 else 13545 Diag(NameLoc, diag::err_arc_array_param_no_ownership) 13546 << TSInfo->getTypeLoc().getSourceRange(); 13547 } 13548 lifetime = Qualifiers::OCL_ExplicitNone; 13549 } else { 13550 lifetime = T->getObjCARCImplicitLifetime(); 13551 } 13552 T = Context.getLifetimeQualifiedType(T, lifetime); 13553 } 13554 13555 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 13556 Context.getAdjustedParameterType(T), 13557 TSInfo, SC, nullptr); 13558 13559 // Make a note if we created a new pack in the scope of a lambda, so that 13560 // we know that references to that pack must also be expanded within the 13561 // lambda scope. 13562 if (New->isParameterPack()) 13563 if (auto *LSI = getEnclosingLambda()) 13564 LSI->LocalPacks.push_back(New); 13565 13566 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() || 13567 New->getType().hasNonTrivialToPrimitiveCopyCUnion()) 13568 checkNonTrivialCUnion(New->getType(), New->getLocation(), 13569 NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy); 13570 13571 // Parameters can not be abstract class types. 13572 // For record types, this is done by the AbstractClassUsageDiagnoser once 13573 // the class has been completely parsed. 13574 if (!CurContext->isRecord() && 13575 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 13576 AbstractParamType)) 13577 New->setInvalidDecl(); 13578 13579 // Parameter declarators cannot be interface types. All ObjC objects are 13580 // passed by reference. 13581 if (T->isObjCObjectType()) { 13582 SourceLocation TypeEndLoc = 13583 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc()); 13584 Diag(NameLoc, 13585 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 13586 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 13587 T = Context.getObjCObjectPointerType(T); 13588 New->setType(T); 13589 } 13590 13591 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 13592 // duration shall not be qualified by an address-space qualifier." 13593 // Since all parameters have automatic store duration, they can not have 13594 // an address space. 13595 if (T.getAddressSpace() != LangAS::Default && 13596 // OpenCL allows function arguments declared to be an array of a type 13597 // to be qualified with an address space. 13598 !(getLangOpts().OpenCL && 13599 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) { 13600 Diag(NameLoc, diag::err_arg_with_address_space); 13601 New->setInvalidDecl(); 13602 } 13603 13604 return New; 13605 } 13606 13607 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 13608 SourceLocation LocAfterDecls) { 13609 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 13610 13611 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 13612 // for a K&R function. 13613 if (!FTI.hasPrototype) { 13614 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 13615 --i; 13616 if (FTI.Params[i].Param == nullptr) { 13617 SmallString<256> Code; 13618 llvm::raw_svector_ostream(Code) 13619 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 13620 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 13621 << FTI.Params[i].Ident 13622 << FixItHint::CreateInsertion(LocAfterDecls, Code); 13623 13624 // Implicitly declare the argument as type 'int' for lack of a better 13625 // type. 13626 AttributeFactory attrs; 13627 DeclSpec DS(attrs); 13628 const char* PrevSpec; // unused 13629 unsigned DiagID; // unused 13630 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 13631 DiagID, Context.getPrintingPolicy()); 13632 // Use the identifier location for the type source range. 13633 DS.SetRangeStart(FTI.Params[i].IdentLoc); 13634 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 13635 Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext); 13636 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 13637 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 13638 } 13639 } 13640 } 13641 } 13642 13643 Decl * 13644 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 13645 MultiTemplateParamsArg TemplateParameterLists, 13646 SkipBodyInfo *SkipBody) { 13647 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 13648 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 13649 Scope *ParentScope = FnBodyScope->getParent(); 13650 13651 // Check if we are in an `omp begin/end declare variant` scope. If we are, and 13652 // we define a non-templated function definition, we will create a declaration 13653 // instead (=BaseFD), and emit the definition with a mangled name afterwards. 13654 // The base function declaration will have the equivalent of an `omp declare 13655 // variant` annotation which specifies the mangled definition as a 13656 // specialization function under the OpenMP context defined as part of the 13657 // `omp begin declare variant`. 13658 FunctionDecl *BaseFD = nullptr; 13659 if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope() && 13660 TemplateParameterLists.empty()) 13661 BaseFD = ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( 13662 ParentScope, D); 13663 13664 D.setFunctionDefinitionKind(FDK_Definition); 13665 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 13666 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 13667 13668 if (BaseFD) 13669 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope( 13670 cast<FunctionDecl>(Dcl), BaseFD); 13671 13672 return Dcl; 13673 } 13674 13675 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 13676 Consumer.HandleInlineFunctionDefinition(D); 13677 } 13678 13679 static bool 13680 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 13681 const FunctionDecl *&PossiblePrototype) { 13682 // Don't warn about invalid declarations. 13683 if (FD->isInvalidDecl()) 13684 return false; 13685 13686 // Or declarations that aren't global. 13687 if (!FD->isGlobal()) 13688 return false; 13689 13690 // Don't warn about C++ member functions. 13691 if (isa<CXXMethodDecl>(FD)) 13692 return false; 13693 13694 // Don't warn about 'main'. 13695 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext())) 13696 if (IdentifierInfo *II = FD->getIdentifier()) 13697 if (II->isStr("main")) 13698 return false; 13699 13700 // Don't warn about inline functions. 13701 if (FD->isInlined()) 13702 return false; 13703 13704 // Don't warn about function templates. 13705 if (FD->getDescribedFunctionTemplate()) 13706 return false; 13707 13708 // Don't warn about function template specializations. 13709 if (FD->isFunctionTemplateSpecialization()) 13710 return false; 13711 13712 // Don't warn for OpenCL kernels. 13713 if (FD->hasAttr<OpenCLKernelAttr>()) 13714 return false; 13715 13716 // Don't warn on explicitly deleted functions. 13717 if (FD->isDeleted()) 13718 return false; 13719 13720 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 13721 Prev; Prev = Prev->getPreviousDecl()) { 13722 // Ignore any declarations that occur in function or method 13723 // scope, because they aren't visible from the header. 13724 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 13725 continue; 13726 13727 PossiblePrototype = Prev; 13728 return Prev->getType()->isFunctionNoProtoType(); 13729 } 13730 13731 return true; 13732 } 13733 13734 void 13735 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 13736 const FunctionDecl *EffectiveDefinition, 13737 SkipBodyInfo *SkipBody) { 13738 const FunctionDecl *Definition = EffectiveDefinition; 13739 if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) { 13740 // If this is a friend function defined in a class template, it does not 13741 // have a body until it is used, nevertheless it is a definition, see 13742 // [temp.inst]p2: 13743 // 13744 // ... for the purpose of determining whether an instantiated redeclaration 13745 // is valid according to [basic.def.odr] and [class.mem], a declaration that 13746 // corresponds to a definition in the template is considered to be a 13747 // definition. 13748 // 13749 // The following code must produce redefinition error: 13750 // 13751 // template<typename T> struct C20 { friend void func_20() {} }; 13752 // C20<int> c20i; 13753 // void func_20() {} 13754 // 13755 for (auto I : FD->redecls()) { 13756 if (I != FD && !I->isInvalidDecl() && 13757 I->getFriendObjectKind() != Decl::FOK_None) { 13758 if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) { 13759 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { 13760 // A merged copy of the same function, instantiated as a member of 13761 // the same class, is OK. 13762 if (declaresSameEntity(OrigFD, Original) && 13763 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()), 13764 cast<Decl>(FD->getLexicalDeclContext()))) 13765 continue; 13766 } 13767 13768 if (Original->isThisDeclarationADefinition()) { 13769 Definition = I; 13770 break; 13771 } 13772 } 13773 } 13774 } 13775 } 13776 13777 if (!Definition) 13778 // Similar to friend functions a friend function template may be a 13779 // definition and do not have a body if it is instantiated in a class 13780 // template. 13781 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) { 13782 for (auto I : FTD->redecls()) { 13783 auto D = cast<FunctionTemplateDecl>(I); 13784 if (D != FTD) { 13785 assert(!D->isThisDeclarationADefinition() && 13786 "More than one definition in redeclaration chain"); 13787 if (D->getFriendObjectKind() != Decl::FOK_None) 13788 if (FunctionTemplateDecl *FT = 13789 D->getInstantiatedFromMemberTemplate()) { 13790 if (FT->isThisDeclarationADefinition()) { 13791 Definition = D->getTemplatedDecl(); 13792 break; 13793 } 13794 } 13795 } 13796 } 13797 } 13798 13799 if (!Definition) 13800 return; 13801 13802 if (canRedefineFunction(Definition, getLangOpts())) 13803 return; 13804 13805 // Don't emit an error when this is redefinition of a typo-corrected 13806 // definition. 13807 if (TypoCorrectedFunctionDefinitions.count(Definition)) 13808 return; 13809 13810 // If we don't have a visible definition of the function, and it's inline or 13811 // a template, skip the new definition. 13812 if (SkipBody && !hasVisibleDefinition(Definition) && 13813 (Definition->getFormalLinkage() == InternalLinkage || 13814 Definition->isInlined() || 13815 Definition->getDescribedFunctionTemplate() || 13816 Definition->getNumTemplateParameterLists())) { 13817 SkipBody->ShouldSkip = true; 13818 SkipBody->Previous = const_cast<FunctionDecl*>(Definition); 13819 if (auto *TD = Definition->getDescribedFunctionTemplate()) 13820 makeMergedDefinitionVisible(TD); 13821 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 13822 return; 13823 } 13824 13825 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 13826 Definition->getStorageClass() == SC_Extern) 13827 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 13828 << FD->getDeclName() << getLangOpts().CPlusPlus; 13829 else 13830 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 13831 13832 Diag(Definition->getLocation(), diag::note_previous_definition); 13833 FD->setInvalidDecl(); 13834 } 13835 13836 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 13837 Sema &S) { 13838 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 13839 13840 LambdaScopeInfo *LSI = S.PushLambdaScope(); 13841 LSI->CallOperator = CallOperator; 13842 LSI->Lambda = LambdaClass; 13843 LSI->ReturnType = CallOperator->getReturnType(); 13844 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 13845 13846 if (LCD == LCD_None) 13847 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 13848 else if (LCD == LCD_ByCopy) 13849 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 13850 else if (LCD == LCD_ByRef) 13851 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 13852 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 13853 13854 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 13855 LSI->Mutable = !CallOperator->isConst(); 13856 13857 // Add the captures to the LSI so they can be noted as already 13858 // captured within tryCaptureVar. 13859 auto I = LambdaClass->field_begin(); 13860 for (const auto &C : LambdaClass->captures()) { 13861 if (C.capturesVariable()) { 13862 VarDecl *VD = C.getCapturedVar(); 13863 if (VD->isInitCapture()) 13864 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 13865 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 13866 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 13867 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 13868 /*EllipsisLoc*/C.isPackExpansion() 13869 ? C.getEllipsisLoc() : SourceLocation(), 13870 I->getType(), /*Invalid*/false); 13871 13872 } else if (C.capturesThis()) { 13873 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(), 13874 C.getCaptureKind() == LCK_StarThis); 13875 } else { 13876 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(), 13877 I->getType()); 13878 } 13879 ++I; 13880 } 13881 } 13882 13883 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 13884 SkipBodyInfo *SkipBody) { 13885 if (!D) { 13886 // Parsing the function declaration failed in some way. Push on a fake scope 13887 // anyway so we can try to parse the function body. 13888 PushFunctionScope(); 13889 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 13890 return D; 13891 } 13892 13893 FunctionDecl *FD = nullptr; 13894 13895 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 13896 FD = FunTmpl->getTemplatedDecl(); 13897 else 13898 FD = cast<FunctionDecl>(D); 13899 13900 // Do not push if it is a lambda because one is already pushed when building 13901 // the lambda in ActOnStartOfLambdaDefinition(). 13902 if (!isLambdaCallOperator(FD)) 13903 PushExpressionEvaluationContext( 13904 FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated 13905 : ExprEvalContexts.back().Context); 13906 13907 // Check for defining attributes before the check for redefinition. 13908 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 13909 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 13910 FD->dropAttr<AliasAttr>(); 13911 FD->setInvalidDecl(); 13912 } 13913 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 13914 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 13915 FD->dropAttr<IFuncAttr>(); 13916 FD->setInvalidDecl(); 13917 } 13918 13919 // See if this is a redefinition. If 'will have body' is already set, then 13920 // these checks were already performed when it was set. 13921 if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) { 13922 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 13923 13924 // If we're skipping the body, we're done. Don't enter the scope. 13925 if (SkipBody && SkipBody->ShouldSkip) 13926 return D; 13927 } 13928 13929 // Mark this function as "will have a body eventually". This lets users to 13930 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 13931 // this function. 13932 FD->setWillHaveBody(); 13933 13934 // If we are instantiating a generic lambda call operator, push 13935 // a LambdaScopeInfo onto the function stack. But use the information 13936 // that's already been calculated (ActOnLambdaExpr) to prime the current 13937 // LambdaScopeInfo. 13938 // When the template operator is being specialized, the LambdaScopeInfo, 13939 // has to be properly restored so that tryCaptureVariable doesn't try 13940 // and capture any new variables. In addition when calculating potential 13941 // captures during transformation of nested lambdas, it is necessary to 13942 // have the LSI properly restored. 13943 if (isGenericLambdaCallOperatorSpecialization(FD)) { 13944 assert(inTemplateInstantiation() && 13945 "There should be an active template instantiation on the stack " 13946 "when instantiating a generic lambda!"); 13947 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 13948 } else { 13949 // Enter a new function scope 13950 PushFunctionScope(); 13951 } 13952 13953 // Builtin functions cannot be defined. 13954 if (unsigned BuiltinID = FD->getBuiltinID()) { 13955 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 13956 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 13957 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 13958 FD->setInvalidDecl(); 13959 } 13960 } 13961 13962 // The return type of a function definition must be complete 13963 // (C99 6.9.1p3, C++ [dcl.fct]p6). 13964 QualType ResultType = FD->getReturnType(); 13965 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 13966 !FD->isInvalidDecl() && 13967 RequireCompleteType(FD->getLocation(), ResultType, 13968 diag::err_func_def_incomplete_result)) 13969 FD->setInvalidDecl(); 13970 13971 if (FnBodyScope) 13972 PushDeclContext(FnBodyScope, FD); 13973 13974 // Check the validity of our function parameters 13975 CheckParmsForFunctionDef(FD->parameters(), 13976 /*CheckParameterNames=*/true); 13977 13978 // Add non-parameter declarations already in the function to the current 13979 // scope. 13980 if (FnBodyScope) { 13981 for (Decl *NPD : FD->decls()) { 13982 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 13983 if (!NonParmDecl) 13984 continue; 13985 assert(!isa<ParmVarDecl>(NonParmDecl) && 13986 "parameters should not be in newly created FD yet"); 13987 13988 // If the decl has a name, make it accessible in the current scope. 13989 if (NonParmDecl->getDeclName()) 13990 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 13991 13992 // Similarly, dive into enums and fish their constants out, making them 13993 // accessible in this scope. 13994 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 13995 for (auto *EI : ED->enumerators()) 13996 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 13997 } 13998 } 13999 } 14000 14001 // Introduce our parameters into the function scope 14002 for (auto Param : FD->parameters()) { 14003 Param->setOwningFunction(FD); 14004 14005 // If this has an identifier, add it to the scope stack. 14006 if (Param->getIdentifier() && FnBodyScope) { 14007 CheckShadow(FnBodyScope, Param); 14008 14009 PushOnScopeChains(Param, FnBodyScope); 14010 } 14011 } 14012 14013 // Ensure that the function's exception specification is instantiated. 14014 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 14015 ResolveExceptionSpec(D->getLocation(), FPT); 14016 14017 // dllimport cannot be applied to non-inline function definitions. 14018 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 14019 !FD->isTemplateInstantiation()) { 14020 assert(!FD->hasAttr<DLLExportAttr>()); 14021 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 14022 FD->setInvalidDecl(); 14023 return D; 14024 } 14025 // We want to attach documentation to original Decl (which might be 14026 // a function template). 14027 ActOnDocumentableDecl(D); 14028 if (getCurLexicalContext()->isObjCContainer() && 14029 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 14030 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 14031 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 14032 14033 return D; 14034 } 14035 14036 /// Given the set of return statements within a function body, 14037 /// compute the variables that are subject to the named return value 14038 /// optimization. 14039 /// 14040 /// Each of the variables that is subject to the named return value 14041 /// optimization will be marked as NRVO variables in the AST, and any 14042 /// return statement that has a marked NRVO variable as its NRVO candidate can 14043 /// use the named return value optimization. 14044 /// 14045 /// This function applies a very simplistic algorithm for NRVO: if every return 14046 /// statement in the scope of a variable has the same NRVO candidate, that 14047 /// candidate is an NRVO variable. 14048 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 14049 ReturnStmt **Returns = Scope->Returns.data(); 14050 14051 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 14052 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 14053 if (!NRVOCandidate->isNRVOVariable()) 14054 Returns[I]->setNRVOCandidate(nullptr); 14055 } 14056 } 14057 } 14058 14059 bool Sema::canDelayFunctionBody(const Declarator &D) { 14060 // We can't delay parsing the body of a constexpr function template (yet). 14061 if (D.getDeclSpec().hasConstexprSpecifier()) 14062 return false; 14063 14064 // We can't delay parsing the body of a function template with a deduced 14065 // return type (yet). 14066 if (D.getDeclSpec().hasAutoTypeSpec()) { 14067 // If the placeholder introduces a non-deduced trailing return type, 14068 // we can still delay parsing it. 14069 if (D.getNumTypeObjects()) { 14070 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 14071 if (Outer.Kind == DeclaratorChunk::Function && 14072 Outer.Fun.hasTrailingReturnType()) { 14073 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 14074 return Ty.isNull() || !Ty->isUndeducedType(); 14075 } 14076 } 14077 return false; 14078 } 14079 14080 return true; 14081 } 14082 14083 bool Sema::canSkipFunctionBody(Decl *D) { 14084 // We cannot skip the body of a function (or function template) which is 14085 // constexpr, since we may need to evaluate its body in order to parse the 14086 // rest of the file. 14087 // We cannot skip the body of a function with an undeduced return type, 14088 // because any callers of that function need to know the type. 14089 if (const FunctionDecl *FD = D->getAsFunction()) { 14090 if (FD->isConstexpr()) 14091 return false; 14092 // We can't simply call Type::isUndeducedType here, because inside template 14093 // auto can be deduced to a dependent type, which is not considered 14094 // "undeduced". 14095 if (FD->getReturnType()->getContainedDeducedType()) 14096 return false; 14097 } 14098 return Consumer.shouldSkipFunctionBody(D); 14099 } 14100 14101 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 14102 if (!Decl) 14103 return nullptr; 14104 if (FunctionDecl *FD = Decl->getAsFunction()) 14105 FD->setHasSkippedBody(); 14106 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) 14107 MD->setHasSkippedBody(); 14108 return Decl; 14109 } 14110 14111 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 14112 return ActOnFinishFunctionBody(D, BodyArg, false); 14113 } 14114 14115 /// RAII object that pops an ExpressionEvaluationContext when exiting a function 14116 /// body. 14117 class ExitFunctionBodyRAII { 14118 public: 14119 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {} 14120 ~ExitFunctionBodyRAII() { 14121 if (!IsLambda) 14122 S.PopExpressionEvaluationContext(); 14123 } 14124 14125 private: 14126 Sema &S; 14127 bool IsLambda = false; 14128 }; 14129 14130 static void diagnoseImplicitlyRetainedSelf(Sema &S) { 14131 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo; 14132 14133 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) { 14134 if (EscapeInfo.count(BD)) 14135 return EscapeInfo[BD]; 14136 14137 bool R = false; 14138 const BlockDecl *CurBD = BD; 14139 14140 do { 14141 R = !CurBD->doesNotEscape(); 14142 if (R) 14143 break; 14144 CurBD = CurBD->getParent()->getInnermostBlockDecl(); 14145 } while (CurBD); 14146 14147 return EscapeInfo[BD] = R; 14148 }; 14149 14150 // If the location where 'self' is implicitly retained is inside a escaping 14151 // block, emit a diagnostic. 14152 for (const std::pair<SourceLocation, const BlockDecl *> &P : 14153 S.ImplicitlyRetainedSelfLocs) 14154 if (IsOrNestedInEscapingBlock(P.second)) 14155 S.Diag(P.first, diag::warn_implicitly_retains_self) 14156 << FixItHint::CreateInsertion(P.first, "self->"); 14157 } 14158 14159 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 14160 bool IsInstantiation) { 14161 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 14162 14163 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 14164 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 14165 14166 if (getLangOpts().Coroutines && getCurFunction()->isCoroutine()) 14167 CheckCompletedCoroutineBody(FD, Body); 14168 14169 // Do not call PopExpressionEvaluationContext() if it is a lambda because one 14170 // is already popped when finishing the lambda in BuildLambdaExpr(). This is 14171 // meant to pop the context added in ActOnStartOfFunctionDef(). 14172 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD)); 14173 14174 if (FD) { 14175 FD->setBody(Body); 14176 FD->setWillHaveBody(false); 14177 14178 if (getLangOpts().CPlusPlus14) { 14179 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 14180 FD->getReturnType()->isUndeducedType()) { 14181 // If the function has a deduced result type but contains no 'return' 14182 // statements, the result type as written must be exactly 'auto', and 14183 // the deduced result type is 'void'. 14184 if (!FD->getReturnType()->getAs<AutoType>()) { 14185 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 14186 << FD->getReturnType(); 14187 FD->setInvalidDecl(); 14188 } else { 14189 // Substitute 'void' for the 'auto' in the type. 14190 TypeLoc ResultType = getReturnTypeLoc(FD); 14191 Context.adjustDeducedFunctionResultType( 14192 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 14193 } 14194 } 14195 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 14196 // In C++11, we don't use 'auto' deduction rules for lambda call 14197 // operators because we don't support return type deduction. 14198 auto *LSI = getCurLambda(); 14199 if (LSI->HasImplicitReturnType) { 14200 deduceClosureReturnType(*LSI); 14201 14202 // C++11 [expr.prim.lambda]p4: 14203 // [...] if there are no return statements in the compound-statement 14204 // [the deduced type is] the type void 14205 QualType RetType = 14206 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 14207 14208 // Update the return type to the deduced type. 14209 const auto *Proto = FD->getType()->castAs<FunctionProtoType>(); 14210 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 14211 Proto->getExtProtoInfo())); 14212 } 14213 } 14214 14215 // If the function implicitly returns zero (like 'main') or is naked, 14216 // don't complain about missing return statements. 14217 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 14218 WP.disableCheckFallThrough(); 14219 14220 // MSVC permits the use of pure specifier (=0) on function definition, 14221 // defined at class scope, warn about this non-standard construct. 14222 if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine()) 14223 Diag(FD->getLocation(), diag::ext_pure_function_definition); 14224 14225 if (!FD->isInvalidDecl()) { 14226 // Don't diagnose unused parameters of defaulted or deleted functions. 14227 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody()) 14228 DiagnoseUnusedParameters(FD->parameters()); 14229 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 14230 FD->getReturnType(), FD); 14231 14232 // If this is a structor, we need a vtable. 14233 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 14234 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 14235 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 14236 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 14237 14238 // Try to apply the named return value optimization. We have to check 14239 // if we can do this here because lambdas keep return statements around 14240 // to deduce an implicit return type. 14241 if (FD->getReturnType()->isRecordType() && 14242 (!getLangOpts().CPlusPlus || !FD->isDependentContext())) 14243 computeNRVO(Body, getCurFunction()); 14244 } 14245 14246 // GNU warning -Wmissing-prototypes: 14247 // Warn if a global function is defined without a previous 14248 // prototype declaration. This warning is issued even if the 14249 // definition itself provides a prototype. The aim is to detect 14250 // global functions that fail to be declared in header files. 14251 const FunctionDecl *PossiblePrototype = nullptr; 14252 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) { 14253 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 14254 14255 if (PossiblePrototype) { 14256 // We found a declaration that is not a prototype, 14257 // but that could be a zero-parameter prototype 14258 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) { 14259 TypeLoc TL = TI->getTypeLoc(); 14260 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 14261 Diag(PossiblePrototype->getLocation(), 14262 diag::note_declaration_not_a_prototype) 14263 << (FD->getNumParams() != 0) 14264 << (FD->getNumParams() == 0 14265 ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void") 14266 : FixItHint{}); 14267 } 14268 } else { 14269 // Returns true if the token beginning at this Loc is `const`. 14270 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM, 14271 const LangOptions &LangOpts) { 14272 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); 14273 if (LocInfo.first.isInvalid()) 14274 return false; 14275 14276 bool Invalid = false; 14277 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid); 14278 if (Invalid) 14279 return false; 14280 14281 if (LocInfo.second > Buffer.size()) 14282 return false; 14283 14284 const char *LexStart = Buffer.data() + LocInfo.second; 14285 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second); 14286 14287 return StartTok.consume_front("const") && 14288 (StartTok.empty() || isWhitespace(StartTok[0]) || 14289 StartTok.startswith("/*") || StartTok.startswith("//")); 14290 }; 14291 14292 auto findBeginLoc = [&]() { 14293 // If the return type has `const` qualifier, we want to insert 14294 // `static` before `const` (and not before the typename). 14295 if ((FD->getReturnType()->isAnyPointerType() && 14296 FD->getReturnType()->getPointeeType().isConstQualified()) || 14297 FD->getReturnType().isConstQualified()) { 14298 // But only do this if we can determine where the `const` is. 14299 14300 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(), 14301 getLangOpts())) 14302 14303 return FD->getBeginLoc(); 14304 } 14305 return FD->getTypeSpecStartLoc(); 14306 }; 14307 Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 14308 << /* function */ 1 14309 << (FD->getStorageClass() == SC_None 14310 ? FixItHint::CreateInsertion(findBeginLoc(), "static ") 14311 : FixItHint{}); 14312 } 14313 14314 // GNU warning -Wstrict-prototypes 14315 // Warn if K&R function is defined without a previous declaration. 14316 // This warning is issued only if the definition itself does not provide 14317 // a prototype. Only K&R definitions do not provide a prototype. 14318 if (!FD->hasWrittenPrototype()) { 14319 TypeSourceInfo *TI = FD->getTypeSourceInfo(); 14320 TypeLoc TL = TI->getTypeLoc(); 14321 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); 14322 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2; 14323 } 14324 } 14325 14326 // Warn on CPUDispatch with an actual body. 14327 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body) 14328 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body)) 14329 if (!CmpndBody->body_empty()) 14330 Diag(CmpndBody->body_front()->getBeginLoc(), 14331 diag::warn_dispatch_body_ignored); 14332 14333 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 14334 const CXXMethodDecl *KeyFunction; 14335 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 14336 MD->isVirtual() && 14337 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 14338 MD == KeyFunction->getCanonicalDecl()) { 14339 // Update the key-function state if necessary for this ABI. 14340 if (FD->isInlined() && 14341 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 14342 Context.setNonKeyFunction(MD); 14343 14344 // If the newly-chosen key function is already defined, then we 14345 // need to mark the vtable as used retroactively. 14346 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 14347 const FunctionDecl *Definition; 14348 if (KeyFunction && KeyFunction->isDefined(Definition)) 14349 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 14350 } else { 14351 // We just defined they key function; mark the vtable as used. 14352 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 14353 } 14354 } 14355 } 14356 14357 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 14358 "Function parsing confused"); 14359 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 14360 assert(MD == getCurMethodDecl() && "Method parsing confused"); 14361 MD->setBody(Body); 14362 if (!MD->isInvalidDecl()) { 14363 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 14364 MD->getReturnType(), MD); 14365 14366 if (Body) 14367 computeNRVO(Body, getCurFunction()); 14368 } 14369 if (getCurFunction()->ObjCShouldCallSuper) { 14370 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call) 14371 << MD->getSelector().getAsString(); 14372 getCurFunction()->ObjCShouldCallSuper = false; 14373 } 14374 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 14375 const ObjCMethodDecl *InitMethod = nullptr; 14376 bool isDesignated = 14377 MD->isDesignatedInitializerForTheInterface(&InitMethod); 14378 assert(isDesignated && InitMethod); 14379 (void)isDesignated; 14380 14381 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 14382 auto IFace = MD->getClassInterface(); 14383 if (!IFace) 14384 return false; 14385 auto SuperD = IFace->getSuperClass(); 14386 if (!SuperD) 14387 return false; 14388 return SuperD->getIdentifier() == 14389 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 14390 }; 14391 // Don't issue this warning for unavailable inits or direct subclasses 14392 // of NSObject. 14393 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 14394 Diag(MD->getLocation(), 14395 diag::warn_objc_designated_init_missing_super_call); 14396 Diag(InitMethod->getLocation(), 14397 diag::note_objc_designated_init_marked_here); 14398 } 14399 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 14400 } 14401 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 14402 // Don't issue this warning for unavaialable inits. 14403 if (!MD->isUnavailable()) 14404 Diag(MD->getLocation(), 14405 diag::warn_objc_secondary_init_missing_init_call); 14406 getCurFunction()->ObjCWarnForNoInitDelegation = false; 14407 } 14408 14409 diagnoseImplicitlyRetainedSelf(*this); 14410 } else { 14411 // Parsing the function declaration failed in some way. Pop the fake scope 14412 // we pushed on. 14413 PopFunctionScopeInfo(ActivePolicy, dcl); 14414 return nullptr; 14415 } 14416 14417 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 14418 DiagnoseUnguardedAvailabilityViolations(dcl); 14419 14420 assert(!getCurFunction()->ObjCShouldCallSuper && 14421 "This should only be set for ObjC methods, which should have been " 14422 "handled in the block above."); 14423 14424 // Verify and clean out per-function state. 14425 if (Body && (!FD || !FD->isDefaulted())) { 14426 // C++ constructors that have function-try-blocks can't have return 14427 // statements in the handlers of that block. (C++ [except.handle]p14) 14428 // Verify this. 14429 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 14430 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 14431 14432 // Verify that gotos and switch cases don't jump into scopes illegally. 14433 if (getCurFunction()->NeedsScopeChecking() && 14434 !PP.isCodeCompletionEnabled()) 14435 DiagnoseInvalidJumps(Body); 14436 14437 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 14438 if (!Destructor->getParent()->isDependentType()) 14439 CheckDestructor(Destructor); 14440 14441 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 14442 Destructor->getParent()); 14443 } 14444 14445 // If any errors have occurred, clear out any temporaries that may have 14446 // been leftover. This ensures that these temporaries won't be picked up for 14447 // deletion in some later function. 14448 if (getDiagnostics().hasUncompilableErrorOccurred() || 14449 getDiagnostics().getSuppressAllDiagnostics()) { 14450 DiscardCleanupsInEvaluationContext(); 14451 } 14452 if (!getDiagnostics().hasUncompilableErrorOccurred() && 14453 !isa<FunctionTemplateDecl>(dcl)) { 14454 // Since the body is valid, issue any analysis-based warnings that are 14455 // enabled. 14456 ActivePolicy = &WP; 14457 } 14458 14459 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 14460 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose)) 14461 FD->setInvalidDecl(); 14462 14463 if (FD && FD->hasAttr<NakedAttr>()) { 14464 for (const Stmt *S : Body->children()) { 14465 // Allow local register variables without initializer as they don't 14466 // require prologue. 14467 bool RegisterVariables = false; 14468 if (auto *DS = dyn_cast<DeclStmt>(S)) { 14469 for (const auto *Decl : DS->decls()) { 14470 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 14471 RegisterVariables = 14472 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 14473 if (!RegisterVariables) 14474 break; 14475 } 14476 } 14477 } 14478 if (RegisterVariables) 14479 continue; 14480 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 14481 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function); 14482 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 14483 FD->setInvalidDecl(); 14484 break; 14485 } 14486 } 14487 } 14488 14489 assert(ExprCleanupObjects.size() == 14490 ExprEvalContexts.back().NumCleanupObjects && 14491 "Leftover temporaries in function"); 14492 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function"); 14493 assert(MaybeODRUseExprs.empty() && 14494 "Leftover expressions for odr-use checking"); 14495 } 14496 14497 if (!IsInstantiation) 14498 PopDeclContext(); 14499 14500 PopFunctionScopeInfo(ActivePolicy, dcl); 14501 // If any errors have occurred, clear out any temporaries that may have 14502 // been leftover. This ensures that these temporaries won't be picked up for 14503 // deletion in some later function. 14504 if (getDiagnostics().hasUncompilableErrorOccurred()) { 14505 DiscardCleanupsInEvaluationContext(); 14506 } 14507 14508 if (LangOpts.OpenMP || LangOpts.CUDA || LangOpts.SYCLIsDevice) { 14509 auto ES = getEmissionStatus(FD); 14510 if (ES == Sema::FunctionEmissionStatus::Emitted || 14511 ES == Sema::FunctionEmissionStatus::Unknown) 14512 DeclsToCheckForDeferredDiags.push_back(FD); 14513 } 14514 14515 return dcl; 14516 } 14517 14518 /// When we finish delayed parsing of an attribute, we must attach it to the 14519 /// relevant Decl. 14520 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 14521 ParsedAttributes &Attrs) { 14522 // Always attach attributes to the underlying decl. 14523 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 14524 D = TD->getTemplatedDecl(); 14525 ProcessDeclAttributeList(S, D, Attrs); 14526 14527 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 14528 if (Method->isStatic()) 14529 checkThisInStaticMemberFunctionAttributes(Method); 14530 } 14531 14532 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 14533 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 14534 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 14535 IdentifierInfo &II, Scope *S) { 14536 // Find the scope in which the identifier is injected and the corresponding 14537 // DeclContext. 14538 // FIXME: C89 does not say what happens if there is no enclosing block scope. 14539 // In that case, we inject the declaration into the translation unit scope 14540 // instead. 14541 Scope *BlockScope = S; 14542 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) 14543 BlockScope = BlockScope->getParent(); 14544 14545 Scope *ContextScope = BlockScope; 14546 while (!ContextScope->getEntity()) 14547 ContextScope = ContextScope->getParent(); 14548 ContextRAII SavedContext(*this, ContextScope->getEntity()); 14549 14550 // Before we produce a declaration for an implicitly defined 14551 // function, see whether there was a locally-scoped declaration of 14552 // this name as a function or variable. If so, use that 14553 // (non-visible) declaration, and complain about it. 14554 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); 14555 if (ExternCPrev) { 14556 // We still need to inject the function into the enclosing block scope so 14557 // that later (non-call) uses can see it. 14558 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); 14559 14560 // C89 footnote 38: 14561 // If in fact it is not defined as having type "function returning int", 14562 // the behavior is undefined. 14563 if (!isa<FunctionDecl>(ExternCPrev) || 14564 !Context.typesAreCompatible( 14565 cast<FunctionDecl>(ExternCPrev)->getType(), 14566 Context.getFunctionNoProtoType(Context.IntTy))) { 14567 Diag(Loc, diag::ext_use_out_of_scope_declaration) 14568 << ExternCPrev << !getLangOpts().C99; 14569 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 14570 return ExternCPrev; 14571 } 14572 } 14573 14574 // Extension in C99. Legal in C90, but warn about it. 14575 unsigned diag_id; 14576 if (II.getName().startswith("__builtin_")) 14577 diag_id = diag::warn_builtin_unknown; 14578 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. 14579 else if (getLangOpts().OpenCL) 14580 diag_id = diag::err_opencl_implicit_function_decl; 14581 else if (getLangOpts().C99) 14582 diag_id = diag::ext_implicit_function_decl; 14583 else 14584 diag_id = diag::warn_implicit_function_decl; 14585 Diag(Loc, diag_id) << &II; 14586 14587 // If we found a prior declaration of this function, don't bother building 14588 // another one. We've already pushed that one into scope, so there's nothing 14589 // more to do. 14590 if (ExternCPrev) 14591 return ExternCPrev; 14592 14593 // Because typo correction is expensive, only do it if the implicit 14594 // function declaration is going to be treated as an error. 14595 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 14596 TypoCorrection Corrected; 14597 DeclFilterCCC<FunctionDecl> CCC{}; 14598 if (S && (Corrected = 14599 CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName, 14600 S, nullptr, CCC, CTK_NonError))) 14601 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 14602 /*ErrorRecovery*/false); 14603 } 14604 14605 // Set a Declarator for the implicit definition: int foo(); 14606 const char *Dummy; 14607 AttributeFactory attrFactory; 14608 DeclSpec DS(attrFactory); 14609 unsigned DiagID; 14610 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 14611 Context.getPrintingPolicy()); 14612 (void)Error; // Silence warning. 14613 assert(!Error && "Error setting up implicit decl!"); 14614 SourceLocation NoLoc; 14615 Declarator D(DS, DeclaratorContext::BlockContext); 14616 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 14617 /*IsAmbiguous=*/false, 14618 /*LParenLoc=*/NoLoc, 14619 /*Params=*/nullptr, 14620 /*NumParams=*/0, 14621 /*EllipsisLoc=*/NoLoc, 14622 /*RParenLoc=*/NoLoc, 14623 /*RefQualifierIsLvalueRef=*/true, 14624 /*RefQualifierLoc=*/NoLoc, 14625 /*MutableLoc=*/NoLoc, EST_None, 14626 /*ESpecRange=*/SourceRange(), 14627 /*Exceptions=*/nullptr, 14628 /*ExceptionRanges=*/nullptr, 14629 /*NumExceptions=*/0, 14630 /*NoexceptExpr=*/nullptr, 14631 /*ExceptionSpecTokens=*/nullptr, 14632 /*DeclsInPrototype=*/None, Loc, 14633 Loc, D), 14634 std::move(DS.getAttributes()), SourceLocation()); 14635 D.SetIdentifier(&II, Loc); 14636 14637 // Insert this function into the enclosing block scope. 14638 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); 14639 FD->setImplicit(); 14640 14641 AddKnownFunctionAttributes(FD); 14642 14643 return FD; 14644 } 14645 14646 /// If this function is a C++ replaceable global allocation function 14647 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]), 14648 /// adds any function attributes that we know a priori based on the standard. 14649 /// 14650 /// We need to check for duplicate attributes both here and where user-written 14651 /// attributes are applied to declarations. 14652 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction( 14653 FunctionDecl *FD) { 14654 if (FD->isInvalidDecl()) 14655 return; 14656 14657 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New && 14658 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New) 14659 return; 14660 14661 Optional<unsigned> AlignmentParam; 14662 bool IsNothrow = false; 14663 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow)) 14664 return; 14665 14666 // C++2a [basic.stc.dynamic.allocation]p4: 14667 // An allocation function that has a non-throwing exception specification 14668 // indicates failure by returning a null pointer value. Any other allocation 14669 // function never returns a null pointer value and indicates failure only by 14670 // throwing an exception [...] 14671 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>()) 14672 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation())); 14673 14674 // C++2a [basic.stc.dynamic.allocation]p2: 14675 // An allocation function attempts to allocate the requested amount of 14676 // storage. [...] If the request succeeds, the value returned by a 14677 // replaceable allocation function is a [...] pointer value p0 different 14678 // from any previously returned value p1 [...] 14679 // 14680 // However, this particular information is being added in codegen, 14681 // because there is an opt-out switch for it (-fno-assume-sane-operator-new) 14682 14683 // C++2a [basic.stc.dynamic.allocation]p2: 14684 // An allocation function attempts to allocate the requested amount of 14685 // storage. If it is successful, it returns the address of the start of a 14686 // block of storage whose length in bytes is at least as large as the 14687 // requested size. 14688 if (!FD->hasAttr<AllocSizeAttr>()) { 14689 FD->addAttr(AllocSizeAttr::CreateImplicit( 14690 Context, /*ElemSizeParam=*/ParamIdx(1, FD), 14691 /*NumElemsParam=*/ParamIdx(), FD->getLocation())); 14692 } 14693 14694 // C++2a [basic.stc.dynamic.allocation]p3: 14695 // For an allocation function [...], the pointer returned on a successful 14696 // call shall represent the address of storage that is aligned as follows: 14697 // (3.1) If the allocation function takes an argument of type 14698 // std::align_val_t, the storage will have the alignment 14699 // specified by the value of this argument. 14700 if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) { 14701 FD->addAttr(AllocAlignAttr::CreateImplicit( 14702 Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation())); 14703 } 14704 14705 // FIXME: 14706 // C++2a [basic.stc.dynamic.allocation]p3: 14707 // For an allocation function [...], the pointer returned on a successful 14708 // call shall represent the address of storage that is aligned as follows: 14709 // (3.2) Otherwise, if the allocation function is named operator new[], 14710 // the storage is aligned for any object that does not have 14711 // new-extended alignment ([basic.align]) and is no larger than the 14712 // requested size. 14713 // (3.3) Otherwise, the storage is aligned for any object that does not 14714 // have new-extended alignment and is of the requested size. 14715 } 14716 14717 /// Adds any function attributes that we know a priori based on 14718 /// the declaration of this function. 14719 /// 14720 /// These attributes can apply both to implicitly-declared builtins 14721 /// (like __builtin___printf_chk) or to library-declared functions 14722 /// like NSLog or printf. 14723 /// 14724 /// We need to check for duplicate attributes both here and where user-written 14725 /// attributes are applied to declarations. 14726 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 14727 if (FD->isInvalidDecl()) 14728 return; 14729 14730 // If this is a built-in function, map its builtin attributes to 14731 // actual attributes. 14732 if (unsigned BuiltinID = FD->getBuiltinID()) { 14733 // Handle printf-formatting attributes. 14734 unsigned FormatIdx; 14735 bool HasVAListArg; 14736 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 14737 if (!FD->hasAttr<FormatAttr>()) { 14738 const char *fmt = "printf"; 14739 unsigned int NumParams = FD->getNumParams(); 14740 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 14741 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 14742 fmt = "NSString"; 14743 FD->addAttr(FormatAttr::CreateImplicit(Context, 14744 &Context.Idents.get(fmt), 14745 FormatIdx+1, 14746 HasVAListArg ? 0 : FormatIdx+2, 14747 FD->getLocation())); 14748 } 14749 } 14750 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 14751 HasVAListArg)) { 14752 if (!FD->hasAttr<FormatAttr>()) 14753 FD->addAttr(FormatAttr::CreateImplicit(Context, 14754 &Context.Idents.get("scanf"), 14755 FormatIdx+1, 14756 HasVAListArg ? 0 : FormatIdx+2, 14757 FD->getLocation())); 14758 } 14759 14760 // Handle automatically recognized callbacks. 14761 SmallVector<int, 4> Encoding; 14762 if (!FD->hasAttr<CallbackAttr>() && 14763 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding)) 14764 FD->addAttr(CallbackAttr::CreateImplicit( 14765 Context, Encoding.data(), Encoding.size(), FD->getLocation())); 14766 14767 // Mark const if we don't care about errno and that is the only thing 14768 // preventing the function from being const. This allows IRgen to use LLVM 14769 // intrinsics for such functions. 14770 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() && 14771 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) 14772 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14773 14774 // We make "fma" on some platforms const because we know it does not set 14775 // errno in those environments even though it could set errno based on the 14776 // C standard. 14777 const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); 14778 if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) && 14779 !FD->hasAttr<ConstAttr>()) { 14780 switch (BuiltinID) { 14781 case Builtin::BI__builtin_fma: 14782 case Builtin::BI__builtin_fmaf: 14783 case Builtin::BI__builtin_fmal: 14784 case Builtin::BIfma: 14785 case Builtin::BIfmaf: 14786 case Builtin::BIfmal: 14787 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14788 break; 14789 default: 14790 break; 14791 } 14792 } 14793 14794 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 14795 !FD->hasAttr<ReturnsTwiceAttr>()) 14796 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 14797 FD->getLocation())); 14798 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 14799 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 14800 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 14801 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 14802 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 14803 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14804 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 14805 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 14806 // Add the appropriate attribute, depending on the CUDA compilation mode 14807 // and which target the builtin belongs to. For example, during host 14808 // compilation, aux builtins are __device__, while the rest are __host__. 14809 if (getLangOpts().CUDAIsDevice != 14810 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 14811 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 14812 else 14813 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 14814 } 14815 } 14816 14817 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD); 14818 14819 // If C++ exceptions are enabled but we are told extern "C" functions cannot 14820 // throw, add an implicit nothrow attribute to any extern "C" function we come 14821 // across. 14822 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 14823 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 14824 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 14825 if (!FPT || FPT->getExceptionSpecType() == EST_None) 14826 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 14827 } 14828 14829 IdentifierInfo *Name = FD->getIdentifier(); 14830 if (!Name) 14831 return; 14832 if ((!getLangOpts().CPlusPlus && 14833 FD->getDeclContext()->isTranslationUnit()) || 14834 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 14835 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 14836 LinkageSpecDecl::lang_c)) { 14837 // Okay: this could be a libc/libm/Objective-C function we know 14838 // about. 14839 } else 14840 return; 14841 14842 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 14843 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 14844 // target-specific builtins, perhaps? 14845 if (!FD->hasAttr<FormatAttr>()) 14846 FD->addAttr(FormatAttr::CreateImplicit(Context, 14847 &Context.Idents.get("printf"), 2, 14848 Name->isStr("vasprintf") ? 0 : 3, 14849 FD->getLocation())); 14850 } 14851 14852 if (Name->isStr("__CFStringMakeConstantString")) { 14853 // We already have a __builtin___CFStringMakeConstantString, 14854 // but builds that use -fno-constant-cfstrings don't go through that. 14855 if (!FD->hasAttr<FormatArgAttr>()) 14856 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), 14857 FD->getLocation())); 14858 } 14859 } 14860 14861 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 14862 TypeSourceInfo *TInfo) { 14863 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 14864 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 14865 14866 if (!TInfo) { 14867 assert(D.isInvalidType() && "no declarator info for valid type"); 14868 TInfo = Context.getTrivialTypeSourceInfo(T); 14869 } 14870 14871 // Scope manipulation handled by caller. 14872 TypedefDecl *NewTD = 14873 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(), 14874 D.getIdentifierLoc(), D.getIdentifier(), TInfo); 14875 14876 // Bail out immediately if we have an invalid declaration. 14877 if (D.isInvalidType()) { 14878 NewTD->setInvalidDecl(); 14879 return NewTD; 14880 } 14881 14882 if (D.getDeclSpec().isModulePrivateSpecified()) { 14883 if (CurContext->isFunctionOrMethod()) 14884 Diag(NewTD->getLocation(), diag::err_module_private_local) 14885 << 2 << NewTD->getDeclName() 14886 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 14887 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 14888 else 14889 NewTD->setModulePrivate(); 14890 } 14891 14892 // C++ [dcl.typedef]p8: 14893 // If the typedef declaration defines an unnamed class (or 14894 // enum), the first typedef-name declared by the declaration 14895 // to be that class type (or enum type) is used to denote the 14896 // class type (or enum type) for linkage purposes only. 14897 // We need to check whether the type was declared in the declaration. 14898 switch (D.getDeclSpec().getTypeSpecType()) { 14899 case TST_enum: 14900 case TST_struct: 14901 case TST_interface: 14902 case TST_union: 14903 case TST_class: { 14904 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 14905 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 14906 break; 14907 } 14908 14909 default: 14910 break; 14911 } 14912 14913 return NewTD; 14914 } 14915 14916 /// Check that this is a valid underlying type for an enum declaration. 14917 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 14918 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 14919 QualType T = TI->getType(); 14920 14921 if (T->isDependentType()) 14922 return false; 14923 14924 // This doesn't use 'isIntegralType' despite the error message mentioning 14925 // integral type because isIntegralType would also allow enum types in C. 14926 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 14927 if (BT->isInteger()) 14928 return false; 14929 14930 if (T->isExtIntType()) 14931 return false; 14932 14933 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 14934 } 14935 14936 /// Check whether this is a valid redeclaration of a previous enumeration. 14937 /// \return true if the redeclaration was invalid. 14938 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 14939 QualType EnumUnderlyingTy, bool IsFixed, 14940 const EnumDecl *Prev) { 14941 if (IsScoped != Prev->isScoped()) { 14942 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 14943 << Prev->isScoped(); 14944 Diag(Prev->getLocation(), diag::note_previous_declaration); 14945 return true; 14946 } 14947 14948 if (IsFixed && Prev->isFixed()) { 14949 if (!EnumUnderlyingTy->isDependentType() && 14950 !Prev->getIntegerType()->isDependentType() && 14951 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 14952 Prev->getIntegerType())) { 14953 // TODO: Highlight the underlying type of the redeclaration. 14954 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 14955 << EnumUnderlyingTy << Prev->getIntegerType(); 14956 Diag(Prev->getLocation(), diag::note_previous_declaration) 14957 << Prev->getIntegerTypeRange(); 14958 return true; 14959 } 14960 } else if (IsFixed != Prev->isFixed()) { 14961 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 14962 << Prev->isFixed(); 14963 Diag(Prev->getLocation(), diag::note_previous_declaration); 14964 return true; 14965 } 14966 14967 return false; 14968 } 14969 14970 /// Get diagnostic %select index for tag kind for 14971 /// redeclaration diagnostic message. 14972 /// WARNING: Indexes apply to particular diagnostics only! 14973 /// 14974 /// \returns diagnostic %select index. 14975 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 14976 switch (Tag) { 14977 case TTK_Struct: return 0; 14978 case TTK_Interface: return 1; 14979 case TTK_Class: return 2; 14980 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 14981 } 14982 } 14983 14984 /// Determine if tag kind is a class-key compatible with 14985 /// class for redeclaration (class, struct, or __interface). 14986 /// 14987 /// \returns true iff the tag kind is compatible. 14988 static bool isClassCompatTagKind(TagTypeKind Tag) 14989 { 14990 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 14991 } 14992 14993 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 14994 TagTypeKind TTK) { 14995 if (isa<TypedefDecl>(PrevDecl)) 14996 return NTK_Typedef; 14997 else if (isa<TypeAliasDecl>(PrevDecl)) 14998 return NTK_TypeAlias; 14999 else if (isa<ClassTemplateDecl>(PrevDecl)) 15000 return NTK_Template; 15001 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 15002 return NTK_TypeAliasTemplate; 15003 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 15004 return NTK_TemplateTemplateArgument; 15005 switch (TTK) { 15006 case TTK_Struct: 15007 case TTK_Interface: 15008 case TTK_Class: 15009 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 15010 case TTK_Union: 15011 return NTK_NonUnion; 15012 case TTK_Enum: 15013 return NTK_NonEnum; 15014 } 15015 llvm_unreachable("invalid TTK"); 15016 } 15017 15018 /// Determine whether a tag with a given kind is acceptable 15019 /// as a redeclaration of the given tag declaration. 15020 /// 15021 /// \returns true if the new tag kind is acceptable, false otherwise. 15022 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 15023 TagTypeKind NewTag, bool isDefinition, 15024 SourceLocation NewTagLoc, 15025 const IdentifierInfo *Name) { 15026 // C++ [dcl.type.elab]p3: 15027 // The class-key or enum keyword present in the 15028 // elaborated-type-specifier shall agree in kind with the 15029 // declaration to which the name in the elaborated-type-specifier 15030 // refers. This rule also applies to the form of 15031 // elaborated-type-specifier that declares a class-name or 15032 // friend class since it can be construed as referring to the 15033 // definition of the class. Thus, in any 15034 // elaborated-type-specifier, the enum keyword shall be used to 15035 // refer to an enumeration (7.2), the union class-key shall be 15036 // used to refer to a union (clause 9), and either the class or 15037 // struct class-key shall be used to refer to a class (clause 9) 15038 // declared using the class or struct class-key. 15039 TagTypeKind OldTag = Previous->getTagKind(); 15040 if (OldTag != NewTag && 15041 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag))) 15042 return false; 15043 15044 // Tags are compatible, but we might still want to warn on mismatched tags. 15045 // Non-class tags can't be mismatched at this point. 15046 if (!isClassCompatTagKind(NewTag)) 15047 return true; 15048 15049 // Declarations for which -Wmismatched-tags is disabled are entirely ignored 15050 // by our warning analysis. We don't want to warn about mismatches with (eg) 15051 // declarations in system headers that are designed to be specialized, but if 15052 // a user asks us to warn, we should warn if their code contains mismatched 15053 // declarations. 15054 auto IsIgnoredLoc = [&](SourceLocation Loc) { 15055 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch, 15056 Loc); 15057 }; 15058 if (IsIgnoredLoc(NewTagLoc)) 15059 return true; 15060 15061 auto IsIgnored = [&](const TagDecl *Tag) { 15062 return IsIgnoredLoc(Tag->getLocation()); 15063 }; 15064 while (IsIgnored(Previous)) { 15065 Previous = Previous->getPreviousDecl(); 15066 if (!Previous) 15067 return true; 15068 OldTag = Previous->getTagKind(); 15069 } 15070 15071 bool isTemplate = false; 15072 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 15073 isTemplate = Record->getDescribedClassTemplate(); 15074 15075 if (inTemplateInstantiation()) { 15076 if (OldTag != NewTag) { 15077 // In a template instantiation, do not offer fix-its for tag mismatches 15078 // since they usually mess up the template instead of fixing the problem. 15079 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15080 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15081 << getRedeclDiagFromTagKind(OldTag); 15082 // FIXME: Note previous location? 15083 } 15084 return true; 15085 } 15086 15087 if (isDefinition) { 15088 // On definitions, check all previous tags and issue a fix-it for each 15089 // one that doesn't match the current tag. 15090 if (Previous->getDefinition()) { 15091 // Don't suggest fix-its for redefinitions. 15092 return true; 15093 } 15094 15095 bool previousMismatch = false; 15096 for (const TagDecl *I : Previous->redecls()) { 15097 if (I->getTagKind() != NewTag) { 15098 // Ignore previous declarations for which the warning was disabled. 15099 if (IsIgnored(I)) 15100 continue; 15101 15102 if (!previousMismatch) { 15103 previousMismatch = true; 15104 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 15105 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15106 << getRedeclDiagFromTagKind(I->getTagKind()); 15107 } 15108 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 15109 << getRedeclDiagFromTagKind(NewTag) 15110 << FixItHint::CreateReplacement(I->getInnerLocStart(), 15111 TypeWithKeyword::getTagTypeKindName(NewTag)); 15112 } 15113 } 15114 return true; 15115 } 15116 15117 // Identify the prevailing tag kind: this is the kind of the definition (if 15118 // there is a non-ignored definition), or otherwise the kind of the prior 15119 // (non-ignored) declaration. 15120 const TagDecl *PrevDef = Previous->getDefinition(); 15121 if (PrevDef && IsIgnored(PrevDef)) 15122 PrevDef = nullptr; 15123 const TagDecl *Redecl = PrevDef ? PrevDef : Previous; 15124 if (Redecl->getTagKind() != NewTag) { 15125 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 15126 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 15127 << getRedeclDiagFromTagKind(OldTag); 15128 Diag(Redecl->getLocation(), diag::note_previous_use); 15129 15130 // If there is a previous definition, suggest a fix-it. 15131 if (PrevDef) { 15132 Diag(NewTagLoc, diag::note_struct_class_suggestion) 15133 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 15134 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 15135 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 15136 } 15137 } 15138 15139 return true; 15140 } 15141 15142 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 15143 /// from an outer enclosing namespace or file scope inside a friend declaration. 15144 /// This should provide the commented out code in the following snippet: 15145 /// namespace N { 15146 /// struct X; 15147 /// namespace M { 15148 /// struct Y { friend struct /*N::*/ X; }; 15149 /// } 15150 /// } 15151 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 15152 SourceLocation NameLoc) { 15153 // While the decl is in a namespace, do repeated lookup of that name and see 15154 // if we get the same namespace back. If we do not, continue until 15155 // translation unit scope, at which point we have a fully qualified NNS. 15156 SmallVector<IdentifierInfo *, 4> Namespaces; 15157 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15158 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 15159 // This tag should be declared in a namespace, which can only be enclosed by 15160 // other namespaces. Bail if there's an anonymous namespace in the chain. 15161 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 15162 if (!Namespace || Namespace->isAnonymousNamespace()) 15163 return FixItHint(); 15164 IdentifierInfo *II = Namespace->getIdentifier(); 15165 Namespaces.push_back(II); 15166 NamedDecl *Lookup = SemaRef.LookupSingleName( 15167 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 15168 if (Lookup == Namespace) 15169 break; 15170 } 15171 15172 // Once we have all the namespaces, reverse them to go outermost first, and 15173 // build an NNS. 15174 SmallString<64> Insertion; 15175 llvm::raw_svector_ostream OS(Insertion); 15176 if (DC->isTranslationUnit()) 15177 OS << "::"; 15178 std::reverse(Namespaces.begin(), Namespaces.end()); 15179 for (auto *II : Namespaces) 15180 OS << II->getName() << "::"; 15181 return FixItHint::CreateInsertion(NameLoc, Insertion); 15182 } 15183 15184 /// Determine whether a tag originally declared in context \p OldDC can 15185 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup 15186 /// found a declaration in \p OldDC as a previous decl, perhaps through a 15187 /// using-declaration). 15188 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 15189 DeclContext *NewDC) { 15190 OldDC = OldDC->getRedeclContext(); 15191 NewDC = NewDC->getRedeclContext(); 15192 15193 if (OldDC->Equals(NewDC)) 15194 return true; 15195 15196 // In MSVC mode, we allow a redeclaration if the contexts are related (either 15197 // encloses the other). 15198 if (S.getLangOpts().MSVCCompat && 15199 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 15200 return true; 15201 15202 return false; 15203 } 15204 15205 /// This is invoked when we see 'struct foo' or 'struct {'. In the 15206 /// former case, Name will be non-null. In the later case, Name will be null. 15207 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 15208 /// reference/declaration/definition of a tag. 15209 /// 15210 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 15211 /// trailing-type-specifier) other than one in an alias-declaration. 15212 /// 15213 /// \param SkipBody If non-null, will be set to indicate if the caller should 15214 /// skip the definition of this tag and treat it as if it were a declaration. 15215 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 15216 SourceLocation KWLoc, CXXScopeSpec &SS, 15217 IdentifierInfo *Name, SourceLocation NameLoc, 15218 const ParsedAttributesView &Attrs, AccessSpecifier AS, 15219 SourceLocation ModulePrivateLoc, 15220 MultiTemplateParamsArg TemplateParameterLists, 15221 bool &OwnedDecl, bool &IsDependent, 15222 SourceLocation ScopedEnumKWLoc, 15223 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, 15224 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 15225 SkipBodyInfo *SkipBody) { 15226 // If this is not a definition, it must have a name. 15227 IdentifierInfo *OrigName = Name; 15228 assert((Name != nullptr || TUK == TUK_Definition) && 15229 "Nameless record must be a definition!"); 15230 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 15231 15232 OwnedDecl = false; 15233 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 15234 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 15235 15236 // FIXME: Check member specializations more carefully. 15237 bool isMemberSpecialization = false; 15238 bool Invalid = false; 15239 15240 // We only need to do this matching if we have template parameters 15241 // or a scope specifier, which also conveniently avoids this work 15242 // for non-C++ cases. 15243 if (TemplateParameterLists.size() > 0 || 15244 (SS.isNotEmpty() && TUK != TUK_Reference)) { 15245 if (TemplateParameterList *TemplateParams = 15246 MatchTemplateParametersToScopeSpecifier( 15247 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 15248 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 15249 if (Kind == TTK_Enum) { 15250 Diag(KWLoc, diag::err_enum_template); 15251 return nullptr; 15252 } 15253 15254 if (TemplateParams->size() > 0) { 15255 // This is a declaration or definition of a class template (which may 15256 // be a member of another template). 15257 15258 if (Invalid) 15259 return nullptr; 15260 15261 OwnedDecl = false; 15262 DeclResult Result = CheckClassTemplate( 15263 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams, 15264 AS, ModulePrivateLoc, 15265 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1, 15266 TemplateParameterLists.data(), SkipBody); 15267 return Result.get(); 15268 } else { 15269 // The "template<>" header is extraneous. 15270 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 15271 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 15272 isMemberSpecialization = true; 15273 } 15274 } 15275 } 15276 15277 // Figure out the underlying type if this a enum declaration. We need to do 15278 // this early, because it's needed to detect if this is an incompatible 15279 // redeclaration. 15280 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 15281 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; 15282 15283 if (Kind == TTK_Enum) { 15284 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { 15285 // No underlying type explicitly specified, or we failed to parse the 15286 // type, default to int. 15287 EnumUnderlying = Context.IntTy.getTypePtr(); 15288 } else if (UnderlyingType.get()) { 15289 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 15290 // integral type; any cv-qualification is ignored. 15291 TypeSourceInfo *TI = nullptr; 15292 GetTypeFromParser(UnderlyingType.get(), &TI); 15293 EnumUnderlying = TI; 15294 15295 if (CheckEnumUnderlyingType(TI)) 15296 // Recover by falling back to int. 15297 EnumUnderlying = Context.IntTy.getTypePtr(); 15298 15299 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 15300 UPPC_FixedUnderlyingType)) 15301 EnumUnderlying = Context.IntTy.getTypePtr(); 15302 15303 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) { 15304 // For MSVC ABI compatibility, unfixed enums must use an underlying type 15305 // of 'int'. However, if this is an unfixed forward declaration, don't set 15306 // the underlying type unless the user enables -fms-compatibility. This 15307 // makes unfixed forward declared enums incomplete and is more conforming. 15308 if (TUK == TUK_Definition || getLangOpts().MSVCCompat) 15309 EnumUnderlying = Context.IntTy.getTypePtr(); 15310 } 15311 } 15312 15313 DeclContext *SearchDC = CurContext; 15314 DeclContext *DC = CurContext; 15315 bool isStdBadAlloc = false; 15316 bool isStdAlignValT = false; 15317 15318 RedeclarationKind Redecl = forRedeclarationInCurContext(); 15319 if (TUK == TUK_Friend || TUK == TUK_Reference) 15320 Redecl = NotForRedeclaration; 15321 15322 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C 15323 /// implemented asks for structural equivalence checking, the returned decl 15324 /// here is passed back to the parser, allowing the tag body to be parsed. 15325 auto createTagFromNewDecl = [&]() -> TagDecl * { 15326 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage"); 15327 // If there is an identifier, use the location of the identifier as the 15328 // location of the decl, otherwise use the location of the struct/union 15329 // keyword. 15330 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 15331 TagDecl *New = nullptr; 15332 15333 if (Kind == TTK_Enum) { 15334 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, 15335 ScopedEnum, ScopedEnumUsesClassTag, IsFixed); 15336 // If this is an undefined enum, bail. 15337 if (TUK != TUK_Definition && !Invalid) 15338 return nullptr; 15339 if (EnumUnderlying) { 15340 EnumDecl *ED = cast<EnumDecl>(New); 15341 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) 15342 ED->setIntegerTypeSourceInfo(TI); 15343 else 15344 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); 15345 ED->setPromotionType(ED->getIntegerType()); 15346 } 15347 } else { // struct/union 15348 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 15349 nullptr); 15350 } 15351 15352 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 15353 // Add alignment attributes if necessary; these attributes are checked 15354 // when the ASTContext lays out the structure. 15355 // 15356 // It is important for implementing the correct semantics that this 15357 // happen here (in ActOnTag). The #pragma pack stack is 15358 // maintained as a result of parser callbacks which can occur at 15359 // many points during the parsing of a struct declaration (because 15360 // the #pragma tokens are effectively skipped over during the 15361 // parsing of the struct). 15362 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 15363 AddAlignmentAttributesForRecord(RD); 15364 AddMsStructLayoutForRecord(RD); 15365 } 15366 } 15367 New->setLexicalDeclContext(CurContext); 15368 return New; 15369 }; 15370 15371 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 15372 if (Name && SS.isNotEmpty()) { 15373 // We have a nested-name tag ('struct foo::bar'). 15374 15375 // Check for invalid 'foo::'. 15376 if (SS.isInvalid()) { 15377 Name = nullptr; 15378 goto CreateNewDecl; 15379 } 15380 15381 // If this is a friend or a reference to a class in a dependent 15382 // context, don't try to make a decl for it. 15383 if (TUK == TUK_Friend || TUK == TUK_Reference) { 15384 DC = computeDeclContext(SS, false); 15385 if (!DC) { 15386 IsDependent = true; 15387 return nullptr; 15388 } 15389 } else { 15390 DC = computeDeclContext(SS, true); 15391 if (!DC) { 15392 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 15393 << SS.getRange(); 15394 return nullptr; 15395 } 15396 } 15397 15398 if (RequireCompleteDeclContext(SS, DC)) 15399 return nullptr; 15400 15401 SearchDC = DC; 15402 // Look-up name inside 'foo::'. 15403 LookupQualifiedName(Previous, DC); 15404 15405 if (Previous.isAmbiguous()) 15406 return nullptr; 15407 15408 if (Previous.empty()) { 15409 // Name lookup did not find anything. However, if the 15410 // nested-name-specifier refers to the current instantiation, 15411 // and that current instantiation has any dependent base 15412 // classes, we might find something at instantiation time: treat 15413 // this as a dependent elaborated-type-specifier. 15414 // But this only makes any sense for reference-like lookups. 15415 if (Previous.wasNotFoundInCurrentInstantiation() && 15416 (TUK == TUK_Reference || TUK == TUK_Friend)) { 15417 IsDependent = true; 15418 return nullptr; 15419 } 15420 15421 // A tag 'foo::bar' must already exist. 15422 Diag(NameLoc, diag::err_not_tag_in_scope) 15423 << Kind << Name << DC << SS.getRange(); 15424 Name = nullptr; 15425 Invalid = true; 15426 goto CreateNewDecl; 15427 } 15428 } else if (Name) { 15429 // C++14 [class.mem]p14: 15430 // If T is the name of a class, then each of the following shall have a 15431 // name different from T: 15432 // -- every member of class T that is itself a type 15433 if (TUK != TUK_Reference && TUK != TUK_Friend && 15434 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 15435 return nullptr; 15436 15437 // If this is a named struct, check to see if there was a previous forward 15438 // declaration or definition. 15439 // FIXME: We're looking into outer scopes here, even when we 15440 // shouldn't be. Doing so can result in ambiguities that we 15441 // shouldn't be diagnosing. 15442 LookupName(Previous, S); 15443 15444 // When declaring or defining a tag, ignore ambiguities introduced 15445 // by types using'ed into this scope. 15446 if (Previous.isAmbiguous() && 15447 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 15448 LookupResult::Filter F = Previous.makeFilter(); 15449 while (F.hasNext()) { 15450 NamedDecl *ND = F.next(); 15451 if (!ND->getDeclContext()->getRedeclContext()->Equals( 15452 SearchDC->getRedeclContext())) 15453 F.erase(); 15454 } 15455 F.done(); 15456 } 15457 15458 // C++11 [namespace.memdef]p3: 15459 // If the name in a friend declaration is neither qualified nor 15460 // a template-id and the declaration is a function or an 15461 // elaborated-type-specifier, the lookup to determine whether 15462 // the entity has been previously declared shall not consider 15463 // any scopes outside the innermost enclosing namespace. 15464 // 15465 // MSVC doesn't implement the above rule for types, so a friend tag 15466 // declaration may be a redeclaration of a type declared in an enclosing 15467 // scope. They do implement this rule for friend functions. 15468 // 15469 // Does it matter that this should be by scope instead of by 15470 // semantic context? 15471 if (!Previous.empty() && TUK == TUK_Friend) { 15472 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 15473 LookupResult::Filter F = Previous.makeFilter(); 15474 bool FriendSawTagOutsideEnclosingNamespace = false; 15475 while (F.hasNext()) { 15476 NamedDecl *ND = F.next(); 15477 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15478 if (DC->isFileContext() && 15479 !EnclosingNS->Encloses(ND->getDeclContext())) { 15480 if (getLangOpts().MSVCCompat) 15481 FriendSawTagOutsideEnclosingNamespace = true; 15482 else 15483 F.erase(); 15484 } 15485 } 15486 F.done(); 15487 15488 // Diagnose this MSVC extension in the easy case where lookup would have 15489 // unambiguously found something outside the enclosing namespace. 15490 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 15491 NamedDecl *ND = Previous.getFoundDecl(); 15492 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 15493 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 15494 } 15495 } 15496 15497 // Note: there used to be some attempt at recovery here. 15498 if (Previous.isAmbiguous()) 15499 return nullptr; 15500 15501 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 15502 // FIXME: This makes sure that we ignore the contexts associated 15503 // with C structs, unions, and enums when looking for a matching 15504 // tag declaration or definition. See the similar lookup tweak 15505 // in Sema::LookupName; is there a better way to deal with this? 15506 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 15507 SearchDC = SearchDC->getParent(); 15508 } 15509 } 15510 15511 if (Previous.isSingleResult() && 15512 Previous.getFoundDecl()->isTemplateParameter()) { 15513 // Maybe we will complain about the shadowed template parameter. 15514 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 15515 // Just pretend that we didn't see the previous declaration. 15516 Previous.clear(); 15517 } 15518 15519 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 15520 DC->Equals(getStdNamespace())) { 15521 if (Name->isStr("bad_alloc")) { 15522 // This is a declaration of or a reference to "std::bad_alloc". 15523 isStdBadAlloc = true; 15524 15525 // If std::bad_alloc has been implicitly declared (but made invisible to 15526 // name lookup), fill in this implicit declaration as the previous 15527 // declaration, so that the declarations get chained appropriately. 15528 if (Previous.empty() && StdBadAlloc) 15529 Previous.addDecl(getStdBadAlloc()); 15530 } else if (Name->isStr("align_val_t")) { 15531 isStdAlignValT = true; 15532 if (Previous.empty() && StdAlignValT) 15533 Previous.addDecl(getStdAlignValT()); 15534 } 15535 } 15536 15537 // If we didn't find a previous declaration, and this is a reference 15538 // (or friend reference), move to the correct scope. In C++, we 15539 // also need to do a redeclaration lookup there, just in case 15540 // there's a shadow friend decl. 15541 if (Name && Previous.empty() && 15542 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { 15543 if (Invalid) goto CreateNewDecl; 15544 assert(SS.isEmpty()); 15545 15546 if (TUK == TUK_Reference || IsTemplateParamOrArg) { 15547 // C++ [basic.scope.pdecl]p5: 15548 // -- for an elaborated-type-specifier of the form 15549 // 15550 // class-key identifier 15551 // 15552 // if the elaborated-type-specifier is used in the 15553 // decl-specifier-seq or parameter-declaration-clause of a 15554 // function defined in namespace scope, the identifier is 15555 // declared as a class-name in the namespace that contains 15556 // the declaration; otherwise, except as a friend 15557 // declaration, the identifier is declared in the smallest 15558 // non-class, non-function-prototype scope that contains the 15559 // declaration. 15560 // 15561 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 15562 // C structs and unions. 15563 // 15564 // It is an error in C++ to declare (rather than define) an enum 15565 // type, including via an elaborated type specifier. We'll 15566 // diagnose that later; for now, declare the enum in the same 15567 // scope as we would have picked for any other tag type. 15568 // 15569 // GNU C also supports this behavior as part of its incomplete 15570 // enum types extension, while GNU C++ does not. 15571 // 15572 // Find the context where we'll be declaring the tag. 15573 // FIXME: We would like to maintain the current DeclContext as the 15574 // lexical context, 15575 SearchDC = getTagInjectionContext(SearchDC); 15576 15577 // Find the scope where we'll be declaring the tag. 15578 S = getTagInjectionScope(S, getLangOpts()); 15579 } else { 15580 assert(TUK == TUK_Friend); 15581 // C++ [namespace.memdef]p3: 15582 // If a friend declaration in a non-local class first declares a 15583 // class or function, the friend class or function is a member of 15584 // the innermost enclosing namespace. 15585 SearchDC = SearchDC->getEnclosingNamespaceContext(); 15586 } 15587 15588 // In C++, we need to do a redeclaration lookup to properly 15589 // diagnose some problems. 15590 // FIXME: redeclaration lookup is also used (with and without C++) to find a 15591 // hidden declaration so that we don't get ambiguity errors when using a 15592 // type declared by an elaborated-type-specifier. In C that is not correct 15593 // and we should instead merge compatible types found by lookup. 15594 if (getLangOpts().CPlusPlus) { 15595 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 15596 LookupQualifiedName(Previous, SearchDC); 15597 } else { 15598 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 15599 LookupName(Previous, S); 15600 } 15601 } 15602 15603 // If we have a known previous declaration to use, then use it. 15604 if (Previous.empty() && SkipBody && SkipBody->Previous) 15605 Previous.addDecl(SkipBody->Previous); 15606 15607 if (!Previous.empty()) { 15608 NamedDecl *PrevDecl = Previous.getFoundDecl(); 15609 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 15610 15611 // It's okay to have a tag decl in the same scope as a typedef 15612 // which hides a tag decl in the same scope. Finding this 15613 // insanity with a redeclaration lookup can only actually happen 15614 // in C++. 15615 // 15616 // This is also okay for elaborated-type-specifiers, which is 15617 // technically forbidden by the current standard but which is 15618 // okay according to the likely resolution of an open issue; 15619 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 15620 if (getLangOpts().CPlusPlus) { 15621 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 15622 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 15623 TagDecl *Tag = TT->getDecl(); 15624 if (Tag->getDeclName() == Name && 15625 Tag->getDeclContext()->getRedeclContext() 15626 ->Equals(TD->getDeclContext()->getRedeclContext())) { 15627 PrevDecl = Tag; 15628 Previous.clear(); 15629 Previous.addDecl(Tag); 15630 Previous.resolveKind(); 15631 } 15632 } 15633 } 15634 } 15635 15636 // If this is a redeclaration of a using shadow declaration, it must 15637 // declare a tag in the same context. In MSVC mode, we allow a 15638 // redefinition if either context is within the other. 15639 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 15640 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 15641 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 15642 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 15643 !(OldTag && isAcceptableTagRedeclContext( 15644 *this, OldTag->getDeclContext(), SearchDC))) { 15645 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 15646 Diag(Shadow->getTargetDecl()->getLocation(), 15647 diag::note_using_decl_target); 15648 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) 15649 << 0; 15650 // Recover by ignoring the old declaration. 15651 Previous.clear(); 15652 goto CreateNewDecl; 15653 } 15654 } 15655 15656 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 15657 // If this is a use of a previous tag, or if the tag is already declared 15658 // in the same scope (so that the definition/declaration completes or 15659 // rementions the tag), reuse the decl. 15660 if (TUK == TUK_Reference || TUK == TUK_Friend || 15661 isDeclInScope(DirectPrevDecl, SearchDC, S, 15662 SS.isNotEmpty() || isMemberSpecialization)) { 15663 // Make sure that this wasn't declared as an enum and now used as a 15664 // struct or something similar. 15665 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 15666 TUK == TUK_Definition, KWLoc, 15667 Name)) { 15668 bool SafeToContinue 15669 = (PrevTagDecl->getTagKind() != TTK_Enum && 15670 Kind != TTK_Enum); 15671 if (SafeToContinue) 15672 Diag(KWLoc, diag::err_use_with_wrong_tag) 15673 << Name 15674 << FixItHint::CreateReplacement(SourceRange(KWLoc), 15675 PrevTagDecl->getKindName()); 15676 else 15677 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 15678 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 15679 15680 if (SafeToContinue) 15681 Kind = PrevTagDecl->getTagKind(); 15682 else { 15683 // Recover by making this an anonymous redefinition. 15684 Name = nullptr; 15685 Previous.clear(); 15686 Invalid = true; 15687 } 15688 } 15689 15690 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 15691 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 15692 if (TUK == TUK_Reference || TUK == TUK_Friend) 15693 return PrevTagDecl; 15694 15695 QualType EnumUnderlyingTy; 15696 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 15697 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 15698 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 15699 EnumUnderlyingTy = QualType(T, 0); 15700 15701 // All conflicts with previous declarations are recovered by 15702 // returning the previous declaration, unless this is a definition, 15703 // in which case we want the caller to bail out. 15704 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 15705 ScopedEnum, EnumUnderlyingTy, 15706 IsFixed, PrevEnum)) 15707 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 15708 } 15709 15710 // C++11 [class.mem]p1: 15711 // A member shall not be declared twice in the member-specification, 15712 // except that a nested class or member class template can be declared 15713 // and then later defined. 15714 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 15715 S->isDeclScope(PrevDecl)) { 15716 Diag(NameLoc, diag::ext_member_redeclared); 15717 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 15718 } 15719 15720 if (!Invalid) { 15721 // If this is a use, just return the declaration we found, unless 15722 // we have attributes. 15723 if (TUK == TUK_Reference || TUK == TUK_Friend) { 15724 if (!Attrs.empty()) { 15725 // FIXME: Diagnose these attributes. For now, we create a new 15726 // declaration to hold them. 15727 } else if (TUK == TUK_Reference && 15728 (PrevTagDecl->getFriendObjectKind() == 15729 Decl::FOK_Undeclared || 15730 PrevDecl->getOwningModule() != getCurrentModule()) && 15731 SS.isEmpty()) { 15732 // This declaration is a reference to an existing entity, but 15733 // has different visibility from that entity: it either makes 15734 // a friend visible or it makes a type visible in a new module. 15735 // In either case, create a new declaration. We only do this if 15736 // the declaration would have meant the same thing if no prior 15737 // declaration were found, that is, if it was found in the same 15738 // scope where we would have injected a declaration. 15739 if (!getTagInjectionContext(CurContext)->getRedeclContext() 15740 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 15741 return PrevTagDecl; 15742 // This is in the injected scope, create a new declaration in 15743 // that scope. 15744 S = getTagInjectionScope(S, getLangOpts()); 15745 } else { 15746 return PrevTagDecl; 15747 } 15748 } 15749 15750 // Diagnose attempts to redefine a tag. 15751 if (TUK == TUK_Definition) { 15752 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 15753 // If we're defining a specialization and the previous definition 15754 // is from an implicit instantiation, don't emit an error 15755 // here; we'll catch this in the general case below. 15756 bool IsExplicitSpecializationAfterInstantiation = false; 15757 if (isMemberSpecialization) { 15758 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 15759 IsExplicitSpecializationAfterInstantiation = 15760 RD->getTemplateSpecializationKind() != 15761 TSK_ExplicitSpecialization; 15762 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 15763 IsExplicitSpecializationAfterInstantiation = 15764 ED->getTemplateSpecializationKind() != 15765 TSK_ExplicitSpecialization; 15766 } 15767 15768 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do 15769 // not keep more that one definition around (merge them). However, 15770 // ensure the decl passes the structural compatibility check in 15771 // C11 6.2.7/1 (or 6.1.2.6/1 in C89). 15772 NamedDecl *Hidden = nullptr; 15773 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 15774 // There is a definition of this tag, but it is not visible. We 15775 // explicitly make use of C++'s one definition rule here, and 15776 // assume that this definition is identical to the hidden one 15777 // we already have. Make the existing definition visible and 15778 // use it in place of this one. 15779 if (!getLangOpts().CPlusPlus) { 15780 // Postpone making the old definition visible until after we 15781 // complete parsing the new one and do the structural 15782 // comparison. 15783 SkipBody->CheckSameAsPrevious = true; 15784 SkipBody->New = createTagFromNewDecl(); 15785 SkipBody->Previous = Def; 15786 return Def; 15787 } else { 15788 SkipBody->ShouldSkip = true; 15789 SkipBody->Previous = Def; 15790 makeMergedDefinitionVisible(Hidden); 15791 // Carry on and handle it like a normal definition. We'll 15792 // skip starting the definitiion later. 15793 } 15794 } else if (!IsExplicitSpecializationAfterInstantiation) { 15795 // A redeclaration in function prototype scope in C isn't 15796 // visible elsewhere, so merely issue a warning. 15797 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 15798 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 15799 else 15800 Diag(NameLoc, diag::err_redefinition) << Name; 15801 notePreviousDefinition(Def, 15802 NameLoc.isValid() ? NameLoc : KWLoc); 15803 // If this is a redefinition, recover by making this 15804 // struct be anonymous, which will make any later 15805 // references get the previous definition. 15806 Name = nullptr; 15807 Previous.clear(); 15808 Invalid = true; 15809 } 15810 } else { 15811 // If the type is currently being defined, complain 15812 // about a nested redefinition. 15813 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 15814 if (TD->isBeingDefined()) { 15815 Diag(NameLoc, diag::err_nested_redefinition) << Name; 15816 Diag(PrevTagDecl->getLocation(), 15817 diag::note_previous_definition); 15818 Name = nullptr; 15819 Previous.clear(); 15820 Invalid = true; 15821 } 15822 } 15823 15824 // Okay, this is definition of a previously declared or referenced 15825 // tag. We're going to create a new Decl for it. 15826 } 15827 15828 // Okay, we're going to make a redeclaration. If this is some kind 15829 // of reference, make sure we build the redeclaration in the same DC 15830 // as the original, and ignore the current access specifier. 15831 if (TUK == TUK_Friend || TUK == TUK_Reference) { 15832 SearchDC = PrevTagDecl->getDeclContext(); 15833 AS = AS_none; 15834 } 15835 } 15836 // If we get here we have (another) forward declaration or we 15837 // have a definition. Just create a new decl. 15838 15839 } else { 15840 // If we get here, this is a definition of a new tag type in a nested 15841 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 15842 // new decl/type. We set PrevDecl to NULL so that the entities 15843 // have distinct types. 15844 Previous.clear(); 15845 } 15846 // If we get here, we're going to create a new Decl. If PrevDecl 15847 // is non-NULL, it's a definition of the tag declared by 15848 // PrevDecl. If it's NULL, we have a new definition. 15849 15850 // Otherwise, PrevDecl is not a tag, but was found with tag 15851 // lookup. This is only actually possible in C++, where a few 15852 // things like templates still live in the tag namespace. 15853 } else { 15854 // Use a better diagnostic if an elaborated-type-specifier 15855 // found the wrong kind of type on the first 15856 // (non-redeclaration) lookup. 15857 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 15858 !Previous.isForRedeclaration()) { 15859 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 15860 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 15861 << Kind; 15862 Diag(PrevDecl->getLocation(), diag::note_declared_at); 15863 Invalid = true; 15864 15865 // Otherwise, only diagnose if the declaration is in scope. 15866 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 15867 SS.isNotEmpty() || isMemberSpecialization)) { 15868 // do nothing 15869 15870 // Diagnose implicit declarations introduced by elaborated types. 15871 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 15872 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 15873 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 15874 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 15875 Invalid = true; 15876 15877 // Otherwise it's a declaration. Call out a particularly common 15878 // case here. 15879 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 15880 unsigned Kind = 0; 15881 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 15882 Diag(NameLoc, diag::err_tag_definition_of_typedef) 15883 << Name << Kind << TND->getUnderlyingType(); 15884 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 15885 Invalid = true; 15886 15887 // Otherwise, diagnose. 15888 } else { 15889 // The tag name clashes with something else in the target scope, 15890 // issue an error and recover by making this tag be anonymous. 15891 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 15892 notePreviousDefinition(PrevDecl, NameLoc); 15893 Name = nullptr; 15894 Invalid = true; 15895 } 15896 15897 // The existing declaration isn't relevant to us; we're in a 15898 // new scope, so clear out the previous declaration. 15899 Previous.clear(); 15900 } 15901 } 15902 15903 CreateNewDecl: 15904 15905 TagDecl *PrevDecl = nullptr; 15906 if (Previous.isSingleResult()) 15907 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 15908 15909 // If there is an identifier, use the location of the identifier as the 15910 // location of the decl, otherwise use the location of the struct/union 15911 // keyword. 15912 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 15913 15914 // Otherwise, create a new declaration. If there is a previous 15915 // declaration of the same entity, the two will be linked via 15916 // PrevDecl. 15917 TagDecl *New; 15918 15919 if (Kind == TTK_Enum) { 15920 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 15921 // enum X { A, B, C } D; D should chain to X. 15922 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 15923 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 15924 ScopedEnumUsesClassTag, IsFixed); 15925 15926 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 15927 StdAlignValT = cast<EnumDecl>(New); 15928 15929 // If this is an undefined enum, warn. 15930 if (TUK != TUK_Definition && !Invalid) { 15931 TagDecl *Def; 15932 if (IsFixed && cast<EnumDecl>(New)->isFixed()) { 15933 // C++0x: 7.2p2: opaque-enum-declaration. 15934 // Conflicts are diagnosed above. Do nothing. 15935 } 15936 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 15937 Diag(Loc, diag::ext_forward_ref_enum_def) 15938 << New; 15939 Diag(Def->getLocation(), diag::note_previous_definition); 15940 } else { 15941 unsigned DiagID = diag::ext_forward_ref_enum; 15942 if (getLangOpts().MSVCCompat) 15943 DiagID = diag::ext_ms_forward_ref_enum; 15944 else if (getLangOpts().CPlusPlus) 15945 DiagID = diag::err_forward_ref_enum; 15946 Diag(Loc, DiagID); 15947 } 15948 } 15949 15950 if (EnumUnderlying) { 15951 EnumDecl *ED = cast<EnumDecl>(New); 15952 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 15953 ED->setIntegerTypeSourceInfo(TI); 15954 else 15955 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 15956 ED->setPromotionType(ED->getIntegerType()); 15957 assert(ED->isComplete() && "enum with type should be complete"); 15958 } 15959 } else { 15960 // struct/union/class 15961 15962 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 15963 // struct X { int A; } D; D should chain to X. 15964 if (getLangOpts().CPlusPlus) { 15965 // FIXME: Look for a way to use RecordDecl for simple structs. 15966 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 15967 cast_or_null<CXXRecordDecl>(PrevDecl)); 15968 15969 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 15970 StdBadAlloc = cast<CXXRecordDecl>(New); 15971 } else 15972 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 15973 cast_or_null<RecordDecl>(PrevDecl)); 15974 } 15975 15976 // C++11 [dcl.type]p3: 15977 // A type-specifier-seq shall not define a class or enumeration [...]. 15978 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && 15979 TUK == TUK_Definition) { 15980 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 15981 << Context.getTagDeclType(New); 15982 Invalid = true; 15983 } 15984 15985 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && 15986 DC->getDeclKind() == Decl::Enum) { 15987 Diag(New->getLocation(), diag::err_type_defined_in_enum) 15988 << Context.getTagDeclType(New); 15989 Invalid = true; 15990 } 15991 15992 // Maybe add qualifier info. 15993 if (SS.isNotEmpty()) { 15994 if (SS.isSet()) { 15995 // If this is either a declaration or a definition, check the 15996 // nested-name-specifier against the current context. 15997 if ((TUK == TUK_Definition || TUK == TUK_Declaration) && 15998 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, 15999 isMemberSpecialization)) 16000 Invalid = true; 16001 16002 New->setQualifierInfo(SS.getWithLocInContext(Context)); 16003 if (TemplateParameterLists.size() > 0) { 16004 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 16005 } 16006 } 16007 else 16008 Invalid = true; 16009 } 16010 16011 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 16012 // Add alignment attributes if necessary; these attributes are checked when 16013 // the ASTContext lays out the structure. 16014 // 16015 // It is important for implementing the correct semantics that this 16016 // happen here (in ActOnTag). The #pragma pack stack is 16017 // maintained as a result of parser callbacks which can occur at 16018 // many points during the parsing of a struct declaration (because 16019 // the #pragma tokens are effectively skipped over during the 16020 // parsing of the struct). 16021 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 16022 AddAlignmentAttributesForRecord(RD); 16023 AddMsStructLayoutForRecord(RD); 16024 } 16025 } 16026 16027 if (ModulePrivateLoc.isValid()) { 16028 if (isMemberSpecialization) 16029 Diag(New->getLocation(), diag::err_module_private_specialization) 16030 << 2 16031 << FixItHint::CreateRemoval(ModulePrivateLoc); 16032 // __module_private__ does not apply to local classes. However, we only 16033 // diagnose this as an error when the declaration specifiers are 16034 // freestanding. Here, we just ignore the __module_private__. 16035 else if (!SearchDC->isFunctionOrMethod()) 16036 New->setModulePrivate(); 16037 } 16038 16039 // If this is a specialization of a member class (of a class template), 16040 // check the specialization. 16041 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 16042 Invalid = true; 16043 16044 // If we're declaring or defining a tag in function prototype scope in C, 16045 // note that this type can only be used within the function and add it to 16046 // the list of decls to inject into the function definition scope. 16047 if ((Name || Kind == TTK_Enum) && 16048 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 16049 if (getLangOpts().CPlusPlus) { 16050 // C++ [dcl.fct]p6: 16051 // Types shall not be defined in return or parameter types. 16052 if (TUK == TUK_Definition && !IsTypeSpecifier) { 16053 Diag(Loc, diag::err_type_defined_in_param_type) 16054 << Name; 16055 Invalid = true; 16056 } 16057 } else if (!PrevDecl) { 16058 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 16059 } 16060 } 16061 16062 if (Invalid) 16063 New->setInvalidDecl(); 16064 16065 // Set the lexical context. If the tag has a C++ scope specifier, the 16066 // lexical context will be different from the semantic context. 16067 New->setLexicalDeclContext(CurContext); 16068 16069 // Mark this as a friend decl if applicable. 16070 // In Microsoft mode, a friend declaration also acts as a forward 16071 // declaration so we always pass true to setObjectOfFriendDecl to make 16072 // the tag name visible. 16073 if (TUK == TUK_Friend) 16074 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 16075 16076 // Set the access specifier. 16077 if (!Invalid && SearchDC->isRecord()) 16078 SetMemberAccessSpecifier(New, PrevDecl, AS); 16079 16080 if (PrevDecl) 16081 CheckRedeclarationModuleOwnership(New, PrevDecl); 16082 16083 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) 16084 New->startDefinition(); 16085 16086 ProcessDeclAttributeList(S, New, Attrs); 16087 AddPragmaAttributes(S, New); 16088 16089 // If this has an identifier, add it to the scope stack. 16090 if (TUK == TUK_Friend) { 16091 // We might be replacing an existing declaration in the lookup tables; 16092 // if so, borrow its access specifier. 16093 if (PrevDecl) 16094 New->setAccess(PrevDecl->getAccess()); 16095 16096 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 16097 DC->makeDeclVisibleInContext(New); 16098 if (Name) // can be null along some error paths 16099 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 16100 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 16101 } else if (Name) { 16102 S = getNonFieldDeclScope(S); 16103 PushOnScopeChains(New, S, true); 16104 } else { 16105 CurContext->addDecl(New); 16106 } 16107 16108 // If this is the C FILE type, notify the AST context. 16109 if (IdentifierInfo *II = New->getIdentifier()) 16110 if (!New->isInvalidDecl() && 16111 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 16112 II->isStr("FILE")) 16113 Context.setFILEDecl(New); 16114 16115 if (PrevDecl) 16116 mergeDeclAttributes(New, PrevDecl); 16117 16118 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) 16119 inferGslOwnerPointerAttribute(CXXRD); 16120 16121 // If there's a #pragma GCC visibility in scope, set the visibility of this 16122 // record. 16123 AddPushedVisibilityAttribute(New); 16124 16125 if (isMemberSpecialization && !New->isInvalidDecl()) 16126 CompleteMemberSpecialization(New, Previous); 16127 16128 OwnedDecl = true; 16129 // In C++, don't return an invalid declaration. We can't recover well from 16130 // the cases where we make the type anonymous. 16131 if (Invalid && getLangOpts().CPlusPlus) { 16132 if (New->isBeingDefined()) 16133 if (auto RD = dyn_cast<RecordDecl>(New)) 16134 RD->completeDefinition(); 16135 return nullptr; 16136 } else if (SkipBody && SkipBody->ShouldSkip) { 16137 return SkipBody->Previous; 16138 } else { 16139 return New; 16140 } 16141 } 16142 16143 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 16144 AdjustDeclIfTemplate(TagD); 16145 TagDecl *Tag = cast<TagDecl>(TagD); 16146 16147 // Enter the tag context. 16148 PushDeclContext(S, Tag); 16149 16150 ActOnDocumentableDecl(TagD); 16151 16152 // If there's a #pragma GCC visibility in scope, set the visibility of this 16153 // record. 16154 AddPushedVisibilityAttribute(Tag); 16155 } 16156 16157 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, 16158 SkipBodyInfo &SkipBody) { 16159 if (!hasStructuralCompatLayout(Prev, SkipBody.New)) 16160 return false; 16161 16162 // Make the previous decl visible. 16163 makeMergedDefinitionVisible(SkipBody.Previous); 16164 return true; 16165 } 16166 16167 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 16168 assert(isa<ObjCContainerDecl>(IDecl) && 16169 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 16170 DeclContext *OCD = cast<DeclContext>(IDecl); 16171 assert(OCD->getLexicalParent() == CurContext && 16172 "The next DeclContext should be lexically contained in the current one."); 16173 CurContext = OCD; 16174 return IDecl; 16175 } 16176 16177 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 16178 SourceLocation FinalLoc, 16179 bool IsFinalSpelledSealed, 16180 SourceLocation LBraceLoc) { 16181 AdjustDeclIfTemplate(TagD); 16182 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 16183 16184 FieldCollector->StartClass(); 16185 16186 if (!Record->getIdentifier()) 16187 return; 16188 16189 if (FinalLoc.isValid()) 16190 Record->addAttr(FinalAttr::Create( 16191 Context, FinalLoc, AttributeCommonInfo::AS_Keyword, 16192 static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed))); 16193 16194 // C++ [class]p2: 16195 // [...] The class-name is also inserted into the scope of the 16196 // class itself; this is known as the injected-class-name. For 16197 // purposes of access checking, the injected-class-name is treated 16198 // as if it were a public member name. 16199 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create( 16200 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(), 16201 Record->getLocation(), Record->getIdentifier(), 16202 /*PrevDecl=*/nullptr, 16203 /*DelayTypeCreation=*/true); 16204 Context.getTypeDeclType(InjectedClassName, Record); 16205 InjectedClassName->setImplicit(); 16206 InjectedClassName->setAccess(AS_public); 16207 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 16208 InjectedClassName->setDescribedClassTemplate(Template); 16209 PushOnScopeChains(InjectedClassName, S); 16210 assert(InjectedClassName->isInjectedClassName() && 16211 "Broken injected-class-name"); 16212 } 16213 16214 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 16215 SourceRange BraceRange) { 16216 AdjustDeclIfTemplate(TagD); 16217 TagDecl *Tag = cast<TagDecl>(TagD); 16218 Tag->setBraceRange(BraceRange); 16219 16220 // Make sure we "complete" the definition even it is invalid. 16221 if (Tag->isBeingDefined()) { 16222 assert(Tag->isInvalidDecl() && "We should already have completed it"); 16223 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16224 RD->completeDefinition(); 16225 } 16226 16227 if (isa<CXXRecordDecl>(Tag)) { 16228 FieldCollector->FinishClass(); 16229 } 16230 16231 // Exit this scope of this tag's definition. 16232 PopDeclContext(); 16233 16234 if (getCurLexicalContext()->isObjCContainer() && 16235 Tag->getDeclContext()->isFileContext()) 16236 Tag->setTopLevelDeclInObjCContainer(); 16237 16238 // Notify the consumer that we've defined a tag. 16239 if (!Tag->isInvalidDecl()) 16240 Consumer.HandleTagDeclDefinition(Tag); 16241 } 16242 16243 void Sema::ActOnObjCContainerFinishDefinition() { 16244 // Exit this scope of this interface definition. 16245 PopDeclContext(); 16246 } 16247 16248 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 16249 assert(DC == CurContext && "Mismatch of container contexts"); 16250 OriginalLexicalContext = DC; 16251 ActOnObjCContainerFinishDefinition(); 16252 } 16253 16254 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 16255 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 16256 OriginalLexicalContext = nullptr; 16257 } 16258 16259 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 16260 AdjustDeclIfTemplate(TagD); 16261 TagDecl *Tag = cast<TagDecl>(TagD); 16262 Tag->setInvalidDecl(); 16263 16264 // Make sure we "complete" the definition even it is invalid. 16265 if (Tag->isBeingDefined()) { 16266 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16267 RD->completeDefinition(); 16268 } 16269 16270 // We're undoing ActOnTagStartDefinition here, not 16271 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 16272 // the FieldCollector. 16273 16274 PopDeclContext(); 16275 } 16276 16277 // Note that FieldName may be null for anonymous bitfields. 16278 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 16279 IdentifierInfo *FieldName, 16280 QualType FieldTy, bool IsMsStruct, 16281 Expr *BitWidth, bool *ZeroWidth) { 16282 assert(BitWidth); 16283 if (BitWidth->containsErrors()) 16284 return ExprError(); 16285 16286 // Default to true; that shouldn't confuse checks for emptiness 16287 if (ZeroWidth) 16288 *ZeroWidth = true; 16289 16290 // C99 6.7.2.1p4 - verify the field type. 16291 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 16292 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 16293 // Handle incomplete and sizeless types with a specific error. 16294 if (RequireCompleteSizedType(FieldLoc, FieldTy, 16295 diag::err_field_incomplete_or_sizeless)) 16296 return ExprError(); 16297 if (FieldName) 16298 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 16299 << FieldName << FieldTy << BitWidth->getSourceRange(); 16300 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 16301 << FieldTy << BitWidth->getSourceRange(); 16302 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 16303 UPPC_BitFieldWidth)) 16304 return ExprError(); 16305 16306 // If the bit-width is type- or value-dependent, don't try to check 16307 // it now. 16308 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 16309 return BitWidth; 16310 16311 llvm::APSInt Value; 16312 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 16313 if (ICE.isInvalid()) 16314 return ICE; 16315 BitWidth = ICE.get(); 16316 16317 if (Value != 0 && ZeroWidth) 16318 *ZeroWidth = false; 16319 16320 // Zero-width bitfield is ok for anonymous field. 16321 if (Value == 0 && FieldName) 16322 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 16323 16324 if (Value.isSigned() && Value.isNegative()) { 16325 if (FieldName) 16326 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 16327 << FieldName << Value.toString(10); 16328 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 16329 << Value.toString(10); 16330 } 16331 16332 if (!FieldTy->isDependentType()) { 16333 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 16334 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 16335 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 16336 16337 // Over-wide bitfields are an error in C or when using the MSVC bitfield 16338 // ABI. 16339 bool CStdConstraintViolation = 16340 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 16341 bool MSBitfieldViolation = 16342 Value.ugt(TypeStorageSize) && 16343 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 16344 if (CStdConstraintViolation || MSBitfieldViolation) { 16345 unsigned DiagWidth = 16346 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 16347 if (FieldName) 16348 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 16349 << FieldName << (unsigned)Value.getZExtValue() 16350 << !CStdConstraintViolation << DiagWidth; 16351 16352 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) 16353 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation 16354 << DiagWidth; 16355 } 16356 16357 // Warn on types where the user might conceivably expect to get all 16358 // specified bits as value bits: that's all integral types other than 16359 // 'bool'. 16360 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) { 16361 if (FieldName) 16362 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 16363 << FieldName << (unsigned)Value.getZExtValue() 16364 << (unsigned)TypeWidth; 16365 else 16366 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width) 16367 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth; 16368 } 16369 } 16370 16371 return BitWidth; 16372 } 16373 16374 /// ActOnField - Each field of a C struct/union is passed into this in order 16375 /// to create a FieldDecl object for it. 16376 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 16377 Declarator &D, Expr *BitfieldWidth) { 16378 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 16379 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 16380 /*InitStyle=*/ICIS_NoInit, AS_public); 16381 return Res; 16382 } 16383 16384 /// HandleField - Analyze a field of a C struct or a C++ data member. 16385 /// 16386 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 16387 SourceLocation DeclStart, 16388 Declarator &D, Expr *BitWidth, 16389 InClassInitStyle InitStyle, 16390 AccessSpecifier AS) { 16391 if (D.isDecompositionDeclarator()) { 16392 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 16393 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 16394 << Decomp.getSourceRange(); 16395 return nullptr; 16396 } 16397 16398 IdentifierInfo *II = D.getIdentifier(); 16399 SourceLocation Loc = DeclStart; 16400 if (II) Loc = D.getIdentifierLoc(); 16401 16402 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16403 QualType T = TInfo->getType(); 16404 if (getLangOpts().CPlusPlus) { 16405 CheckExtraCXXDefaultArguments(D); 16406 16407 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 16408 UPPC_DataMemberType)) { 16409 D.setInvalidType(); 16410 T = Context.IntTy; 16411 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 16412 } 16413 } 16414 16415 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 16416 16417 if (D.getDeclSpec().isInlineSpecified()) 16418 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 16419 << getLangOpts().CPlusPlus17; 16420 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 16421 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 16422 diag::err_invalid_thread) 16423 << DeclSpec::getSpecifierName(TSCS); 16424 16425 // Check to see if this name was declared as a member previously 16426 NamedDecl *PrevDecl = nullptr; 16427 LookupResult Previous(*this, II, Loc, LookupMemberName, 16428 ForVisibleRedeclaration); 16429 LookupName(Previous, S); 16430 switch (Previous.getResultKind()) { 16431 case LookupResult::Found: 16432 case LookupResult::FoundUnresolvedValue: 16433 PrevDecl = Previous.getAsSingle<NamedDecl>(); 16434 break; 16435 16436 case LookupResult::FoundOverloaded: 16437 PrevDecl = Previous.getRepresentativeDecl(); 16438 break; 16439 16440 case LookupResult::NotFound: 16441 case LookupResult::NotFoundInCurrentInstantiation: 16442 case LookupResult::Ambiguous: 16443 break; 16444 } 16445 Previous.suppressDiagnostics(); 16446 16447 if (PrevDecl && PrevDecl->isTemplateParameter()) { 16448 // Maybe we will complain about the shadowed template parameter. 16449 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 16450 // Just pretend that we didn't see the previous declaration. 16451 PrevDecl = nullptr; 16452 } 16453 16454 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 16455 PrevDecl = nullptr; 16456 16457 bool Mutable 16458 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 16459 SourceLocation TSSL = D.getBeginLoc(); 16460 FieldDecl *NewFD 16461 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 16462 TSSL, AS, PrevDecl, &D); 16463 16464 if (NewFD->isInvalidDecl()) 16465 Record->setInvalidDecl(); 16466 16467 if (D.getDeclSpec().isModulePrivateSpecified()) 16468 NewFD->setModulePrivate(); 16469 16470 if (NewFD->isInvalidDecl() && PrevDecl) { 16471 // Don't introduce NewFD into scope; there's already something 16472 // with the same name in the same scope. 16473 } else if (II) { 16474 PushOnScopeChains(NewFD, S); 16475 } else 16476 Record->addDecl(NewFD); 16477 16478 return NewFD; 16479 } 16480 16481 /// Build a new FieldDecl and check its well-formedness. 16482 /// 16483 /// This routine builds a new FieldDecl given the fields name, type, 16484 /// record, etc. \p PrevDecl should refer to any previous declaration 16485 /// with the same name and in the same scope as the field to be 16486 /// created. 16487 /// 16488 /// \returns a new FieldDecl. 16489 /// 16490 /// \todo The Declarator argument is a hack. It will be removed once 16491 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 16492 TypeSourceInfo *TInfo, 16493 RecordDecl *Record, SourceLocation Loc, 16494 bool Mutable, Expr *BitWidth, 16495 InClassInitStyle InitStyle, 16496 SourceLocation TSSL, 16497 AccessSpecifier AS, NamedDecl *PrevDecl, 16498 Declarator *D) { 16499 IdentifierInfo *II = Name.getAsIdentifierInfo(); 16500 bool InvalidDecl = false; 16501 if (D) InvalidDecl = D->isInvalidType(); 16502 16503 // If we receive a broken type, recover by assuming 'int' and 16504 // marking this declaration as invalid. 16505 if (T.isNull() || T->containsErrors()) { 16506 InvalidDecl = true; 16507 T = Context.IntTy; 16508 } 16509 16510 QualType EltTy = Context.getBaseElementType(T); 16511 if (!EltTy->isDependentType() && !EltTy->containsErrors()) { 16512 if (RequireCompleteSizedType(Loc, EltTy, 16513 diag::err_field_incomplete_or_sizeless)) { 16514 // Fields of incomplete type force their record to be invalid. 16515 Record->setInvalidDecl(); 16516 InvalidDecl = true; 16517 } else { 16518 NamedDecl *Def; 16519 EltTy->isIncompleteType(&Def); 16520 if (Def && Def->isInvalidDecl()) { 16521 Record->setInvalidDecl(); 16522 InvalidDecl = true; 16523 } 16524 } 16525 } 16526 16527 // TR 18037 does not allow fields to be declared with address space 16528 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() || 16529 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { 16530 Diag(Loc, diag::err_field_with_address_space); 16531 Record->setInvalidDecl(); 16532 InvalidDecl = true; 16533 } 16534 16535 if (LangOpts.OpenCL) { 16536 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 16537 // used as structure or union field: image, sampler, event or block types. 16538 if (T->isEventT() || T->isImageType() || T->isSamplerT() || 16539 T->isBlockPointerType()) { 16540 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 16541 Record->setInvalidDecl(); 16542 InvalidDecl = true; 16543 } 16544 // OpenCL v1.2 s6.9.c: bitfields are not supported. 16545 if (BitWidth) { 16546 Diag(Loc, diag::err_opencl_bitfields); 16547 InvalidDecl = true; 16548 } 16549 } 16550 16551 // Anonymous bit-fields cannot be cv-qualified (CWG 2229). 16552 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && 16553 T.hasQualifiers()) { 16554 InvalidDecl = true; 16555 Diag(Loc, diag::err_anon_bitfield_qualifiers); 16556 } 16557 16558 // C99 6.7.2.1p8: A member of a structure or union may have any type other 16559 // than a variably modified type. 16560 if (!InvalidDecl && T->isVariablyModifiedType()) { 16561 bool SizeIsNegative; 16562 llvm::APSInt Oversized; 16563 16564 TypeSourceInfo *FixedTInfo = 16565 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 16566 SizeIsNegative, 16567 Oversized); 16568 if (FixedTInfo) { 16569 Diag(Loc, diag::warn_illegal_constant_array_size); 16570 TInfo = FixedTInfo; 16571 T = FixedTInfo->getType(); 16572 } else { 16573 if (SizeIsNegative) 16574 Diag(Loc, diag::err_typecheck_negative_array_size); 16575 else if (Oversized.getBoolValue()) 16576 Diag(Loc, diag::err_array_too_large) 16577 << Oversized.toString(10); 16578 else 16579 Diag(Loc, diag::err_typecheck_field_variable_size); 16580 InvalidDecl = true; 16581 } 16582 } 16583 16584 // Fields can not have abstract class types 16585 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 16586 diag::err_abstract_type_in_decl, 16587 AbstractFieldType)) 16588 InvalidDecl = true; 16589 16590 bool ZeroWidth = false; 16591 if (InvalidDecl) 16592 BitWidth = nullptr; 16593 // If this is declared as a bit-field, check the bit-field. 16594 if (BitWidth) { 16595 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 16596 &ZeroWidth).get(); 16597 if (!BitWidth) { 16598 InvalidDecl = true; 16599 BitWidth = nullptr; 16600 ZeroWidth = false; 16601 } 16602 16603 // Only data members can have in-class initializers. 16604 if (BitWidth && !II && InitStyle) { 16605 Diag(Loc, diag::err_anon_bitfield_init); 16606 InvalidDecl = true; 16607 BitWidth = nullptr; 16608 ZeroWidth = false; 16609 } 16610 } 16611 16612 // Check that 'mutable' is consistent with the type of the declaration. 16613 if (!InvalidDecl && Mutable) { 16614 unsigned DiagID = 0; 16615 if (T->isReferenceType()) 16616 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 16617 : diag::err_mutable_reference; 16618 else if (T.isConstQualified()) 16619 DiagID = diag::err_mutable_const; 16620 16621 if (DiagID) { 16622 SourceLocation ErrLoc = Loc; 16623 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 16624 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 16625 Diag(ErrLoc, DiagID); 16626 if (DiagID != diag::ext_mutable_reference) { 16627 Mutable = false; 16628 InvalidDecl = true; 16629 } 16630 } 16631 } 16632 16633 // C++11 [class.union]p8 (DR1460): 16634 // At most one variant member of a union may have a 16635 // brace-or-equal-initializer. 16636 if (InitStyle != ICIS_NoInit) 16637 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 16638 16639 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 16640 BitWidth, Mutable, InitStyle); 16641 if (InvalidDecl) 16642 NewFD->setInvalidDecl(); 16643 16644 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 16645 Diag(Loc, diag::err_duplicate_member) << II; 16646 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 16647 NewFD->setInvalidDecl(); 16648 } 16649 16650 if (!InvalidDecl && getLangOpts().CPlusPlus) { 16651 if (Record->isUnion()) { 16652 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 16653 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 16654 if (RDecl->getDefinition()) { 16655 // C++ [class.union]p1: An object of a class with a non-trivial 16656 // constructor, a non-trivial copy constructor, a non-trivial 16657 // destructor, or a non-trivial copy assignment operator 16658 // cannot be a member of a union, nor can an array of such 16659 // objects. 16660 if (CheckNontrivialField(NewFD)) 16661 NewFD->setInvalidDecl(); 16662 } 16663 } 16664 16665 // C++ [class.union]p1: If a union contains a member of reference type, 16666 // the program is ill-formed, except when compiling with MSVC extensions 16667 // enabled. 16668 if (EltTy->isReferenceType()) { 16669 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 16670 diag::ext_union_member_of_reference_type : 16671 diag::err_union_member_of_reference_type) 16672 << NewFD->getDeclName() << EltTy; 16673 if (!getLangOpts().MicrosoftExt) 16674 NewFD->setInvalidDecl(); 16675 } 16676 } 16677 } 16678 16679 // FIXME: We need to pass in the attributes given an AST 16680 // representation, not a parser representation. 16681 if (D) { 16682 // FIXME: The current scope is almost... but not entirely... correct here. 16683 ProcessDeclAttributes(getCurScope(), NewFD, *D); 16684 16685 if (NewFD->hasAttrs()) 16686 CheckAlignasUnderalignment(NewFD); 16687 } 16688 16689 // In auto-retain/release, infer strong retension for fields of 16690 // retainable type. 16691 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 16692 NewFD->setInvalidDecl(); 16693 16694 if (T.isObjCGCWeak()) 16695 Diag(Loc, diag::warn_attribute_weak_on_field); 16696 16697 NewFD->setAccess(AS); 16698 return NewFD; 16699 } 16700 16701 bool Sema::CheckNontrivialField(FieldDecl *FD) { 16702 assert(FD); 16703 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 16704 16705 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 16706 return false; 16707 16708 QualType EltTy = Context.getBaseElementType(FD->getType()); 16709 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 16710 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 16711 if (RDecl->getDefinition()) { 16712 // We check for copy constructors before constructors 16713 // because otherwise we'll never get complaints about 16714 // copy constructors. 16715 16716 CXXSpecialMember member = CXXInvalid; 16717 // We're required to check for any non-trivial constructors. Since the 16718 // implicit default constructor is suppressed if there are any 16719 // user-declared constructors, we just need to check that there is a 16720 // trivial default constructor and a trivial copy constructor. (We don't 16721 // worry about move constructors here, since this is a C++98 check.) 16722 if (RDecl->hasNonTrivialCopyConstructor()) 16723 member = CXXCopyConstructor; 16724 else if (!RDecl->hasTrivialDefaultConstructor()) 16725 member = CXXDefaultConstructor; 16726 else if (RDecl->hasNonTrivialCopyAssignment()) 16727 member = CXXCopyAssignment; 16728 else if (RDecl->hasNonTrivialDestructor()) 16729 member = CXXDestructor; 16730 16731 if (member != CXXInvalid) { 16732 if (!getLangOpts().CPlusPlus11 && 16733 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 16734 // Objective-C++ ARC: it is an error to have a non-trivial field of 16735 // a union. However, system headers in Objective-C programs 16736 // occasionally have Objective-C lifetime objects within unions, 16737 // and rather than cause the program to fail, we make those 16738 // members unavailable. 16739 SourceLocation Loc = FD->getLocation(); 16740 if (getSourceManager().isInSystemHeader(Loc)) { 16741 if (!FD->hasAttr<UnavailableAttr>()) 16742 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 16743 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 16744 return false; 16745 } 16746 } 16747 16748 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 16749 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 16750 diag::err_illegal_union_or_anon_struct_member) 16751 << FD->getParent()->isUnion() << FD->getDeclName() << member; 16752 DiagnoseNontrivial(RDecl, member); 16753 return !getLangOpts().CPlusPlus11; 16754 } 16755 } 16756 } 16757 16758 return false; 16759 } 16760 16761 /// TranslateIvarVisibility - Translate visibility from a token ID to an 16762 /// AST enum value. 16763 static ObjCIvarDecl::AccessControl 16764 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 16765 switch (ivarVisibility) { 16766 default: llvm_unreachable("Unknown visitibility kind"); 16767 case tok::objc_private: return ObjCIvarDecl::Private; 16768 case tok::objc_public: return ObjCIvarDecl::Public; 16769 case tok::objc_protected: return ObjCIvarDecl::Protected; 16770 case tok::objc_package: return ObjCIvarDecl::Package; 16771 } 16772 } 16773 16774 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 16775 /// in order to create an IvarDecl object for it. 16776 Decl *Sema::ActOnIvar(Scope *S, 16777 SourceLocation DeclStart, 16778 Declarator &D, Expr *BitfieldWidth, 16779 tok::ObjCKeywordKind Visibility) { 16780 16781 IdentifierInfo *II = D.getIdentifier(); 16782 Expr *BitWidth = (Expr*)BitfieldWidth; 16783 SourceLocation Loc = DeclStart; 16784 if (II) Loc = D.getIdentifierLoc(); 16785 16786 // FIXME: Unnamed fields can be handled in various different ways, for 16787 // example, unnamed unions inject all members into the struct namespace! 16788 16789 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16790 QualType T = TInfo->getType(); 16791 16792 if (BitWidth) { 16793 // 6.7.2.1p3, 6.7.2.1p4 16794 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 16795 if (!BitWidth) 16796 D.setInvalidType(); 16797 } else { 16798 // Not a bitfield. 16799 16800 // validate II. 16801 16802 } 16803 if (T->isReferenceType()) { 16804 Diag(Loc, diag::err_ivar_reference_type); 16805 D.setInvalidType(); 16806 } 16807 // C99 6.7.2.1p8: A member of a structure or union may have any type other 16808 // than a variably modified type. 16809 else if (T->isVariablyModifiedType()) { 16810 Diag(Loc, diag::err_typecheck_ivar_variable_size); 16811 D.setInvalidType(); 16812 } 16813 16814 // Get the visibility (access control) for this ivar. 16815 ObjCIvarDecl::AccessControl ac = 16816 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 16817 : ObjCIvarDecl::None; 16818 // Must set ivar's DeclContext to its enclosing interface. 16819 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 16820 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 16821 return nullptr; 16822 ObjCContainerDecl *EnclosingContext; 16823 if (ObjCImplementationDecl *IMPDecl = 16824 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 16825 if (LangOpts.ObjCRuntime.isFragile()) { 16826 // Case of ivar declared in an implementation. Context is that of its class. 16827 EnclosingContext = IMPDecl->getClassInterface(); 16828 assert(EnclosingContext && "Implementation has no class interface!"); 16829 } 16830 else 16831 EnclosingContext = EnclosingDecl; 16832 } else { 16833 if (ObjCCategoryDecl *CDecl = 16834 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 16835 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 16836 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 16837 return nullptr; 16838 } 16839 } 16840 EnclosingContext = EnclosingDecl; 16841 } 16842 16843 // Construct the decl. 16844 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 16845 DeclStart, Loc, II, T, 16846 TInfo, ac, (Expr *)BitfieldWidth); 16847 16848 if (II) { 16849 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 16850 ForVisibleRedeclaration); 16851 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 16852 && !isa<TagDecl>(PrevDecl)) { 16853 Diag(Loc, diag::err_duplicate_member) << II; 16854 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 16855 NewID->setInvalidDecl(); 16856 } 16857 } 16858 16859 // Process attributes attached to the ivar. 16860 ProcessDeclAttributes(S, NewID, D); 16861 16862 if (D.isInvalidType()) 16863 NewID->setInvalidDecl(); 16864 16865 // In ARC, infer 'retaining' for ivars of retainable type. 16866 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 16867 NewID->setInvalidDecl(); 16868 16869 if (D.getDeclSpec().isModulePrivateSpecified()) 16870 NewID->setModulePrivate(); 16871 16872 if (II) { 16873 // FIXME: When interfaces are DeclContexts, we'll need to add 16874 // these to the interface. 16875 S->AddDecl(NewID); 16876 IdResolver.AddDecl(NewID); 16877 } 16878 16879 if (LangOpts.ObjCRuntime.isNonFragile() && 16880 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 16881 Diag(Loc, diag::warn_ivars_in_interface); 16882 16883 return NewID; 16884 } 16885 16886 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 16887 /// class and class extensions. For every class \@interface and class 16888 /// extension \@interface, if the last ivar is a bitfield of any type, 16889 /// then add an implicit `char :0` ivar to the end of that interface. 16890 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 16891 SmallVectorImpl<Decl *> &AllIvarDecls) { 16892 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 16893 return; 16894 16895 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 16896 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 16897 16898 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) 16899 return; 16900 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 16901 if (!ID) { 16902 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 16903 if (!CD->IsClassExtension()) 16904 return; 16905 } 16906 // No need to add this to end of @implementation. 16907 else 16908 return; 16909 } 16910 // All conditions are met. Add a new bitfield to the tail end of ivars. 16911 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 16912 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 16913 16914 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 16915 DeclLoc, DeclLoc, nullptr, 16916 Context.CharTy, 16917 Context.getTrivialTypeSourceInfo(Context.CharTy, 16918 DeclLoc), 16919 ObjCIvarDecl::Private, BW, 16920 true); 16921 AllIvarDecls.push_back(Ivar); 16922 } 16923 16924 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 16925 ArrayRef<Decl *> Fields, SourceLocation LBrac, 16926 SourceLocation RBrac, 16927 const ParsedAttributesView &Attrs) { 16928 assert(EnclosingDecl && "missing record or interface decl"); 16929 16930 // If this is an Objective-C @implementation or category and we have 16931 // new fields here we should reset the layout of the interface since 16932 // it will now change. 16933 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 16934 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 16935 switch (DC->getKind()) { 16936 default: break; 16937 case Decl::ObjCCategory: 16938 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 16939 break; 16940 case Decl::ObjCImplementation: 16941 Context. 16942 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 16943 break; 16944 } 16945 } 16946 16947 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 16948 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl); 16949 16950 // Start counting up the number of named members; make sure to include 16951 // members of anonymous structs and unions in the total. 16952 unsigned NumNamedMembers = 0; 16953 if (Record) { 16954 for (const auto *I : Record->decls()) { 16955 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 16956 if (IFD->getDeclName()) 16957 ++NumNamedMembers; 16958 } 16959 } 16960 16961 // Verify that all the fields are okay. 16962 SmallVector<FieldDecl*, 32> RecFields; 16963 16964 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 16965 i != end; ++i) { 16966 FieldDecl *FD = cast<FieldDecl>(*i); 16967 16968 // Get the type for the field. 16969 const Type *FDTy = FD->getType().getTypePtr(); 16970 16971 if (!FD->isAnonymousStructOrUnion()) { 16972 // Remember all fields written by the user. 16973 RecFields.push_back(FD); 16974 } 16975 16976 // If the field is already invalid for some reason, don't emit more 16977 // diagnostics about it. 16978 if (FD->isInvalidDecl()) { 16979 EnclosingDecl->setInvalidDecl(); 16980 continue; 16981 } 16982 16983 // C99 6.7.2.1p2: 16984 // A structure or union shall not contain a member with 16985 // incomplete or function type (hence, a structure shall not 16986 // contain an instance of itself, but may contain a pointer to 16987 // an instance of itself), except that the last member of a 16988 // structure with more than one named member may have incomplete 16989 // array type; such a structure (and any union containing, 16990 // possibly recursively, a member that is such a structure) 16991 // shall not be a member of a structure or an element of an 16992 // array. 16993 bool IsLastField = (i + 1 == Fields.end()); 16994 if (FDTy->isFunctionType()) { 16995 // Field declared as a function. 16996 Diag(FD->getLocation(), diag::err_field_declared_as_function) 16997 << FD->getDeclName(); 16998 FD->setInvalidDecl(); 16999 EnclosingDecl->setInvalidDecl(); 17000 continue; 17001 } else if (FDTy->isIncompleteArrayType() && 17002 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { 17003 if (Record) { 17004 // Flexible array member. 17005 // Microsoft and g++ is more permissive regarding flexible array. 17006 // It will accept flexible array in union and also 17007 // as the sole element of a struct/class. 17008 unsigned DiagID = 0; 17009 if (!Record->isUnion() && !IsLastField) { 17010 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) 17011 << FD->getDeclName() << FD->getType() << Record->getTagKind(); 17012 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); 17013 FD->setInvalidDecl(); 17014 EnclosingDecl->setInvalidDecl(); 17015 continue; 17016 } else if (Record->isUnion()) 17017 DiagID = getLangOpts().MicrosoftExt 17018 ? diag::ext_flexible_array_union_ms 17019 : getLangOpts().CPlusPlus 17020 ? diag::ext_flexible_array_union_gnu 17021 : diag::err_flexible_array_union; 17022 else if (NumNamedMembers < 1) 17023 DiagID = getLangOpts().MicrosoftExt 17024 ? diag::ext_flexible_array_empty_aggregate_ms 17025 : getLangOpts().CPlusPlus 17026 ? diag::ext_flexible_array_empty_aggregate_gnu 17027 : diag::err_flexible_array_empty_aggregate; 17028 17029 if (DiagID) 17030 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 17031 << Record->getTagKind(); 17032 // While the layout of types that contain virtual bases is not specified 17033 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 17034 // virtual bases after the derived members. This would make a flexible 17035 // array member declared at the end of an object not adjacent to the end 17036 // of the type. 17037 if (CXXRecord && CXXRecord->getNumVBases() != 0) 17038 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 17039 << FD->getDeclName() << Record->getTagKind(); 17040 if (!getLangOpts().C99) 17041 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 17042 << FD->getDeclName() << Record->getTagKind(); 17043 17044 // If the element type has a non-trivial destructor, we would not 17045 // implicitly destroy the elements, so disallow it for now. 17046 // 17047 // FIXME: GCC allows this. We should probably either implicitly delete 17048 // the destructor of the containing class, or just allow this. 17049 QualType BaseElem = Context.getBaseElementType(FD->getType()); 17050 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 17051 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 17052 << FD->getDeclName() << FD->getType(); 17053 FD->setInvalidDecl(); 17054 EnclosingDecl->setInvalidDecl(); 17055 continue; 17056 } 17057 // Okay, we have a legal flexible array member at the end of the struct. 17058 Record->setHasFlexibleArrayMember(true); 17059 } else { 17060 // In ObjCContainerDecl ivars with incomplete array type are accepted, 17061 // unless they are followed by another ivar. That check is done 17062 // elsewhere, after synthesized ivars are known. 17063 } 17064 } else if (!FDTy->isDependentType() && 17065 RequireCompleteSizedType( 17066 FD->getLocation(), FD->getType(), 17067 diag::err_field_incomplete_or_sizeless)) { 17068 // Incomplete type 17069 FD->setInvalidDecl(); 17070 EnclosingDecl->setInvalidDecl(); 17071 continue; 17072 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 17073 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 17074 // A type which contains a flexible array member is considered to be a 17075 // flexible array member. 17076 Record->setHasFlexibleArrayMember(true); 17077 if (!Record->isUnion()) { 17078 // If this is a struct/class and this is not the last element, reject 17079 // it. Note that GCC supports variable sized arrays in the middle of 17080 // structures. 17081 if (!IsLastField) 17082 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 17083 << FD->getDeclName() << FD->getType(); 17084 else { 17085 // We support flexible arrays at the end of structs in 17086 // other structs as an extension. 17087 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 17088 << FD->getDeclName(); 17089 } 17090 } 17091 } 17092 if (isa<ObjCContainerDecl>(EnclosingDecl) && 17093 RequireNonAbstractType(FD->getLocation(), FD->getType(), 17094 diag::err_abstract_type_in_decl, 17095 AbstractIvarType)) { 17096 // Ivars can not have abstract class types 17097 FD->setInvalidDecl(); 17098 } 17099 if (Record && FDTTy->getDecl()->hasObjectMember()) 17100 Record->setHasObjectMember(true); 17101 if (Record && FDTTy->getDecl()->hasVolatileMember()) 17102 Record->setHasVolatileMember(true); 17103 } else if (FDTy->isObjCObjectType()) { 17104 /// A field cannot be an Objective-c object 17105 Diag(FD->getLocation(), diag::err_statically_allocated_object) 17106 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 17107 QualType T = Context.getObjCObjectPointerType(FD->getType()); 17108 FD->setType(T); 17109 } else if (Record && Record->isUnion() && 17110 FD->getType().hasNonTrivialObjCLifetime() && 17111 getSourceManager().isInSystemHeader(FD->getLocation()) && 17112 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() && 17113 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong || 17114 !Context.hasDirectOwnershipQualifier(FD->getType()))) { 17115 // For backward compatibility, fields of C unions declared in system 17116 // headers that have non-trivial ObjC ownership qualifications are marked 17117 // as unavailable unless the qualifier is explicit and __strong. This can 17118 // break ABI compatibility between programs compiled with ARC and MRR, but 17119 // is a better option than rejecting programs using those unions under 17120 // ARC. 17121 FD->addAttr(UnavailableAttr::CreateImplicit( 17122 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, 17123 FD->getLocation())); 17124 } else if (getLangOpts().ObjC && 17125 getLangOpts().getGC() != LangOptions::NonGC && Record && 17126 !Record->hasObjectMember()) { 17127 if (FD->getType()->isObjCObjectPointerType() || 17128 FD->getType().isObjCGCStrong()) 17129 Record->setHasObjectMember(true); 17130 else if (Context.getAsArrayType(FD->getType())) { 17131 QualType BaseType = Context.getBaseElementType(FD->getType()); 17132 if (BaseType->isRecordType() && 17133 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember()) 17134 Record->setHasObjectMember(true); 17135 else if (BaseType->isObjCObjectPointerType() || 17136 BaseType.isObjCGCStrong()) 17137 Record->setHasObjectMember(true); 17138 } 17139 } 17140 17141 if (Record && !getLangOpts().CPlusPlus && 17142 !shouldIgnoreForRecordTriviality(FD)) { 17143 QualType FT = FD->getType(); 17144 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) { 17145 Record->setNonTrivialToPrimitiveDefaultInitialize(true); 17146 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 17147 Record->isUnion()) 17148 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true); 17149 } 17150 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); 17151 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) { 17152 Record->setNonTrivialToPrimitiveCopy(true); 17153 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion()) 17154 Record->setHasNonTrivialToPrimitiveCopyCUnion(true); 17155 } 17156 if (FT.isDestructedType()) { 17157 Record->setNonTrivialToPrimitiveDestroy(true); 17158 Record->setParamDestroyedInCallee(true); 17159 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion()) 17160 Record->setHasNonTrivialToPrimitiveDestructCUnion(true); 17161 } 17162 17163 if (const auto *RT = FT->getAs<RecordType>()) { 17164 if (RT->getDecl()->getArgPassingRestrictions() == 17165 RecordDecl::APK_CanNeverPassInRegs) 17166 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17167 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) 17168 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 17169 } 17170 17171 if (Record && FD->getType().isVolatileQualified()) 17172 Record->setHasVolatileMember(true); 17173 // Keep track of the number of named members. 17174 if (FD->getIdentifier()) 17175 ++NumNamedMembers; 17176 } 17177 17178 // Okay, we successfully defined 'Record'. 17179 if (Record) { 17180 bool Completed = false; 17181 if (CXXRecord) { 17182 if (!CXXRecord->isInvalidDecl()) { 17183 // Set access bits correctly on the directly-declared conversions. 17184 for (CXXRecordDecl::conversion_iterator 17185 I = CXXRecord->conversion_begin(), 17186 E = CXXRecord->conversion_end(); I != E; ++I) 17187 I.setAccess((*I)->getAccess()); 17188 } 17189 17190 // Add any implicitly-declared members to this class. 17191 AddImplicitlyDeclaredMembersToClass(CXXRecord); 17192 17193 if (!CXXRecord->isDependentType()) { 17194 if (!CXXRecord->isInvalidDecl()) { 17195 // If we have virtual base classes, we may end up finding multiple 17196 // final overriders for a given virtual function. Check for this 17197 // problem now. 17198 if (CXXRecord->getNumVBases()) { 17199 CXXFinalOverriderMap FinalOverriders; 17200 CXXRecord->getFinalOverriders(FinalOverriders); 17201 17202 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 17203 MEnd = FinalOverriders.end(); 17204 M != MEnd; ++M) { 17205 for (OverridingMethods::iterator SO = M->second.begin(), 17206 SOEnd = M->second.end(); 17207 SO != SOEnd; ++SO) { 17208 assert(SO->second.size() > 0 && 17209 "Virtual function without overriding functions?"); 17210 if (SO->second.size() == 1) 17211 continue; 17212 17213 // C++ [class.virtual]p2: 17214 // In a derived class, if a virtual member function of a base 17215 // class subobject has more than one final overrider the 17216 // program is ill-formed. 17217 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 17218 << (const NamedDecl *)M->first << Record; 17219 Diag(M->first->getLocation(), 17220 diag::note_overridden_virtual_function); 17221 for (OverridingMethods::overriding_iterator 17222 OM = SO->second.begin(), 17223 OMEnd = SO->second.end(); 17224 OM != OMEnd; ++OM) 17225 Diag(OM->Method->getLocation(), diag::note_final_overrider) 17226 << (const NamedDecl *)M->first << OM->Method->getParent(); 17227 17228 Record->setInvalidDecl(); 17229 } 17230 } 17231 CXXRecord->completeDefinition(&FinalOverriders); 17232 Completed = true; 17233 } 17234 } 17235 } 17236 } 17237 17238 if (!Completed) 17239 Record->completeDefinition(); 17240 17241 // Handle attributes before checking the layout. 17242 ProcessDeclAttributeList(S, Record, Attrs); 17243 17244 // We may have deferred checking for a deleted destructor. Check now. 17245 if (CXXRecord) { 17246 auto *Dtor = CXXRecord->getDestructor(); 17247 if (Dtor && Dtor->isImplicit() && 17248 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { 17249 CXXRecord->setImplicitDestructorIsDeleted(); 17250 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 17251 } 17252 } 17253 17254 if (Record->hasAttrs()) { 17255 CheckAlignasUnderalignment(Record); 17256 17257 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 17258 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 17259 IA->getRange(), IA->getBestCase(), 17260 IA->getInheritanceModel()); 17261 } 17262 17263 // Check if the structure/union declaration is a type that can have zero 17264 // size in C. For C this is a language extension, for C++ it may cause 17265 // compatibility problems. 17266 bool CheckForZeroSize; 17267 if (!getLangOpts().CPlusPlus) { 17268 CheckForZeroSize = true; 17269 } else { 17270 // For C++ filter out types that cannot be referenced in C code. 17271 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 17272 CheckForZeroSize = 17273 CXXRecord->getLexicalDeclContext()->isExternCContext() && 17274 !CXXRecord->isDependentType() && 17275 CXXRecord->isCLike(); 17276 } 17277 if (CheckForZeroSize) { 17278 bool ZeroSize = true; 17279 bool IsEmpty = true; 17280 unsigned NonBitFields = 0; 17281 for (RecordDecl::field_iterator I = Record->field_begin(), 17282 E = Record->field_end(); 17283 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 17284 IsEmpty = false; 17285 if (I->isUnnamedBitfield()) { 17286 if (!I->isZeroLengthBitField(Context)) 17287 ZeroSize = false; 17288 } else { 17289 ++NonBitFields; 17290 QualType FieldType = I->getType(); 17291 if (FieldType->isIncompleteType() || 17292 !Context.getTypeSizeInChars(FieldType).isZero()) 17293 ZeroSize = false; 17294 } 17295 } 17296 17297 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 17298 // allowed in C++, but warn if its declaration is inside 17299 // extern "C" block. 17300 if (ZeroSize) { 17301 Diag(RecLoc, getLangOpts().CPlusPlus ? 17302 diag::warn_zero_size_struct_union_in_extern_c : 17303 diag::warn_zero_size_struct_union_compat) 17304 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 17305 } 17306 17307 // Structs without named members are extension in C (C99 6.7.2.1p7), 17308 // but are accepted by GCC. 17309 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 17310 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 17311 diag::ext_no_named_members_in_struct_union) 17312 << Record->isUnion(); 17313 } 17314 } 17315 } else { 17316 ObjCIvarDecl **ClsFields = 17317 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 17318 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 17319 ID->setEndOfDefinitionLoc(RBrac); 17320 // Add ivar's to class's DeclContext. 17321 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17322 ClsFields[i]->setLexicalDeclContext(ID); 17323 ID->addDecl(ClsFields[i]); 17324 } 17325 // Must enforce the rule that ivars in the base classes may not be 17326 // duplicates. 17327 if (ID->getSuperClass()) 17328 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 17329 } else if (ObjCImplementationDecl *IMPDecl = 17330 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 17331 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 17332 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 17333 // Ivar declared in @implementation never belongs to the implementation. 17334 // Only it is in implementation's lexical context. 17335 ClsFields[I]->setLexicalDeclContext(IMPDecl); 17336 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 17337 IMPDecl->setIvarLBraceLoc(LBrac); 17338 IMPDecl->setIvarRBraceLoc(RBrac); 17339 } else if (ObjCCategoryDecl *CDecl = 17340 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 17341 // case of ivars in class extension; all other cases have been 17342 // reported as errors elsewhere. 17343 // FIXME. Class extension does not have a LocEnd field. 17344 // CDecl->setLocEnd(RBrac); 17345 // Add ivar's to class extension's DeclContext. 17346 // Diagnose redeclaration of private ivars. 17347 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 17348 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17349 if (IDecl) { 17350 if (const ObjCIvarDecl *ClsIvar = 17351 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 17352 Diag(ClsFields[i]->getLocation(), 17353 diag::err_duplicate_ivar_declaration); 17354 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 17355 continue; 17356 } 17357 for (const auto *Ext : IDecl->known_extensions()) { 17358 if (const ObjCIvarDecl *ClsExtIvar 17359 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 17360 Diag(ClsFields[i]->getLocation(), 17361 diag::err_duplicate_ivar_declaration); 17362 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 17363 continue; 17364 } 17365 } 17366 } 17367 ClsFields[i]->setLexicalDeclContext(CDecl); 17368 CDecl->addDecl(ClsFields[i]); 17369 } 17370 CDecl->setIvarLBraceLoc(LBrac); 17371 CDecl->setIvarRBraceLoc(RBrac); 17372 } 17373 } 17374 } 17375 17376 /// Determine whether the given integral value is representable within 17377 /// the given type T. 17378 static bool isRepresentableIntegerValue(ASTContext &Context, 17379 llvm::APSInt &Value, 17380 QualType T) { 17381 assert((T->isIntegralType(Context) || T->isEnumeralType()) && 17382 "Integral type required!"); 17383 unsigned BitWidth = Context.getIntWidth(T); 17384 17385 if (Value.isUnsigned() || Value.isNonNegative()) { 17386 if (T->isSignedIntegerOrEnumerationType()) 17387 --BitWidth; 17388 return Value.getActiveBits() <= BitWidth; 17389 } 17390 return Value.getMinSignedBits() <= BitWidth; 17391 } 17392 17393 // Given an integral type, return the next larger integral type 17394 // (or a NULL type of no such type exists). 17395 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 17396 // FIXME: Int128/UInt128 support, which also needs to be introduced into 17397 // enum checking below. 17398 assert((T->isIntegralType(Context) || 17399 T->isEnumeralType()) && "Integral type required!"); 17400 const unsigned NumTypes = 4; 17401 QualType SignedIntegralTypes[NumTypes] = { 17402 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 17403 }; 17404 QualType UnsignedIntegralTypes[NumTypes] = { 17405 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 17406 Context.UnsignedLongLongTy 17407 }; 17408 17409 unsigned BitWidth = Context.getTypeSize(T); 17410 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 17411 : UnsignedIntegralTypes; 17412 for (unsigned I = 0; I != NumTypes; ++I) 17413 if (Context.getTypeSize(Types[I]) > BitWidth) 17414 return Types[I]; 17415 17416 return QualType(); 17417 } 17418 17419 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 17420 EnumConstantDecl *LastEnumConst, 17421 SourceLocation IdLoc, 17422 IdentifierInfo *Id, 17423 Expr *Val) { 17424 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 17425 llvm::APSInt EnumVal(IntWidth); 17426 QualType EltTy; 17427 17428 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 17429 Val = nullptr; 17430 17431 if (Val) 17432 Val = DefaultLvalueConversion(Val).get(); 17433 17434 if (Val) { 17435 if (Enum->isDependentType() || Val->isTypeDependent()) 17436 EltTy = Context.DependentTy; 17437 else { 17438 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) { 17439 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 17440 // constant-expression in the enumerator-definition shall be a converted 17441 // constant expression of the underlying type. 17442 EltTy = Enum->getIntegerType(); 17443 ExprResult Converted = 17444 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 17445 CCEK_Enumerator); 17446 if (Converted.isInvalid()) 17447 Val = nullptr; 17448 else 17449 Val = Converted.get(); 17450 } else if (!Val->isValueDependent() && 17451 !(Val = VerifyIntegerConstantExpression(Val, 17452 &EnumVal).get())) { 17453 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 17454 } else { 17455 if (Enum->isComplete()) { 17456 EltTy = Enum->getIntegerType(); 17457 17458 // In Obj-C and Microsoft mode, require the enumeration value to be 17459 // representable in the underlying type of the enumeration. In C++11, 17460 // we perform a non-narrowing conversion as part of converted constant 17461 // expression checking. 17462 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 17463 if (Context.getTargetInfo() 17464 .getTriple() 17465 .isWindowsMSVCEnvironment()) { 17466 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 17467 } else { 17468 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 17469 } 17470 } 17471 17472 // Cast to the underlying type. 17473 Val = ImpCastExprToType(Val, EltTy, 17474 EltTy->isBooleanType() ? CK_IntegralToBoolean 17475 : CK_IntegralCast) 17476 .get(); 17477 } else if (getLangOpts().CPlusPlus) { 17478 // C++11 [dcl.enum]p5: 17479 // If the underlying type is not fixed, the type of each enumerator 17480 // is the type of its initializing value: 17481 // - If an initializer is specified for an enumerator, the 17482 // initializing value has the same type as the expression. 17483 EltTy = Val->getType(); 17484 } else { 17485 // C99 6.7.2.2p2: 17486 // The expression that defines the value of an enumeration constant 17487 // shall be an integer constant expression that has a value 17488 // representable as an int. 17489 17490 // Complain if the value is not representable in an int. 17491 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 17492 Diag(IdLoc, diag::ext_enum_value_not_int) 17493 << EnumVal.toString(10) << Val->getSourceRange() 17494 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 17495 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 17496 // Force the type of the expression to 'int'. 17497 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 17498 } 17499 EltTy = Val->getType(); 17500 } 17501 } 17502 } 17503 } 17504 17505 if (!Val) { 17506 if (Enum->isDependentType()) 17507 EltTy = Context.DependentTy; 17508 else if (!LastEnumConst) { 17509 // C++0x [dcl.enum]p5: 17510 // If the underlying type is not fixed, the type of each enumerator 17511 // is the type of its initializing value: 17512 // - If no initializer is specified for the first enumerator, the 17513 // initializing value has an unspecified integral type. 17514 // 17515 // GCC uses 'int' for its unspecified integral type, as does 17516 // C99 6.7.2.2p3. 17517 if (Enum->isFixed()) { 17518 EltTy = Enum->getIntegerType(); 17519 } 17520 else { 17521 EltTy = Context.IntTy; 17522 } 17523 } else { 17524 // Assign the last value + 1. 17525 EnumVal = LastEnumConst->getInitVal(); 17526 ++EnumVal; 17527 EltTy = LastEnumConst->getType(); 17528 17529 // Check for overflow on increment. 17530 if (EnumVal < LastEnumConst->getInitVal()) { 17531 // C++0x [dcl.enum]p5: 17532 // If the underlying type is not fixed, the type of each enumerator 17533 // is the type of its initializing value: 17534 // 17535 // - Otherwise the type of the initializing value is the same as 17536 // the type of the initializing value of the preceding enumerator 17537 // unless the incremented value is not representable in that type, 17538 // in which case the type is an unspecified integral type 17539 // sufficient to contain the incremented value. If no such type 17540 // exists, the program is ill-formed. 17541 QualType T = getNextLargerIntegralType(Context, EltTy); 17542 if (T.isNull() || Enum->isFixed()) { 17543 // There is no integral type larger enough to represent this 17544 // value. Complain, then allow the value to wrap around. 17545 EnumVal = LastEnumConst->getInitVal(); 17546 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 17547 ++EnumVal; 17548 if (Enum->isFixed()) 17549 // When the underlying type is fixed, this is ill-formed. 17550 Diag(IdLoc, diag::err_enumerator_wrapped) 17551 << EnumVal.toString(10) 17552 << EltTy; 17553 else 17554 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 17555 << EnumVal.toString(10); 17556 } else { 17557 EltTy = T; 17558 } 17559 17560 // Retrieve the last enumerator's value, extent that type to the 17561 // type that is supposed to be large enough to represent the incremented 17562 // value, then increment. 17563 EnumVal = LastEnumConst->getInitVal(); 17564 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 17565 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 17566 ++EnumVal; 17567 17568 // If we're not in C++, diagnose the overflow of enumerator values, 17569 // which in C99 means that the enumerator value is not representable in 17570 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 17571 // permits enumerator values that are representable in some larger 17572 // integral type. 17573 if (!getLangOpts().CPlusPlus && !T.isNull()) 17574 Diag(IdLoc, diag::warn_enum_value_overflow); 17575 } else if (!getLangOpts().CPlusPlus && 17576 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 17577 // Enforce C99 6.7.2.2p2 even when we compute the next value. 17578 Diag(IdLoc, diag::ext_enum_value_not_int) 17579 << EnumVal.toString(10) << 1; 17580 } 17581 } 17582 } 17583 17584 if (!EltTy->isDependentType()) { 17585 // Make the enumerator value match the signedness and size of the 17586 // enumerator's type. 17587 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 17588 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 17589 } 17590 17591 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 17592 Val, EnumVal); 17593 } 17594 17595 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 17596 SourceLocation IILoc) { 17597 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 17598 !getLangOpts().CPlusPlus) 17599 return SkipBodyInfo(); 17600 17601 // We have an anonymous enum definition. Look up the first enumerator to 17602 // determine if we should merge the definition with an existing one and 17603 // skip the body. 17604 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 17605 forRedeclarationInCurContext()); 17606 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 17607 if (!PrevECD) 17608 return SkipBodyInfo(); 17609 17610 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 17611 NamedDecl *Hidden; 17612 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 17613 SkipBodyInfo Skip; 17614 Skip.Previous = Hidden; 17615 return Skip; 17616 } 17617 17618 return SkipBodyInfo(); 17619 } 17620 17621 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 17622 SourceLocation IdLoc, IdentifierInfo *Id, 17623 const ParsedAttributesView &Attrs, 17624 SourceLocation EqualLoc, Expr *Val) { 17625 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 17626 EnumConstantDecl *LastEnumConst = 17627 cast_or_null<EnumConstantDecl>(lastEnumConst); 17628 17629 // The scope passed in may not be a decl scope. Zip up the scope tree until 17630 // we find one that is. 17631 S = getNonFieldDeclScope(S); 17632 17633 // Verify that there isn't already something declared with this name in this 17634 // scope. 17635 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration); 17636 LookupName(R, S); 17637 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>(); 17638 17639 if (PrevDecl && PrevDecl->isTemplateParameter()) { 17640 // Maybe we will complain about the shadowed template parameter. 17641 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 17642 // Just pretend that we didn't see the previous declaration. 17643 PrevDecl = nullptr; 17644 } 17645 17646 // C++ [class.mem]p15: 17647 // If T is the name of a class, then each of the following shall have a name 17648 // different from T: 17649 // - every enumerator of every member of class T that is an unscoped 17650 // enumerated type 17651 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) 17652 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 17653 DeclarationNameInfo(Id, IdLoc)); 17654 17655 EnumConstantDecl *New = 17656 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 17657 if (!New) 17658 return nullptr; 17659 17660 if (PrevDecl) { 17661 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) { 17662 // Check for other kinds of shadowing not already handled. 17663 CheckShadow(New, PrevDecl, R); 17664 } 17665 17666 // When in C++, we may get a TagDecl with the same name; in this case the 17667 // enum constant will 'hide' the tag. 17668 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 17669 "Received TagDecl when not in C++!"); 17670 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 17671 if (isa<EnumConstantDecl>(PrevDecl)) 17672 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 17673 else 17674 Diag(IdLoc, diag::err_redefinition) << Id; 17675 notePreviousDefinition(PrevDecl, IdLoc); 17676 return nullptr; 17677 } 17678 } 17679 17680 // Process attributes. 17681 ProcessDeclAttributeList(S, New, Attrs); 17682 AddPragmaAttributes(S, New); 17683 17684 // Register this decl in the current scope stack. 17685 New->setAccess(TheEnumDecl->getAccess()); 17686 PushOnScopeChains(New, S); 17687 17688 ActOnDocumentableDecl(New); 17689 17690 return New; 17691 } 17692 17693 // Returns true when the enum initial expression does not trigger the 17694 // duplicate enum warning. A few common cases are exempted as follows: 17695 // Element2 = Element1 17696 // Element2 = Element1 + 1 17697 // Element2 = Element1 - 1 17698 // Where Element2 and Element1 are from the same enum. 17699 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 17700 Expr *InitExpr = ECD->getInitExpr(); 17701 if (!InitExpr) 17702 return true; 17703 InitExpr = InitExpr->IgnoreImpCasts(); 17704 17705 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 17706 if (!BO->isAdditiveOp()) 17707 return true; 17708 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 17709 if (!IL) 17710 return true; 17711 if (IL->getValue() != 1) 17712 return true; 17713 17714 InitExpr = BO->getLHS(); 17715 } 17716 17717 // This checks if the elements are from the same enum. 17718 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 17719 if (!DRE) 17720 return true; 17721 17722 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 17723 if (!EnumConstant) 17724 return true; 17725 17726 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 17727 Enum) 17728 return true; 17729 17730 return false; 17731 } 17732 17733 // Emits a warning when an element is implicitly set a value that 17734 // a previous element has already been set to. 17735 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 17736 EnumDecl *Enum, QualType EnumType) { 17737 // Avoid anonymous enums 17738 if (!Enum->getIdentifier()) 17739 return; 17740 17741 // Only check for small enums. 17742 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 17743 return; 17744 17745 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 17746 return; 17747 17748 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 17749 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; 17750 17751 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 17752 17753 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map. 17754 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap; 17755 17756 // Use int64_t as a key to avoid needing special handling for map keys. 17757 auto EnumConstantToKey = [](const EnumConstantDecl *D) { 17758 llvm::APSInt Val = D->getInitVal(); 17759 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); 17760 }; 17761 17762 DuplicatesVector DupVector; 17763 ValueToVectorMap EnumMap; 17764 17765 // Populate the EnumMap with all values represented by enum constants without 17766 // an initializer. 17767 for (auto *Element : Elements) { 17768 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); 17769 17770 // Null EnumConstantDecl means a previous diagnostic has been emitted for 17771 // this constant. Skip this enum since it may be ill-formed. 17772 if (!ECD) { 17773 return; 17774 } 17775 17776 // Constants with initalizers are handled in the next loop. 17777 if (ECD->getInitExpr()) 17778 continue; 17779 17780 // Duplicate values are handled in the next loop. 17781 EnumMap.insert({EnumConstantToKey(ECD), ECD}); 17782 } 17783 17784 if (EnumMap.size() == 0) 17785 return; 17786 17787 // Create vectors for any values that has duplicates. 17788 for (auto *Element : Elements) { 17789 // The last loop returned if any constant was null. 17790 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); 17791 if (!ValidDuplicateEnum(ECD, Enum)) 17792 continue; 17793 17794 auto Iter = EnumMap.find(EnumConstantToKey(ECD)); 17795 if (Iter == EnumMap.end()) 17796 continue; 17797 17798 DeclOrVector& Entry = Iter->second; 17799 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 17800 // Ensure constants are different. 17801 if (D == ECD) 17802 continue; 17803 17804 // Create new vector and push values onto it. 17805 auto Vec = std::make_unique<ECDVector>(); 17806 Vec->push_back(D); 17807 Vec->push_back(ECD); 17808 17809 // Update entry to point to the duplicates vector. 17810 Entry = Vec.get(); 17811 17812 // Store the vector somewhere we can consult later for quick emission of 17813 // diagnostics. 17814 DupVector.emplace_back(std::move(Vec)); 17815 continue; 17816 } 17817 17818 ECDVector *Vec = Entry.get<ECDVector*>(); 17819 // Make sure constants are not added more than once. 17820 if (*Vec->begin() == ECD) 17821 continue; 17822 17823 Vec->push_back(ECD); 17824 } 17825 17826 // Emit diagnostics. 17827 for (const auto &Vec : DupVector) { 17828 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 17829 17830 // Emit warning for one enum constant. 17831 auto *FirstECD = Vec->front(); 17832 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) 17833 << FirstECD << FirstECD->getInitVal().toString(10) 17834 << FirstECD->getSourceRange(); 17835 17836 // Emit one note for each of the remaining enum constants with 17837 // the same value. 17838 for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end())) 17839 S.Diag(ECD->getLocation(), diag::note_duplicate_element) 17840 << ECD << ECD->getInitVal().toString(10) 17841 << ECD->getSourceRange(); 17842 } 17843 } 17844 17845 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 17846 bool AllowMask) const { 17847 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 17848 assert(ED->isCompleteDefinition() && "expected enum definition"); 17849 17850 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 17851 llvm::APInt &FlagBits = R.first->second; 17852 17853 if (R.second) { 17854 for (auto *E : ED->enumerators()) { 17855 const auto &EVal = E->getInitVal(); 17856 // Only single-bit enumerators introduce new flag values. 17857 if (EVal.isPowerOf2()) 17858 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 17859 } 17860 } 17861 17862 // A value is in a flag enum if either its bits are a subset of the enum's 17863 // flag bits (the first condition) or we are allowing masks and the same is 17864 // true of its complement (the second condition). When masks are allowed, we 17865 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 17866 // 17867 // While it's true that any value could be used as a mask, the assumption is 17868 // that a mask will have all of the insignificant bits set. Anything else is 17869 // likely a logic error. 17870 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 17871 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 17872 } 17873 17874 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 17875 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S, 17876 const ParsedAttributesView &Attrs) { 17877 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 17878 QualType EnumType = Context.getTypeDeclType(Enum); 17879 17880 ProcessDeclAttributeList(S, Enum, Attrs); 17881 17882 if (Enum->isDependentType()) { 17883 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 17884 EnumConstantDecl *ECD = 17885 cast_or_null<EnumConstantDecl>(Elements[i]); 17886 if (!ECD) continue; 17887 17888 ECD->setType(EnumType); 17889 } 17890 17891 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 17892 return; 17893 } 17894 17895 // TODO: If the result value doesn't fit in an int, it must be a long or long 17896 // long value. ISO C does not support this, but GCC does as an extension, 17897 // emit a warning. 17898 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 17899 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 17900 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 17901 17902 // Verify that all the values are okay, compute the size of the values, and 17903 // reverse the list. 17904 unsigned NumNegativeBits = 0; 17905 unsigned NumPositiveBits = 0; 17906 17907 // Keep track of whether all elements have type int. 17908 bool AllElementsInt = true; 17909 17910 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 17911 EnumConstantDecl *ECD = 17912 cast_or_null<EnumConstantDecl>(Elements[i]); 17913 if (!ECD) continue; // Already issued a diagnostic. 17914 17915 const llvm::APSInt &InitVal = ECD->getInitVal(); 17916 17917 // Keep track of the size of positive and negative values. 17918 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 17919 NumPositiveBits = std::max(NumPositiveBits, 17920 (unsigned)InitVal.getActiveBits()); 17921 else 17922 NumNegativeBits = std::max(NumNegativeBits, 17923 (unsigned)InitVal.getMinSignedBits()); 17924 17925 // Keep track of whether every enum element has type int (very common). 17926 if (AllElementsInt) 17927 AllElementsInt = ECD->getType() == Context.IntTy; 17928 } 17929 17930 // Figure out the type that should be used for this enum. 17931 QualType BestType; 17932 unsigned BestWidth; 17933 17934 // C++0x N3000 [conv.prom]p3: 17935 // An rvalue of an unscoped enumeration type whose underlying 17936 // type is not fixed can be converted to an rvalue of the first 17937 // of the following types that can represent all the values of 17938 // the enumeration: int, unsigned int, long int, unsigned long 17939 // int, long long int, or unsigned long long int. 17940 // C99 6.4.4.3p2: 17941 // An identifier declared as an enumeration constant has type int. 17942 // The C99 rule is modified by a gcc extension 17943 QualType BestPromotionType; 17944 17945 bool Packed = Enum->hasAttr<PackedAttr>(); 17946 // -fshort-enums is the equivalent to specifying the packed attribute on all 17947 // enum definitions. 17948 if (LangOpts.ShortEnums) 17949 Packed = true; 17950 17951 // If the enum already has a type because it is fixed or dictated by the 17952 // target, promote that type instead of analyzing the enumerators. 17953 if (Enum->isComplete()) { 17954 BestType = Enum->getIntegerType(); 17955 if (BestType->isPromotableIntegerType()) 17956 BestPromotionType = Context.getPromotedIntegerType(BestType); 17957 else 17958 BestPromotionType = BestType; 17959 17960 BestWidth = Context.getIntWidth(BestType); 17961 } 17962 else if (NumNegativeBits) { 17963 // If there is a negative value, figure out the smallest integer type (of 17964 // int/long/longlong) that fits. 17965 // If it's packed, check also if it fits a char or a short. 17966 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 17967 BestType = Context.SignedCharTy; 17968 BestWidth = CharWidth; 17969 } else if (Packed && NumNegativeBits <= ShortWidth && 17970 NumPositiveBits < ShortWidth) { 17971 BestType = Context.ShortTy; 17972 BestWidth = ShortWidth; 17973 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 17974 BestType = Context.IntTy; 17975 BestWidth = IntWidth; 17976 } else { 17977 BestWidth = Context.getTargetInfo().getLongWidth(); 17978 17979 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 17980 BestType = Context.LongTy; 17981 } else { 17982 BestWidth = Context.getTargetInfo().getLongLongWidth(); 17983 17984 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 17985 Diag(Enum->getLocation(), diag::ext_enum_too_large); 17986 BestType = Context.LongLongTy; 17987 } 17988 } 17989 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 17990 } else { 17991 // If there is no negative value, figure out the smallest type that fits 17992 // all of the enumerator values. 17993 // If it's packed, check also if it fits a char or a short. 17994 if (Packed && NumPositiveBits <= CharWidth) { 17995 BestType = Context.UnsignedCharTy; 17996 BestPromotionType = Context.IntTy; 17997 BestWidth = CharWidth; 17998 } else if (Packed && NumPositiveBits <= ShortWidth) { 17999 BestType = Context.UnsignedShortTy; 18000 BestPromotionType = Context.IntTy; 18001 BestWidth = ShortWidth; 18002 } else if (NumPositiveBits <= IntWidth) { 18003 BestType = Context.UnsignedIntTy; 18004 BestWidth = IntWidth; 18005 BestPromotionType 18006 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18007 ? Context.UnsignedIntTy : Context.IntTy; 18008 } else if (NumPositiveBits <= 18009 (BestWidth = Context.getTargetInfo().getLongWidth())) { 18010 BestType = Context.UnsignedLongTy; 18011 BestPromotionType 18012 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18013 ? Context.UnsignedLongTy : Context.LongTy; 18014 } else { 18015 BestWidth = Context.getTargetInfo().getLongLongWidth(); 18016 assert(NumPositiveBits <= BestWidth && 18017 "How could an initializer get larger than ULL?"); 18018 BestType = Context.UnsignedLongLongTy; 18019 BestPromotionType 18020 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 18021 ? Context.UnsignedLongLongTy : Context.LongLongTy; 18022 } 18023 } 18024 18025 // Loop over all of the enumerator constants, changing their types to match 18026 // the type of the enum if needed. 18027 for (auto *D : Elements) { 18028 auto *ECD = cast_or_null<EnumConstantDecl>(D); 18029 if (!ECD) continue; // Already issued a diagnostic. 18030 18031 // Standard C says the enumerators have int type, but we allow, as an 18032 // extension, the enumerators to be larger than int size. If each 18033 // enumerator value fits in an int, type it as an int, otherwise type it the 18034 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 18035 // that X has type 'int', not 'unsigned'. 18036 18037 // Determine whether the value fits into an int. 18038 llvm::APSInt InitVal = ECD->getInitVal(); 18039 18040 // If it fits into an integer type, force it. Otherwise force it to match 18041 // the enum decl type. 18042 QualType NewTy; 18043 unsigned NewWidth; 18044 bool NewSign; 18045 if (!getLangOpts().CPlusPlus && 18046 !Enum->isFixed() && 18047 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 18048 NewTy = Context.IntTy; 18049 NewWidth = IntWidth; 18050 NewSign = true; 18051 } else if (ECD->getType() == BestType) { 18052 // Already the right type! 18053 if (getLangOpts().CPlusPlus) 18054 // C++ [dcl.enum]p4: Following the closing brace of an 18055 // enum-specifier, each enumerator has the type of its 18056 // enumeration. 18057 ECD->setType(EnumType); 18058 continue; 18059 } else { 18060 NewTy = BestType; 18061 NewWidth = BestWidth; 18062 NewSign = BestType->isSignedIntegerOrEnumerationType(); 18063 } 18064 18065 // Adjust the APSInt value. 18066 InitVal = InitVal.extOrTrunc(NewWidth); 18067 InitVal.setIsSigned(NewSign); 18068 ECD->setInitVal(InitVal); 18069 18070 // Adjust the Expr initializer and type. 18071 if (ECD->getInitExpr() && 18072 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 18073 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 18074 CK_IntegralCast, 18075 ECD->getInitExpr(), 18076 /*base paths*/ nullptr, 18077 VK_RValue)); 18078 if (getLangOpts().CPlusPlus) 18079 // C++ [dcl.enum]p4: Following the closing brace of an 18080 // enum-specifier, each enumerator has the type of its 18081 // enumeration. 18082 ECD->setType(EnumType); 18083 else 18084 ECD->setType(NewTy); 18085 } 18086 18087 Enum->completeDefinition(BestType, BestPromotionType, 18088 NumPositiveBits, NumNegativeBits); 18089 18090 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 18091 18092 if (Enum->isClosedFlag()) { 18093 for (Decl *D : Elements) { 18094 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 18095 if (!ECD) continue; // Already issued a diagnostic. 18096 18097 llvm::APSInt InitVal = ECD->getInitVal(); 18098 if (InitVal != 0 && !InitVal.isPowerOf2() && 18099 !IsValueInFlagEnum(Enum, InitVal, true)) 18100 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 18101 << ECD << Enum; 18102 } 18103 } 18104 18105 // Now that the enum type is defined, ensure it's not been underaligned. 18106 if (Enum->hasAttrs()) 18107 CheckAlignasUnderalignment(Enum); 18108 } 18109 18110 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 18111 SourceLocation StartLoc, 18112 SourceLocation EndLoc) { 18113 StringLiteral *AsmString = cast<StringLiteral>(expr); 18114 18115 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 18116 AsmString, StartLoc, 18117 EndLoc); 18118 CurContext->addDecl(New); 18119 return New; 18120 } 18121 18122 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 18123 IdentifierInfo* AliasName, 18124 SourceLocation PragmaLoc, 18125 SourceLocation NameLoc, 18126 SourceLocation AliasNameLoc) { 18127 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 18128 LookupOrdinaryName); 18129 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc), 18130 AttributeCommonInfo::AS_Pragma); 18131 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit( 18132 Context, AliasName->getName(), /*LiteralLabel=*/true, Info); 18133 18134 // If a declaration that: 18135 // 1) declares a function or a variable 18136 // 2) has external linkage 18137 // already exists, add a label attribute to it. 18138 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18139 if (isDeclExternC(PrevDecl)) 18140 PrevDecl->addAttr(Attr); 18141 else 18142 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 18143 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 18144 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 18145 } else 18146 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 18147 } 18148 18149 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 18150 SourceLocation PragmaLoc, 18151 SourceLocation NameLoc) { 18152 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 18153 18154 if (PrevDecl) { 18155 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma)); 18156 } else { 18157 (void)WeakUndeclaredIdentifiers.insert( 18158 std::pair<IdentifierInfo*,WeakInfo> 18159 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 18160 } 18161 } 18162 18163 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 18164 IdentifierInfo* AliasName, 18165 SourceLocation PragmaLoc, 18166 SourceLocation NameLoc, 18167 SourceLocation AliasNameLoc) { 18168 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 18169 LookupOrdinaryName); 18170 WeakInfo W = WeakInfo(Name, NameLoc); 18171 18172 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 18173 if (!PrevDecl->hasAttr<AliasAttr>()) 18174 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 18175 DeclApplyPragmaWeak(TUScope, ND, W); 18176 } else { 18177 (void)WeakUndeclaredIdentifiers.insert( 18178 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 18179 } 18180 } 18181 18182 Decl *Sema::getObjCDeclContext() const { 18183 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 18184 } 18185 18186 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD, 18187 bool Final) { 18188 // SYCL functions can be template, so we check if they have appropriate 18189 // attribute prior to checking if it is a template. 18190 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>()) 18191 return FunctionEmissionStatus::Emitted; 18192 18193 // Templates are emitted when they're instantiated. 18194 if (FD->isDependentContext()) 18195 return FunctionEmissionStatus::TemplateDiscarded; 18196 18197 FunctionEmissionStatus OMPES = FunctionEmissionStatus::Unknown; 18198 if (LangOpts.OpenMPIsDevice) { 18199 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18200 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18201 if (DevTy.hasValue()) { 18202 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host) 18203 OMPES = FunctionEmissionStatus::OMPDiscarded; 18204 else if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost || 18205 *DevTy == OMPDeclareTargetDeclAttr::DT_Any) { 18206 OMPES = FunctionEmissionStatus::Emitted; 18207 } 18208 } 18209 } else if (LangOpts.OpenMP) { 18210 // In OpenMP 4.5 all the functions are host functions. 18211 if (LangOpts.OpenMP <= 45) { 18212 OMPES = FunctionEmissionStatus::Emitted; 18213 } else { 18214 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18215 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18216 // In OpenMP 5.0 or above, DevTy may be changed later by 18217 // #pragma omp declare target to(*) device_type(*). Therefore DevTy 18218 // having no value does not imply host. The emission status will be 18219 // checked again at the end of compilation unit. 18220 if (DevTy.hasValue()) { 18221 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) { 18222 OMPES = FunctionEmissionStatus::OMPDiscarded; 18223 } else if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host || 18224 *DevTy == OMPDeclareTargetDeclAttr::DT_Any) 18225 OMPES = FunctionEmissionStatus::Emitted; 18226 } else if (Final) 18227 OMPES = FunctionEmissionStatus::Emitted; 18228 } 18229 } 18230 if (OMPES == FunctionEmissionStatus::OMPDiscarded || 18231 (OMPES == FunctionEmissionStatus::Emitted && !LangOpts.CUDA)) 18232 return OMPES; 18233 18234 if (LangOpts.CUDA) { 18235 // When compiling for device, host functions are never emitted. Similarly, 18236 // when compiling for host, device and global functions are never emitted. 18237 // (Technically, we do emit a host-side stub for global functions, but this 18238 // doesn't count for our purposes here.) 18239 Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD); 18240 if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host) 18241 return FunctionEmissionStatus::CUDADiscarded; 18242 if (!LangOpts.CUDAIsDevice && 18243 (T == Sema::CFT_Device || T == Sema::CFT_Global)) 18244 return FunctionEmissionStatus::CUDADiscarded; 18245 18246 // Check whether this function is externally visible -- if so, it's 18247 // known-emitted. 18248 // 18249 // We have to check the GVA linkage of the function's *definition* -- if we 18250 // only have a declaration, we don't know whether or not the function will 18251 // be emitted, because (say) the definition could include "inline". 18252 FunctionDecl *Def = FD->getDefinition(); 18253 18254 if (Def && 18255 !isDiscardableGVALinkage(getASTContext().GetGVALinkageForFunction(Def)) 18256 && (!LangOpts.OpenMP || OMPES == FunctionEmissionStatus::Emitted)) 18257 return FunctionEmissionStatus::Emitted; 18258 } 18259 18260 // Otherwise, the function is known-emitted if it's in our set of 18261 // known-emitted functions. 18262 return FunctionEmissionStatus::Unknown; 18263 } 18264 18265 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) { 18266 // Host-side references to a __global__ function refer to the stub, so the 18267 // function itself is never emitted and therefore should not be marked. 18268 // If we have host fn calls kernel fn calls host+device, the HD function 18269 // does not get instantiated on the host. We model this by omitting at the 18270 // call to the kernel from the callgraph. This ensures that, when compiling 18271 // for host, only HD functions actually called from the host get marked as 18272 // known-emitted. 18273 return LangOpts.CUDA && !LangOpts.CUDAIsDevice && 18274 IdentifyCUDATarget(Callee) == CFT_Global; 18275 } 18276